写一个边缘检测算法的代码
时间: 2023-05-20 07:00:42 浏览: 114
以下是一个简单的边缘检测算法的代码,使用Sobel算子:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg', 0)
# Sobel算子
sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
# 计算梯度幅值和方向
grad = np.sqrt(sobel_x**2 + sobel_y**2)
grad = np.uint8(grad)
theta = np.arctan2(sobel_y, sobel_x)
# 非极大值抑制
rows, cols = img.shape
for i in range(1, rows-1):
for j in range(1, cols-1):
if (theta[i,j] >= -np.pi/8 and theta[i,j] < np.pi/8) or (theta[i,j] >= 7*np.pi/8 and theta[i,j] <= np.pi) or (theta[i,j] >= -np.pi and theta[i,j] < -7*np.pi/8):
if grad[i,j] < grad[i,j-1] or grad[i,j] < grad[i,j+1]:
grad[i,j] = 0
elif (theta[i,j] >= np.pi/8 and theta[i,j] < 3*np.pi/8) or (theta[i,j] >= -7*np.pi/8 and theta[i,j] < -5*np.pi/8):
if grad[i,j] < grad[i-1,j+1] or grad[i,j] < grad[i+1,j-1]:
grad[i,j] = 0
elif (theta[i,j] >= 3*np.pi/8 and theta[i,j] < 5*np.pi/8) or (theta[i,j] >= -5*np.pi/8 and theta[i,j] < -3*np.pi/8):
if grad[i,j] < grad[i-1,j] or grad[i,j] < grad[i+1,j]:
grad[i,j] = 0
else:
if grad[i,j] < grad[i-1,j-1] or grad[i,j] < grad[i+1,j+1]:
grad[i,j] = 0
# 双阈值处理
high_threshold = 100
low_threshold = 50
edge = np.zeros_like(grad)
edge[grad > high_threshold] = 255
edge[(grad >= low_threshold) & (grad <= high_threshold)] = 127
# 滞后阈值处理
for i in range(1, rows-1):
for j in range(1, cols-1):
if edge[i,j] == 127:
if (edge[i-1,j-1] == 255) or (edge[i-1,j] == 255) or (edge[i-1,j+1] == 255) or (edge[i,j-1] == 255) or (edge[i,j+1] == 255) or (edge[i+1,j-1] == 255) or (edge[i+1,j] == 255) or (edge[i+1,j+1] == 255):
edge[i,j] = 255
else:
edge[i,j] = 0
# 显示结果
cv2.imshow('image', img)
cv2.imshow('edge', edge)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,这只是一个简单的边缘检测算法,可能不适用于所有情况。对于更复杂的图像,可能需要使用更高级的算法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)