Opencv-图像检测学习
立即下载
资源介绍:
图像检测学习
import cv2
import numpy as np
# 读取图片
image = cv2.imread('test.jpg')
# 将图片转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用高斯模糊减少噪声
blurred = cv2.GaussianBlur(gray, (9, 9), 0)
# 使用霍夫圆变换检测圆
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1, minDist=20,
param1=50, param2=30, minRadius=0, maxRadius=70)
# 初始化计数器
small_circle_count = 0
medium_circle_count = 0
# 确保至少找到一个圆
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
if 0 <= i[2] < 40: # 小圆
cv2.circle(image, (i[0], i[1]), i[2], (255, 0, 255), 2) # 紫色框小圆
small_circle_count += 1
elif 40 <= i[2] <= 50: # 中圆
cv2.circle(image, (i[0], i[1]), i[2], (0, 255, 0), 2) # 红色框中圆
medium_circle_count += 1
# 显示结果和统计数量
print(f"Detected {small_circle_count} small circles.")
print(f"Detected {medium_circle_count} medium circles.")
cv2.imshow('Detected Circles', image)
cv2.waitKey(0)
cv2.destroyAllWindows()