我正在开发一个程序,我应该检测同一类型的形状,并用不同的颜色给每种类型上色。
我用cv2.findCountours
然后cv2.approxPolyDP
来检测每个形状。
程序检测任何8个边为圆的形状,因此我决定添加一些检查-我使用cv2.contourArea
检查当前轮廓的面积,我还检查当前轮廓的cv2.minEnclosingCircle(cnt)
面积。
如果它们相等,我们就有一个圆。
import numpy as np
import cv2
img = cv2.imread('1.jpg')
gray = cv2.imread('1.jpg',0)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt, .03 * cv2.arcLength(cnt, True), True)
print len(approx)
if len(approx)==3:
print "triangle"
cv2.drawContours(img,[cnt],0,(122,212,78),-1)
elif len(approx)==4:
print "square"
cv2.drawContours(img,[cnt],0,(94,234,255),-1)
elif len(approx)==8:
area = cv2.contourArea(cnt)
(cx, cy), radius = cv2.minEnclosingCircle(cnt)
circleArea = radius * radius * np.pi
print circleArea
print area
if circleArea == area:
cv2.drawContours(img, [cnt], 0, (220, 152, 91), -1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
我打印了每一个区域,结果都不一样- 即使形状明显是圆形。
例如,对于同一个形状,minEnclosingCircle区域得到628.254637106,contour区域得到569。 另一个示例:2220.55512328用于minEnclosingCircle区域,2032.0用于contourmar区域。
我怎样才能正确计算这个面积?
我将感谢您的帮助!
我使用的图像:
以及检测到的形状:
我认为最好使用Hu矩检测圆:
https://en.wikipedia.org/wiki/Image_moment
可以使用opencv计算它们:
http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html
圆具有定义良好的力矩集:
https://users.cs.cf.ac.uk/Paul.Rosin/resources/papers/Hu-circularity-PR-postprint.pdf(第4页)
用这种方法定义的圆可以用来识别圆。
编辑:python中的Hu矩教程:
https://www.pyimagesearch.com/2014/10/27/opencv-shape-descriptor-hu-moments-example/
http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html
stackoverflow上的类似问题:
Shape recognition using Hu moments from OpenCV in Python
您应该检查计数器的凸度,而不是比较区域
您可以尝试使用属于每个blob的某些属性。偏心度,坚固度,紧密度。。特征可以帮助你区分形状。
你可以在下拉链接(但C++)中找到一些信息,给你一些提示< /p>
https://github.com/mribrahim/Blob-Detection
相关问题 更多 >
编程相关推荐