我正在使用HoughCircles,并且可以很好地处理灰度图像,尝试使用二进制文件仍然可以按预期工作。在我使用FloodFill仅检测图像的内圆之后,HoughCircles返回一个空数组。我的代码在这里工作:
import cv2
import numpy as np
# Read image.
img = cv2.imread('terminales.webp', cv2.IMREAD_COLOR)
# Convert to grayscale.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur using 3 * 3 kernel.
gray_blurred = cv2.blur(gray, (3, 3))
ret,binary_img = cv2.threshold(gray_blurred,220,255,cv2.THRESH_BINARY_INV)
# Copy the thresholded image.
im_floodfill = binary_img.copy()
# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h, w = binary_img.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
# Floodfill from point (0, 0)
cv2.floodFill(im_floodfill, mask, (0,0), 255);
# Invert floodfilled image
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
# Combine the two images to get the foreground.
im_out = binary_img | im_floodfill_inv
# Apply Hough transform on the blurred image.
detected_circles = cv2.HoughCircles(binary_img,
cv2.HOUGH_GRADIENT, 1, 1, param1 = 50,
param2 = 30, minRadius = 10, maxRadius = 150)
# Draw circles that are detected.
if detected_circles is not None:
# Convert the circle parameters a, b and r to integers.
detected_circles = np.uint16(np.around(detected_circles))
for pt in detected_circles[0, :]:
a, b, r = pt[0], pt[1], pt[2]
# Draw the circumference of the circle.
cv2.circle(img, (a, b), r, (0, 255, 0), 2)
# Draw a small circle (of radius 1) to show the center.
cv2.circle(img, (a, b), 1, (0, 0, 255), 3)
else:
print("Nothing detected")
cv2.imshow("Detected Circle", img)
cv2.waitKey(0)
如果我在HoughCircle中使用“ im_floodfill”,“ im_out”或“ im_floodfill_inv”而不是“ binary_img”,则不会得到任何结果。我不知道我是否缺少无法完成的事情。
我能够检测到一些减少参数2并增加minDist的东西。
detected_circles_inner = cv2.HoughCircles(im_floodfill,
cv2.HOUGH_GRADIENT, 1, 30, param1 = 50,
param2 = 15, minRadius = 10, maxRadius = 150)