图像边缘检测算法python源代码
时间: 2025-01-06 21:25:49 浏览: 19
Python 实现 Canny 边缘检测
Canny边缘检测是一种多阶段的算法,能够有效地找到图像的真实弱边缘[^1]。下面展示的是利用Python和OpenCV库来实现Canny边缘检测的一个简单例子。
import cv2
import numpy as np
from matplotlib import pyplot as plt
def canny_edge_detection(image_path):
# 读取图片
img = cv2.imread(image_path, 0)
# 使用高斯滤波器平滑图像以减少噪声影响
blurred_img = cv2.GaussianBlur(img, (5, 5), 0)
# 应用Canny算子进行边缘检测
edges = cv2.Canny(blurred_img, threshold1=100, threshold2=200)
return edges
if __name__ == "__main__":
edge_image = canny_edge_detection('path_to_your_image.jpg')
# 显示原始图与边缘检测后的对比效果
fig, axs = plt.subplots(1, 2)
ax = axs.ravel()
ax[0].imshow(cv2.cvtColor(cv2.imread('path_to_your_image.jpg'), cv2.COLOR_BGR2RGB))
ax[0].set_title('Original Image')
ax[1].imshow(edge_image, cmap='gray')
ax[1].set_title('Edge Detected Image')
plt.show()
这段代码首先导入必要的包并定义了一个名为canny_edge_detection
的功能函数,该函数接收一张图片路径作为输入参数。接着通过调用OpenCV中的cv2.Canny()
方法执行实际的边缘检测工作,并返回处理过的二值化边缘映射结果。最后部分展示了如何加载测试图像以及可视化比较原图同经过边缘检测之后的效果图。
对于更复杂的场景下可能还需要调整Gaussian模糊程度(blur_size
)或是两个阈值(thresholds),这取决于具体应用场景的需求。
相关推荐


















