我建议使用OpenCV findContours()
像这样:
#!/usr/bin/env python3
import numpy as np
import cv2
# Load image
im = cv2.imread('pattern.png')
# Convert to grayscale
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
# Find contours, draw on image and save
im2, contours, hierarchy = cv2.findContours(imgray,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im, contours, -1, (0,0,255), 3)
# Show user what we found
i=0
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
print('Contour {}: x={}, y={}, w={}, h={}'.format(i,x,y,w,h))
i = i+1
# Save the result
cv2.imwrite('result.png',im)
样本输出
Contour 0: x=1743, y=903, w=77, h=77
Contour 1: x=1552, y=903, w=77, h=77
Contour 2: x=291, y=903, w=77, h=77
Contour 3: x=100, y=903, w=77, h=77
Contour 4: x=1648, y=808, w=77, h=77
Contour 5: x=196, y=808, w=77, h=77
Contour 6: x=1743, y=712, w=77, h=77
Contour 7: x=291, y=712, w=77, h=77
Contour 8: x=100, y=712, w=77, h=77
Contour 9: x=1551, y=711, w=78, h=78
Contour 10: x=1017, y=597, w=77, h=77
Contour 11: x=826, y=597, w=77, h=77
Contour 12: x=922, y=502, w=77, h=77
Contour 13: x=1017, y=406, w=77, h=77
Contour 14: x=826, y=406, w=77, h=77
Contour 15: x=1743, y=291, w=77, h=77
Contour 16: x=1552, y=291, w=77, h=77
Contour 17: x=291, y=291, w=77, h=77
Contour 18: x=100, y=291, w=77, h=77
Contour 19: x=1648, y=196, w=77, h=77
Contour 20: x=196, y=196, w=77, h=77
Contour 21: x=1743, y=100, w=77, h=77
Contour 22: x=1552, y=100, w=77, h=77
Contour 23: x=291, y=100, w=77, h=77
Contour 24: x=100, y=100, w=77, h=77
请注意,这并不是专门寻找您的图案,它只是寻找黑色背景上的白色物体。这有优点也有缺点。优点是它适用于任何白色形状(圆形、星形、八边形),而无需更改代码。它也可能比模板匹配更快。缺点是,如果图像中存在其他白色物体,它会给您带来误报 - 尽管您可以检查形状、圆形、颜色或其他内容来确认/消除歧义。