如果您只是要使用简单的图像,例如您的示例中的黑色背景,您可以使用相同的基本预处理/阈值,然后找到连接的组件。使用此示例代码在图像中的所有圆圈内绘制一个圆圈。
import cv2
import numpy as np
image = cv2.imread("image1.png")
# constants
BINARY_THRESHOLD = 20
CONNECTIVITY = 4
DRAW_CIRCLE_RADIUS = 4
# convert to gray
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# extract edges
binary_image = cv2.Laplacian(gray_image, cv2.CV_8UC1)
# fill in the holes between edges with dilation
dilated_image = cv2.dilate(binary_image, np.ones((5, 5)))
# threshold the black/ non-black areas
_, thresh = cv2.threshold(dilated_image, BINARY_THRESHOLD, 255, cv2.THRESH_BINARY)
# find connected components
components = cv2.connectedComponentsWithStats(thresh, CONNECTIVITY, cv2.CV_32S)
# draw circles around center of components
#see connectedComponentsWithStats function for attributes of components variable
centers = components[3]
for center in centers:
cv2.circle(thresh, (int(center[0]), int(center[1])), DRAW_CIRCLE_RADIUS, (255), thickness=-1)
cv2.imwrite("res.png", thresh)
cv2.imshow("result", thresh)
cv2.waitKey(0)
这是生成的图像:
编辑:connectedComponentsWithStats 将二进制图像作为输入,并返回该图像中连接的像素组。如果您想自己实现该功能,天真的方法是:
1- 从左上角到右下角扫描图像像素,直到遇到没有标签 (id) 的非零像素。
2-当您遇到非零像素时,递归搜索其所有邻居(如果您使用 4 个连接,则检查 UP-LEFT-DOWN-RIGHT,使用 8 个连接,您还检查对角线),直到完成该区域。为每个像素分配一个标签。增加标签计数器。
3- 从您离开的地方继续扫描。