编写梯度算子、拉普拉斯算子、方向算子、坎尼算子的边缘检测代码
时间: 2023-11-06 09:05:07 浏览: 112
图像锐化算子的比较.docx
以下是Python代码实现:
梯度算子:
```python
import cv2
import numpy as np
def gradient_operator(image):
x_kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
y_kernel = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
grad_x = cv2.filter2D(image, -1, kernel=x_kernel)
grad_y = cv2.filter2D(image, -1, kernel=y_kernel)
gradient = np.sqrt(np.square(grad_x) + np.square(grad_y))
gradient *= 255.0 / gradient.max()
return gradient.astype(np.uint8)
```
拉普拉斯算子:
```python
import cv2
import numpy as np
def laplacian_operator(image):
laplacian_kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
laplacian = cv2.filter2D(image, -1, kernel=laplacian_kernel)
laplacian *= 255.0 / laplacian.max()
return laplacian.astype(np.uint8)
```
方向算子:
```python
import cv2
import numpy as np
def direction_operator(image):
x_kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
y_kernel = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
grad_x = cv2.filter2D(image, -1, kernel=x_kernel)
grad_y = cv2.filter2D(image, -1, kernel=y_kernel)
direction = np.arctan2(grad_y, grad_x) * 180 / np.pi
return direction.astype(np.uint8)
```
坎尼算子:
```python
import cv2
import numpy as np
def canny_operator(image, threshold1=50, threshold2=150):
edges = cv2.Canny(image, threshold1, threshold2)
return edges
```
以上代码中,使用了OpenCV库来进行卷积操作和Canny算子的运用。
阅读全文