用python实现canny边缘检测
时间: 2023-05-24 09:05:57 浏览: 59
以下是Python中Canny边缘检测的实现代码:
```python
import cv2
# 读入图像,转为灰度图
img = cv2.imread("lena.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Canny边缘检测
edges = cv2.Canny(gray, 100, 200)
# 显示结果
cv2.imshow("Original", img)
cv2.imshow("Canny", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,cv2.Canny()函数需要两个参数:low_threshold和high_threshold,表示边缘强度的阈值范围。通常情况下,low_threshold取值为高阈值的1/3到1/2之间。在上述代码中,low_threshold为100,high_threshold为200。
运行结果:
![canny示例图](canny.png)
相关问题
不用OPENCV库用python实现canny边缘检测算法
可以使用Python的NumPy和Matplotlib库来实现Canny边缘检测算法。以下是一个简单的实现示例:
```python
import numpy as np
import matplotlib.pyplot as plt
def canny_edge_detection(image, sigma=1, kernel_size=5, low_threshold=0.1, high_threshold=0.3):
# Convert image to grayscale
gray = np.mean(image, axis=2)
# Apply Gaussian blur
blurred = np.zeros_like(gray)
kernel = np.zeros((kernel_size, kernel_size))
for i in range(kernel_size):
for j in range(kernel_size):
kernel[i, j] = np.exp(-((i - kernel_size // 2) ** 2 + (j - kernel_size // 2) ** 2) / (2 * sigma ** 2))
kernel /= np.sum(kernel)
for i in range(kernel_size // 2, gray.shape[0] - kernel_size // 2):
for j in range(kernel_size // 2, gray.shape[1] - kernel_size // 2):
blurred[i, j] = np.sum(gray[i - kernel_size // 2:i + kernel_size // 2 + 1, j - kernel_size // 2:j + kernel_size // 2 + 1] * kernel)
# Compute gradient magnitude and direction
dx = np.zeros_like(blurred)
dy = np.zeros_like(blurred)
for i in range(1, blurred.shape[0] - 1):
for j in range(1, blurred.shape[1] - 1):
dx[i, j] = blurred[i, j + 1] - blurred[i, j - 1]
dy[i, j] = blurred[i + 1, j] - blurred[i - 1, j]
magnitude = np.sqrt(dx ** 2 + dy ** 2)
direction = np.arctan2(dy, dx)
# Non-maximum suppression
suppressed = np.zeros_like(magnitude)
for i in range(1, magnitude.shape[0] - 1):
for j in range(1, magnitude.shape[1] - 1):
angle = direction[i, j] * 180 / np.pi
if angle < 0:
angle += 180
if (angle >= 0 and angle < 22.5) or (angle >= 157.5 and angle < 180):
if magnitude[i, j] >= magnitude[i, j - 1] and magnitude[i, j] >= magnitude[i, j + 1]:
suppressed[i, j] = magnitude[i, j]
elif (angle >= 22.5 and angle < 67.5):
if magnitude[i, j] >= magnitude[i - 1, j - 1] and magnitude[i, j] >= magnitude[i + 1, j + 1]:
suppressed[i, j] = magnitude[i, j]
elif (angle >= 67.5 and angle < 112.5):
if magnitude[i, j] >= magnitude[i - 1, j] and magnitude[i, j] >= magnitude[i + 1, j]:
suppressed[i, j] = magnitude[i, j]
elif (angle >= 112.5 and angle < 157.5):
if magnitude[i, j] >= magnitude[i - 1, j + 1] and magnitude[i, j] >= magnitude[i + 1, j - 1]:
suppressed[i, j] = magnitude[i, j]
# Double thresholding and edge tracking
low_threshold *= np.max(suppressed)
high_threshold *= np.max(suppressed)
edges = np.zeros_like(suppressed)
strong_i, strong_j = np.where(suppressed >= high_threshold)
weak_i, weak_j = np.where((suppressed >= low_threshold) & (suppressed < high_threshold))
edges[strong_i, strong_j] = 1
while len(weak_i) > 0:
i, j = weak_i[0], weak_j[0]
weak_i, weak_j = np.delete(weak_i, 0), np.delete(weak_j, 0)
if edges[i + 1, j] == 1 or edges[i - 1, j] == 1 or edges[i, j + 1] == 1 or edges[i, j - 1] == 1 or edges[i + 1, j + 1] == 1 or edges[i - 1, j - 1] == 1 or edges[i + 1, j - 1] == 1 or edges[i - 1, j + 1] == 1:
edges[i, j] = 1
return edges
# Test the function on a sample image
image = plt.imread('lena.png')
edges = canny_edge_detection(image)
plt.imshow(edges, cmap='gray')
plt.show()
```
这个实现使用了高斯滤波器来平滑图像,计算梯度幅值和方向,进行非极大值抑制,双阈值处理和边缘跟踪。可以通过调整参数来控制算法的性能。
python实现canny边缘检测算法
Canny边缘检测是一种经典的图像边缘检测算法,下面是Python实现代码:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('image.jpg')
# 灰度化处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯平滑滤波
gaussian = cv2.GaussianBlur(gray, (5, 5), 0)
# 计算梯度
sobelx = cv2.Sobel(gaussian, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(gaussian, cv2.CV_64F, 0, 1, ksize=3)
mag = np.sqrt(sobelx**2 + sobely**2)
mag = np.uint8(mag)
# 非极大值抑制
height, width = mag.shape
non_max = np.zeros((height, width), dtype=np.uint8)
for i in range(1, height - 1):
for j in range(1, width - 1):
if sobelx[i, j] == 0:
tangent = 1e5
else:
tangent = sobely[i, j] / sobelx[i, j]
if mag[i, j] >= mag[i-1, j-1] * tangent and mag[i, j] >= mag[i+1, j+1] * tangent:
non_max[i, j] = 255
elif mag[i, j] >= mag[i-1, j] and mag[i, j] >= mag[i+1, j]:
non_max[i, j] = 255
elif mag[i, j] >= mag[i, j-1] * tangent and mag[i, j] >= mag[i, j+1] * tangent:
non_max[i, j] = 255
elif mag[i, j] >= mag[i, j-1] and mag[i, j] >= mag[i, j+1]:
non_max[i, j] = 255
# 双阈值和连接边缘
weak = 75
strong = 255
result = np.zeros((height, width), dtype=np.uint8)
result[mag > weak] = 1
result[mag > strong] = 255
for i in range(1, height - 1):
for j in range(1, width - 1):
if result[i, j] == 1:
if result[i-1, j-1] == 255 or result[i-1, j] == 255 or result[i-1, j+1] == 255 or result[i, j-1] == 255 or result[i, j+1] == 255 or result[i+1, j-1] == 255 or result[i+1, j] == 255 or result[i+1, j+1] == 255:
result[i, j] = 255
else:
result[i, j] = 0
# 显示图片
cv2.imshow('Canny Edge Detection', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码中使用了OpenCV库实现了Canny边缘检测算法,其中包括灰度化处理、高斯平滑滤波、计算梯度、非极大值抑制、双阈值和连接边缘等步骤,最终结果显示在窗口中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)