我正在研究一个程序,我应该检测相同类型的形状,并用不同颜色为每种类型着色。openCV:使用findContours检测圆圈
我使用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,contourArea面积为569。 另一个示例:minEnclosingCircle区域为2220.55512328,contourArea为2032.0。
如何正确计算此区域?
我会感谢任何帮助!检测
和形状:
我使用的图像
看看到[BLOB探测器(https://www.learnopencv.com/blob -detection-using-opencv-python-c /)它可以按面积,圆度,凸度过滤并正确选择一个圆。 – api55