pythonimport cv2import numpy as npimport matplotlib.pyplot as plt# 1. 环境验证(可选)print("OpenCV版本:", cv2.__version__)# 2. 读取图像(替换为自己的图像路径)img = cv2.imread("hough_test.jpg", 0)if img is None:print("错误:未找到图像,请检查图像路径!")else:# 3. 图像预处理(高斯平滑+边缘检测)img_blur = cv2.GaussianBlur(img, (5, 5), sigmaX=1)edges = cv2.Canny(img_blur, 50, 150)# 4. 霍夫线变换lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180,threshold=50,minLineLength=50,maxLineGap=10)# 5. 霍夫圆变换circles = cv2.HoughCircles(image=img_blur,method=cv2.HOUGH_GRADIENT,dp=1.5,minDist=50,param1=100,param2=30,minRadius=20,maxRadius=80)# 6. 绘制检测结果(分别绘制线、圆,以及综合结果)# 绘制直线img_lines = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)if lines is not None:for line in lines:x1, y1, x2, y2 = line[0]cv2.line(img_lines, (x1, y1), (x2, y2), (0, 0, 255), 2)# 绘制圆形img_circles = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)if circles is not None:circles = np.uint16(np.around(circles))for circle in circles[0, :]:x, y, r = circlecv2.circle(img_circles, (x, y), r, (255, 0, 0), 2)cv2.circle(img_circles, (x, y), 3, (0, 0, 255), -1)# 综合绘制(线+圆)img_combined = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)if lines is not None:for line in lines:x1, y1, x2, y2 = line[0]cv2.line(img_combined, (x1, y1), (x2, y2), (0, 0, 255), 2)if circles is not None:circles = np.uint16(np.around(circles))for circle in circles[0, :]:x, y, r = circlecv2.circle(img_combined, (x, y), r, (255, 0, 0), 2)cv2.circle(img_combined, (x, y), 3, (0, 0, 255), -1)# 7. 统一显示所有效果plt.figure(figsize=(15, 10))# 第一行:原始图、边缘图plt.subplot(2, 3, 1)plt.imshow(img, cmap="gray")plt.title("原始图像")plt.axis("off")plt.subplot(2, 3, 2)plt.imshow(edges, cmap="gray")plt.title("边缘检测图像")plt.axis("off")# 第二行:直线检测、圆形检测、综合检测plt.subplot(2, 3, 4)plt.imshow(cv2.cvtColor(img_lines, cv2.COLOR_BGR2RGB))plt.title(f"霍夫线变换({len(lines) if lines is not None else 0}条直线)")plt.axis("off")plt.subplot(2, 3, 5)plt.imshow(cv2.cvtColor(img_circles, cv2.COLOR_BGR2RGB))plt.title(f"霍夫圆变换({len(circles[0]) if circles is not None else 0}个圆形)")plt.axis("off")plt.subplot(2, 3, 6)plt.imshow(cv2.cvtColor(img_combined, cv2.COLOR_BGR2RGB))plt.title("综合检测结果(线+圆)")plt.axis("off")plt.tight_layout()plt.show()# 8. 保存结果(可选)cv2.imwrite("hough_lines.jpg", img_lines)cv2.imwrite("hough_circles.jpg", img_circles)cv2.imwrite("hough_combined.jpg", img_combined) |