OpenCV Python 轮廓近似

OpenCV Python Contour Approximation

我想在数字仪表中检测一个矩形形状,检测形状轮廓近似,但找不到矩形的准确轮廓。我不知道错误在哪里。请看一下建议

digitalMeter.jpg

required-Output-digitalMeter-contour

    import imutils
    import cv2
    
   
    image = cv2.imread('C:\digitalMeter.jpg')
    
    image = imutils.resize(image, height=500)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edged = cv2.Canny(blurred, 50, 200, 255)
    
    
        cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
        displayCnt = None
        
       
        for c in (cnts):
            peri = cv2.arcLength(c, True)
            approx = cv2.approxPolyDP(c, 0.02 * peri, True)
          
            if len(approx) == 4:
                print(displayCnt)[enter image description here][2]
                displayCnt = approx
                break
        
        cv2.drawContours(image, [displayCnt], -1, (0, 230, 255), 6)
        cv2.imshow('cnts', image)
        cv2.waitKey(0)

这是 Python/OpenCV 中的一种方法。

  • 读取输入
  • 转换为灰色
  • 阈值
  • 应用形态学清理阈值图像
  • 反转,使仪表在黑色背景上显示为白色
  • 找到轮廓并提取最大(实际上只有)的轮廓
  • 在输入图像上绘制轮廓
  • 保存结果

输入:

import cv2
import numpy as np

# read image
img = cv2.imread('digital_meter.jpg')
hh, ww = img.shape[:2]

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray,30,255,cv2.THRESH_BINARY)[1]

# apply close and open morphology
kernel = np.ones((3,3), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((11,11), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# invert
mask = 255 - mask

# get largest contour
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# draw green contour on input
contour_img = img.copy()
cv2.drawContours(contour_img,[big_contour],0,(0,255,0),2)

# save cropped image
cv2.imwrite('digital_meter_thresh.png',thresh)
cv2.imwrite('digital_meter_mask.png',mask)
cv2.imwrite('digital_meter_contour.png',contour_img)
    
# show the images
cv2.imshow("THRESH", thresh)
cv2.imshow("MASK", mask)
cv2.imshow("CONTOUR", contour_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像:

形态学清洗和倒置图像:

输入的结果轮廓: