使用Open CV检测基本形状

时间:2014-08-14 10:28:49

标签: python opencv numpy

我正在研究一种使用Python中的开放式CV从图像中检测基本形状的方法。

这是我用来检测基本图像的代码,它起作用:

import numpy as np
import cv2
import webbrowser

img = cv2.imread('test3.png')
gray = cv2.imread('test3.png',0)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True), True)
    print len(approx)
    if len(approx)==5:
    print "It's a pentagon = mortgages."
    webbrowser.open('http://www.google.co.uk')
    #cv2.drawContours(img,[cnt],0,255,-1)
elif len(approx)==3:
    print "triangle"
    cv2.drawContours(img,[cnt],0,(0,255,0),-1)
elif len(approx)==4:
    print "square"
    cv2.drawContours(img,[cnt],0,(0,0,255),-1)
elif len(approx) == 9:
    print "half-circle"
    cv2.drawContours(img,[cnt],0,(255,255,0),-1)
elif len(approx) > 15:
    print "circle"
    cv2.drawContours(img,[cnt],0,(0,255,255),-1)

#cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

然而,它输出结果两次。任何建议或示例来纠正它将非常感激。

1 个答案:

答案 0 :(得分:0)

如果您只想检索对象的外部轮廓,请将适当的标记添加到cv2.findContours

contours,h = cv2.findContours(thresh,cv2.RETR_EXTERNAL,2)

否则它可以为每个形状返回多个轮廓,因此在for循环中重复结果。

希望它有所帮助。

相关问题