读取图像computer.jpg及coins.jpg,基于Python实现基于霍夫变换的直线和圆检测,并显示原始图像及边缘图像python代码
时间: 2024-10-15 07:18:23 浏览: 34
Python实现霍夫圆和椭圆变换代码详解
5星 · 资源好评率100%
在Python中,我们可以使用OpenCV库来进行图像处理,包括霍夫变换(Hough Transform)来检测直线和圆形。首先,需要安装`opencv-python`库。以下是一个简单的示例,演示如何读取图像、边缘检测以及应用霍夫变换:
```python
import cv2
import numpy as np
# 读取图像
img1 = cv2.imread('computer.jpg')
img2 = cv2.imread('coins.jpg')
# 检查图像是否加载成功
if img1 is None or img2 is None:
print("图片无法加载")
else:
# 转换为灰度图像
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Canny边缘检测
edges1 = cv2.Canny(gray1, 50, 150) # 边缘阈值可以根据实际情况调整
edges2 = cv2.Canny(gray2, 50, 150)
# 对边缘图像应用霍夫变换寻找直线
lines1 = cv2.HoughLinesP(edges1, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=50)
lines2 = cv2.HoughLinesP(edges2, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=50)
# 对边缘图像应用霍夫变换寻找圆形
circles1 = cv2.HoughCircles(edges1, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0)
circles2 = cv2.HoughCircles(edges2, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 可视化结果
for line in lines1:
x1, y1, x2, y2 = line[0]
cv2.line(img1, (x1, y1), (x2, y2), (0, 255, 0), 2)
for circle in circles1:
if circle is not None and len(circle):
cv2.circle(img1, (circle[0][0], circle[0][1]), circle[0][2], (0, 0, 255), 2)
for line in lines2:
x1, y1, x2, y2 = line[0]
cv2.line(img2, (x1, y1), (x2, y2), (0, 255, 0), 2)
for circle in circles2:
if circle is not None and len(circle):
cv2.circle(img2, (circle[0][0], circle[0][1]), circle[0][2], (0, 0, 255), 2)
# 显示原始图像和检测后的图像
cv2.imshow("Computer Image with Lines", img1)
cv2.imshow("Coins Image with Circles", img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文