繁体   English   中英

如何使用opencv和python近似形状高度和宽度以进行图像检测

[英]how to aproximate shapes height and width for image detection using opencv and python

我正在关注一个关于使用opencv、numpy和python进行形状检测的教程,正是这个函数我知道它的原因,但我不知道如何修改它,所以我可以使用它,因为我希望气泡的总数是320但是函数检测 303 只有我试图修改这一行但我得到的最大值是 303 (len(approx) > 8 and w / h <= 1.1 and w / h >= 0.8) 我希望有人向我解释这个函数

这是代码

    def getOvalContours(self, adaptiveFrame):
    contours, hierarchy = cv2.findContours(adaptiveFrame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    ovalContours = []

    for contour in contours:
        approx = cv2.approxPolyDP(contour, 0, True)
        ret = 0
        x, y, w, h = cv2.boundingRect(contour)


        # eliminating not ovals by approx lenght
        if (len(approx) > 8 and w / h <= 1.1 and w / h >= 0.8):

            mask = np.zeros(adaptiveFrame.shape, dtype="uint8")
            cv2.drawContours(mask, [contour], -1, 255, -1)

            ret = cv2.matchShapes(mask, contour, 1, 0.0)

            if (ret < 1):
                ovalContours.append(contour)
                self.bubbleWidthAvr += w
                self.bubbleHeightAvr += h
    self.bubbleWidthAvr = self.bubbleWidthAvr / len(ovalContours)
    self.bubbleHeightAvr = self.bubbleHeightAvr / len(ovalContours)


    return ovalContours

这是图像在此处输入图像描述

这是在 Python/OpenCV 中使用 Hough Circles 的一种方法。

输入

在此处输入图像描述

import cv2
import numpy as np

# Read image
img = cv2.imread('multichoice_test.jpg')
hh, ww = img.shape[:2]

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# get Hough circles
min_dist = 30
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=20, minRadius=10, maxRadius=15)
print("circles:", circles)
print("")

# draw circles
img_circle = img.copy()
count = 0
for circle in circles[0]:
    # draw the circle in the output image, then draw a rectangle
    # corresponding to the center of the circle
    (x,y,r) = circle
    x = int(x)
    y = int(y)
    r = int(r)
    cv2.circle(img_circle, (x, y), r, (0, 0, 255), 1)
    count = count + 1

# print number of circles
print("number of circles:", count)

# save results
cv2.imwrite('multichoice_test_circles.jpg', img_circle)

# show images
cv2.imshow('circles', img_circle)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

在此处输入图像描述

number of circles: 320

此代码段尝试使用启发式规则检测小圆圈。 您可以稍微调整该值以获得所需的数字。 您还应该查看其他用于圆形检测的方法(例如Circle Hough Transform

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM