如何忽略轮廓检测的图像区域,OpenCV

问题描述

--原图供参考---

enter image description here

原图供参考

enter image description here

Original Image

您好 OpenCV 专业用户

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

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

任何提示都会有所帮助,提前致谢.. :)

enter image description here

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,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),3)
                    coordinates_dict["vertical"]=y+h
                elif w>150 and h<24:
                    has_hori_mask = True
                    cv2.rectangle(img_color,255,0),3)
                    coordinates_dict["horizontal"]=y+h

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

enter image description here

解决方法

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

# 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,-1,(0,255),3)

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

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

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

enter image description here

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...