簡體   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