【问题标题】:OpenCV Python Contour ApproximationOpenCV Python 轮廓逼近
【发布时间】:2020-07-31 00:34:37
【问题描述】:

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

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)

【问题讨论】:

    标签: opencv-contour


    【解决方案1】:

    这是在 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()
    

    阈值图像:

    形态清洁和倒置图像:

    输入的结果轮廓:

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多