python - 使用 opencv 检测和计数 blob/连接对象
问题描述
我想检测和计算图像中触摸的对象,同时忽略可能被视为单个对象的对象。我有基本图像,我尝试在其上应用一种cv2.HoughCircles()
方法来尝试识别一些圆圈。然后我解析了返回的数组并尝试使用cv2.circle()
在图像上绘制它们。
但是,我似乎总是得到太多的圆圈返回,cv2.HoughCircles()
无法弄清楚如何只计算接触的物体。
到目前为止我的代码:
import numpy
import matplotlib.pyplot as pyp
import cv2
segmentet = cv2.imread('photo')
houghCircles = cv2.HoughCircles(segmented, cv2.HOUGH_GRADIENT, 1, 80, param1=450, param2=10, minRadius=30, maxRadius=200)
houghArray = numpy.uint16(houghCircles)[0,:]
for circle in houghArray:
cv2.circle(segmented, (circle[0], circle[1]), circle[2], (0, 250, 0), 3)
我怎样才能正确识别和计算所述对象?
解决方案
这是 Python OpenCV 中的一种方法,通过获取轮廓区域和轮廓的凸包区域。取比率 (area/convex_hull_area)。如果足够小,那么它就是一团斑点。否则它是一个孤立的 blob。
输入:
import cv2
import numpy as np
# read input image
img = cv2.imread('blobs_connected.jpg')
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold to binary
thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]
# find contours
#label_img = img.copy()
contour_img = img.copy()
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
index = 1
isolated_count = 0
cluster_count = 0
for cntr in contours:
area = cv2.contourArea(cntr)
convex_hull = cv2.convexHull(cntr)
convex_hull_area = cv2.contourArea(convex_hull)
ratio = area / convex_hull_area
#print(index, area, convex_hull_area, ratio)
#x,y,w,h = cv2.boundingRect(cntr)
#cv2.putText(label_img, str(index), (x,y), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255), 2)
if ratio < 0.91:
# cluster contours in red
cv2.drawContours(contour_img, [cntr], 0, (0,0,255), 2)
cluster_count = cluster_count + 1
else:
# isolated contours in green
cv2.drawContours(contour_img, [cntr], 0, (0,255,0), 2)
isolated_count = isolated_count + 1
index = index + 1
print('number_clusters:',cluster_count)
print('number_isolated:',isolated_count)
# save result
cv2.imwrite("blobs_connected_result.jpg", contour_img)
# show images
cv2.imshow("thresh", thresh)
#cv2.imshow("label_img", label_img)
cv2.imshow("contour_img", contour_img)
cv2.waitKey(0)
红色簇,绿色孤立斑点:
文字信息:
number_clusters: 4
number_isolated: 81
推荐阅读
- python - 如何在 Windows 上使用多个进程为 Flask 应用程序提供服务
- file-upload - 将大文件从多个端点上传到云存储的架构
- r - 我的任务说它完成了,但实际上没有
- ruby - 由于使用 ARGV 而不是 .gets,RSpec 测试失败
- visual-studio-debugging - 无法进入 PresentationFramework
- scala - TwitterServer (Finch/Finagle) 似乎阻止了 api 调用,直到它完成计算
- javascript - 如何循环 Angular FormArray - 当前设置为循环中的最后一项
- google-cloud-data-fusion - Google Cloud Data Fusion - Dataproc 配置突然停止,没有任何错误消息
- c++ - 三角形位置的颜色
- javascript - 如何在 Javascript 中获取地图数组以在下拉列表中打印