You can download this code by clicking the button below.
This code is now available for download.
OpenCV, NumPy, Gaussian blur, Hough transform
Technology Stack : OpenCV, NumPy, 高斯模糊, 霍夫变换
Code Type : The type of code
Code Difficulty : Advanced
import cv2
import numpy as np
def detect_and_draw_circles(image, min_radius=10, max_radius=100):
"""
Detect circles in an image and draw them on the original image.
"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=50, param1=50, param2=30, minRadius=min_radius, maxRadius=max_radius)
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(image, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
return image