gpt4 book ai didi

python - 在openCV中检测圆

转载 作者:行者123 更新时间:2023-12-01 23:00:04 25 4
gpt4 key购买 nike

我在为 HoughCircles 函数选择正确的参数时遇到问题。我尝试从视频中检测圆圈。这个圆圈是我做的,尺寸几乎相同。问题是相机正在移动。

当我更改 maxRadius 时,它仍然以某种方式检测到更大的圆圈(参见右图)。我也尝试更改param1,param2但仍然没有成功。 Left-original picture, Right - after blur and detected circles

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.medianBlur(gray, 25)#cv2.bilateralFilter(gray,10,50,50)


minDist = 100
param1 = 500
param2 = 200#smaller value-> more false circles
minRadius = 5
maxRadius = 10
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1, minDist, param1, param2, minRadius, maxRadius)

if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
cv2.circle(blurred,(i[0], i[1]), i[2], (0, 255, 0), 2)

也许我使用了错误的函数?

最佳答案

不必使用cv2.HoughCircles来选择正确的参数,这里有一种使用轮廓过滤的替代方法。这个想法是获得一个带有 Otsu's threshold 的二值图像。然后执行morphological operations隔离椭圆形轮廓。最后我们find contours并使用 aspect ratio 进行过滤和 contour area 。结果如下:

enter image description here

import cv2
import numpy as np

# Load image, grayscale, median blur, Otsus threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray, 11)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Morph open
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)

# Find contours and filter using contour area and aspect ratio
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
area = cv2.contourArea(c)
if len(approx) > 5 and area > 1000 and area < 500000:
((x, y), r) = cv2.minEnclosingCircle(c)
cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 2)

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()

关于python - 在openCV中检测圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60637120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com