一旦你从cv2.findContours()
获取了两个轮廓,你可以使用按位AND
操作来检测它们是否相交。具体来说,我们可以使用np.logical_and()
。思路是为每个轮廓创建两个单独的图像,然后在它们上面使用逻辑AND
操作。任何具有正值(1
或True
)的点都是相交点。因此,由于你只需要获得是否存在相交的布尔值,我们可以检查相交的图像是否有单个正值。基本上,如果整个数组为False
,则表示轮廓之间没有相交。但如果有一个单独的True
,那么轮廓就接触并且相交。
def contourIntersect(original_image, contour1, contour2):
contours = [contour1, contour2]
blank = np.zeros(original_image.shape[0:2])
image1 = cv2.drawContours(blank.copy(), [contours[0]], 0, 1)
image2 = cv2.drawContours(blank.copy(), [contours[1]], 1, 1)
intersection = np.logical_and(image1, image2)
return intersection.any()
示例
原始图像
检测到的轮廓
现在我们将这两个检测到的轮廓传递给该函数并获取此交集数组:
[[False False False ... False False False]
[False False False ... False False False]
[False False False ... False False False]
...
[False False False ... False False False]
[False False False ... False False False]
[False False False ... False False False]]
我们检查intersection
数组,看看是否存在True
。当轮廓相交时,我们将获得True
或1
,而当它们不相交时,将获得False
或0
。
return intersection.any()
因此,我们得到
错误的
完整代码
import cv2
import numpy as np
def contourIntersect(original_image, contour1, contour2):
contours = [contour1, contour2]
blank = np.zeros(original_image.shape[0:2])
image1 = cv2.drawContours(blank.copy(), contours, 0, 1)
image2 = cv2.drawContours(blank.copy(), contours, 1, 1)
intersection = np.logical_and(image1, image2)
return intersection.any()
original_image = cv2.imread("base.png")
image = original_image.copy()
cv2.imshow("original", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
blurred = cv2.GaussianBlur(gray, (5,5), 0)
cv2.imshow("blur", blurred)
threshold = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
cv2.imshow("thresh", threshold)
contours = cv2.findContours(threshold.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[1] if len(contours) == 3 else contours[0]
contour_list = []
for c in contours:
contour_list.append(c)
cv2.drawContours(image, [c], 0, (0,255,0), 2)
print(contourIntersect(original_image, contour_list[0], contour_list[1]))
cv2.imshow("contour", image)
cv2.waitKey(0)