【问题标题】:Improve rectangle contour detection in image using OpenCV使用 OpenCV 改进图像中的矩形轮廓检测
【发布时间】:2019-11-29 05:46:31
【问题描述】:

我正在尝试检测给定图像中的矩形框

原图: 但是图像不足以检测矩形,我该如何改进它并检测图像中的所有矩形?

我尝试使用canny边缘检测和应用膨胀,双边滤波器将图像转换为二进制图像,然后输出是这样的:

我尝试应用所有的morphologyEx, sobel 然后我无法检测到图像中的所有矩形。如果我能够找到矩形的所有边界,那么我可以使用 find countours 检测所有矩形,但是如何改进图像以检测所有矩形。

下面给出了给定转换的代码

img =  cv2.imread("givenimage.png",0)
img = cv2.resize(img,(1280,720))
edges = cv2.Canny(img,100,200)
kernal = np.ones((2,2),np.uint8)
dilation = cv2.dilate(edges, kernal , iterations=2)
bilateral = cv2.bilateralFilter(dilation,9,75,75)
contours, hireracy = cv2.findContours(bilateral,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i,contour in enumerate(contours):
    approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour,True),True)   
    if len(approx) ==4:
        X,Y,W,H = cv2.boundingRect(approx)
        aspectratio = float(W)/H
        if aspectratio >=1.2 :
            box = cv2.rectangle(img, (X,Y), (X+W,Y+H), (0,0,255), 2)
            cropped = img[Y: Y+H, X: X+W]
            cv2.drawContours(img, [approx], 0, (0,255,0),5)
            x = approx.ravel()[0]
            y = approx.ravel()[1]
            cv2.putText(img, "rectangle"+str(i), (x,y),cv2.FONT_HERSHEY_COMPLEX, 0.5, (0,255,0))
cv2.imshow("image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

以下程序的输出仅检测到 8 个矩形:

但我需要检测图像中存在的所有矩形

1)我可以增加图像中所有黑色像素的厚度吗:

2)我可以扩大白色边界之间的所有像素区域

【问题讨论】:

    标签: python image opencv image-processing computer-vision


    【解决方案1】:

    这是一个简单的方法:

    • 将图像转换为灰度和高斯模糊
    • 执行精确边缘检测
    • 查找轮廓并绘制矩形

    Canny 边缘检测

    结果

    import cv2
    
    image = cv2.imread('1.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (3, 3), 0)
    canny = cv2.Canny(blurred, 120, 255, 1)
    
    # Find contours
    cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    # Iterate thorugh contours and draw rectangles around contours
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
    
    cv2.imshow('canny', canny)
    cv2.imshow('image', image)
    cv2.imwrite('canny.png', canny)
    cv2.imwrite('image.png', image)
    cv2.waitKey(0)
    

    【讨论】:

      【解决方案2】:

      您的想法是对的,但在第一阶段您可以使用threshold 操作。然后找到轮廓。然后minAreaRect对已建立的轮廓进行操作。

      编辑:

      结果和代码(c++):

      Mat img = imread("/Users/alex/Downloads/MyPRI.png", IMREAD_GRAYSCALE);
      Mat img2;
      threshold(img, img2, 220, 255, THRESH_BINARY);
      
      Mat element = getStructuringElement(MORPH_CROSS, Size(3, 3), Point(1, 1));
      erode(img2, img2, element); // without it find contours fails on some rects
      
      imshow("img", img);
      imshow("img2", img2);
      waitKey();
      
      
      // preprocessing done, search rectanges
      vector<vector<Point> > contours;
      
      vector<Vec4i> hierarchy;
      findContours(img2, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
      
      vector<RotatedRect> rects;
      for (int i = 0; i < contours.size(); i++) {
          if (hierarchy[i][2] > 0) continue;
      
          // capture inner contour
          RotatedRect rr = minAreaRect(contours[i]);
          if (rr.size.area() < 100) continue; // too small
      
          rr.size.width += 8;
          rr.size.height += 8; // expand to outlier rect if needed
          rects.push_back(rr);
      }
      
      
      Mat debugImg;
      cvtColor(img, debugImg, CV_GRAY2BGR);
      for (RotatedRect rr : rects) {
          Point2f points[4];
          rr.points(points);
          for (int i = 0; i < 4; i++) {
              int ii = (i + 1) % 4;
              line(debugImg, points[i], points[ii], CV_RGB(255, 0, 0), 2);
          }
      }
      imshow("debug", debugImg);
      waitKey();
      

      【讨论】:

      • 使用阈值操作后,我在图像边界丢失了很多像素,如二进制图像所示。有什么办法可以在不使用膨胀的情况下加入这两个像素?
      猜你喜欢
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2015-07-16
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多