【问题标题】:How to ignore a image region for contour detection, OpenCV如何忽略图像区域进行轮廓检测,OpenCV
【发布时间】:2021-04-13 21:54:22
【问题描述】:

--参考原图-- 原图供参考

OpenCV 专业用户您好!

我正在研究一个用例来检测矩形轮廓并提取它们以在此类图像中进行分析

我想忽略图像中这1个区域(标记为黄色),因为它不需要,如何在使用轮廓检测​​时忽略该区域?

任何提示都会有所帮助,在此先感谢.. :)

def getContours(img_name, img, img_color):
    
    FLAG = 200
    _, contours, hierachy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    has_Mask =False
    has_hori_mask = False
    has_vertical_mask = False
    
    coordinates_dict = {}
    
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 1000:
            #cv2.drawContours(imgContour, cnt, -1, (0,0,255), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02*peri,True)
            if len(approx)==4: # only interested in squares/rectangles
                has_Mask = True
                objCorner = 4
                x, y, w, h = cv2.boundingRect(approx)
                if h>150 and w<40:
                    has_vertical_mask = True
                    cv2.rectangle(img_color, (x,y), (x+w, y+h), (0,0,255), 3)
                    coordinates_dict["vertical"]=y+h
                elif w>150 and h<24:
                    has_hori_mask = True
                    cv2.rectangle(img_color, (x,y), (x+w, y+h), (0,255,0), 3)
                    coordinates_dict["horizontal"]=y+h

    # save the image
    cv2.imwrite(os.path.join(validation_folder, img_name), img_color)

【问题讨论】:

  • 这些区域与顶部/底部的距离是否相同?
  • 是的,它与顶部和底部的距离相同
  • 所有图片?
  • 是的,所有的图像..
  • 太好了,您能否也将您的原始图像(不带标记)添加到问题中?

标签: python opencv image-processing opencv-contour


【解决方案1】:

由于您的图像始终在顶部具有相同的边距,因此您可以在检测过程中排除该图像区域:

# margin in pixels
top_margin = 85

src = cv2.imread('test.jpg')
src_cropped = src[top_margin:src.shape[0], :]
src_gray = cv2.cvtColor(src_cropped, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(src_gray, 127, 255, cv2.THRESH_BINARY_INV)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(src_cropped, contours, -1, (0,0,255), 3)

然后您可以将其应用于原始图像,以在整个图像的裁剪区域中获取边界框:

src[top_margin:src.shape[0], :] = src_cropped

绘制所有轮廓时得到以下结果:

如果将其与约束一起应用,它应该会消除顶部不需要的轮廓。

【讨论】:

  • 如何通过设置底部边距来裁剪底部?我试过:img= img[:, bottom_margin:img.shape[0]] 但输出不如预期我已经更新了图像.. 供您参考
  • @Arjun 如果你想从顶部和底部裁剪边距,你可以使用img[top_margin:src.shape[0]-bottom_margin,:]
猜你喜欢
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多