openCV:使用findContours检测圆

2024-06-07 12:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个程序,我应该检测同一类型的形状,并用不同的颜色给每种类型上色。

我用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区域。

我怎样才能正确计算这个面积?

我将感谢您的帮助!

我使用的图像:

以及检测到的形状:


Tags: 程序区域imglenareacv2形状print
3条回答

您应该检查计数器的凸度,而不是比较区域

elif len(approx)==8:
        k=cv2.isContourConvex(approx)
        if k:
        #now you select a circle

您可以尝试使用属于每个blob的某些属性。偏心度,坚固度,紧密度。。特征可以帮助你区分形状。

你可以在下拉链接(但C++)中找到一些信息,给你一些提示< /p>

https://github.com/mribrahim/Blob-Detection

相关问题 更多 >

    热门问题