概念
检测图像中是否存在形状相交的一种简单方法,假设每个形状都必须是不同的颜色,您可以为每种颜色定义一个遮罩,并且图像的颜色全部被遮盖,除了带有其颜色的形状,检测为形状轮廓找到的轮廓数量。
如果找到多个轮廓(大于指定数量的区域以滤除噪声),这意味着另一个形状的轮廓与该形状的轮廓相交,在其轮廓中留下间隙,因此导致多个轮廓。
代码
import cv2
import numpy as np
def intersected(img, masks):
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
for lower, upper in masks:
mask = cv2.inRange(img_hsv, np.array(lower), np.array(upper))
blur = cv2.GaussianBlur(mask, (5, 5), 0)
canny = cv2.Canny(blur, 0, 0)
contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
count = 0
for cnt in contours:
if cv2.contourArea(cnt) > 50:
cv2.drawContours(img, [cnt], -1, (0, 255, 0), 1)
cv2.imshow("Test", img)
count += 1
if count == 2:
return True
img = cv2.imread("shapes.png")
blue_mask = [1, 0, 0], [178, 255, 255]
red_mask = [0, 1, 0], [179, 254, 255]
if intersected(img, (blue_mask, red_mask)):
print("Intersection detected!")
else:
print("No intersection detected.")
输出
Intersection detected!
解释
- 导入必要的库:
import cv2
import numpy as np
- 定义一个接受 2 个参数的函数;我们将检测的图像是否存在形状交叉点,以及每个形状颜色的 HSV 掩码数组:
def intersected(img, masks):
- 获取 HSV 形式的图像,并遍历每个 HSV 掩码:
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
for lower, upper in masks:
mask = cv2.inRange(img_hsv, np.array(lower), np.array(upper))
- 模糊遮罩以去除噪声,使用 canny 边缘检测器检测其边缘,并找到 canny 边缘的轮廓:
blur = cv2.GaussianBlur(mask, (5, 5), 0)
canny = cv2.Canny(blur, 0, 0)
contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
- 定义一个变量
count,以存储面积大于50 的等高线数量,目前已找到。如果count 变量达到2,我们就知道至少找到了一个交叉点,这足以确认图像中有交叉点:
count = 0
for cnt in contours:
if cv2.contourArea(cnt) > 50:
cv2.drawContours(img, [cnt], -1, (0, 255, 0), 1)
cv2.imshow("Test", img)
count += 1
if count == 2:
return True
- 最后,我们可以利用图像上的功能:
img = cv2.imread("shapes.png")
blue_mask = [1, 0, 0], [178, 255, 255]
red_mask = [0, 1, 0], [179, 254, 255]
if intersected(img, (blue_mask, red_mask)):
print("Intersection detected!")
else:
print("No intersection detected.")