首页 > 解决方案 > 找到矩形内部角点

问题描述

我有一个如下所示的二进制图像,我必须在其中找到矩形的内部角点。我尝试使用OpenCV findcontours函数来获取矩形边界,然后是角点,但它没有提供我正在寻找的确切点位置(它提供了外部角点)。有解决问题的想法或方法吗? 输入

标签: opencvimage-processing

解决方案


如评论中所述,您需要使用cv2.RETR_CCOMP. 以下实现在python中:

img = cv2.imread(os.path.join(r'C:\Users\Jackson\Desktop\stack\contour', FILE_NAME))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Don't use magic numbers
thresh = cv2.threshold(gray, thresh=BLACK_THRESHOLD, maxval=255, type=cv2.THRESH_BINARY)[1]

#--- Find the contours ---
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

#--- get hierarchy descriptions ---
print(hierarchy)

返回:

[[-1 -1  1 -1]
 [-1 -1 -1  0]]

这是什么意思?

层次结构有助于在轮廓之间建立父子关系。子轮廓是外部轮廓内的轮廓,也称为父轮廓。

层次结构返回具有以下含义的数组:

[下一个、上一个、First_Child、父]

这份文档对这个主题有很多启发。

#--- creating a copy of original image ---
img2 = img.copy()

#--- checking whether the contour in hierarchy is a child and if it is then draw it ---
for i in hierarchy:
    print(i)
    if i[2] > 0:      
        cv2.drawContours(img2, [contours[i[2]]], 0, (0,255,0), 2)

cv2.imshow('img2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

在此处输入图像描述


推荐阅读