-1
我正在研究一个程序,我应该检测形状 - 圆形,正方形和traingles - 并用不同的颜色为每种类型着色。openCV:无法正确检测形状使用findContours
我使用cv2.findCountours,然后cv2.approxPolyDP来检测每个形状。
这是我的代码:
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, 0.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:
k = cv2.isContourConvex(approx)
if k:
cv2.drawContours(img, [cnt], 0, (220, 152, 91), -1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
它检测到我所提到的形状,但它检测以及形状,这是不是圆/三角形/平方米,并提出他们,因为他们是。
这是我所使用的图像:1
输出:2
任何建议如何解决这个问题呢? 我可以添加哪些考试?
谢谢!