如果您正在使用 OpenCV 3.0,我建议您看看connectedComponentsWithStats
功能。
另外,下面的代码片段通过打开和关闭来清理图像,然后找到轮廓。然后绘制轮廓和轮廓中心。
# Create a kernel
kernel = np.ones((7,7),np.uint8)
# Use opening to fill the blobs
opened = cv2.morphologyEx(th3, cv2.MORPH_OPEN, kernel)
# Use closing to disconnect the bridges
closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)
# Create a color image to show the result
new_img = cv2.cvtColor(closed, cv2.COLOR_GRAY2BGR)
# Invert the image
closed=255-closed
# Find contours
contours, hierarchy = cv2.findContours(closed, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
# Skip if the contour area is small
area = cv2.contourArea(cnt)
if area < 500:
continue
# Draw the contour
cv2.drawContours(new_img, [cnt], -1, (0, 255, 0), 2)
# Find the center
M = cv2.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# Draw the center
cv2.circle(new_img, (cX, cY), 7, (0, 0, 255), -1)
cv2.imwrite("result.png",new_img)
我得到了以下结果,希望这是您所描述的,并希望它也适合您。