roberts,sobel,prewitt三种算子代码
时间: 2023-07-09 08:29:21 浏览: 43
下面是 Roberts、Sobel、Prewitt三种算子的代码实现:
1. Roberts算子代码实现:
```
import numpy as np
import cv2
def roberts_edge_detection(image):
# 获取图像的长和宽
height, width = image.shape
# 定义Roberts算子
roberts_x = np.array([[1, 0], [0, -1]], dtype=np.float32)
roberts_y = np.array([[0, 1], [-1, 0]], dtype=np.float32)
# 定义输出矩阵
output = np.zeros((height, width), dtype=np.float32)
# 将图像进行灰度化处理
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 对图像进行卷积操作
for i in range(0, height - 1):
for j in range(0, width - 1):
gx = np.sum(roberts_x * gray[i:i+2, j:j+2])
gy = np.sum(roberts_y * gray[i:i+2, j:j+2])
output[i, j] = np.sqrt(gx ** 2 + gy ** 2)
# 对输出矩阵进行归一化处理
output = cv2.normalize(output, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
return output
```
2. Sobel算子代码实现:
```
import numpy as np
import cv2
def sobel_edge_detection(image):
# 获取图像的长和宽
height, width = image.shape
# 定义Sobel算子
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32)
sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=np.float32)
# 定义输出矩阵
output = np.zeros((height, width), dtype=np.float32)
# 将图像进行灰度化处理
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 对图像进行卷积操作
for i in range(1, height - 1):
for j in range(1, width - 1):
gx = np.sum(sobel_x * gray[i-1:i+2, j-1:j+2])
gy = np.sum(sobel_y * gray[i-1:i+2, j-1:j+2])
output[i, j] = np.sqrt(gx ** 2 + gy ** 2)
# 对输出矩阵进行归一化处理
output = cv2.normalize(output, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
return output
```
3. Prewitt算子代码实现:
```
import numpy as np
import cv2
def prewitt_edge_detection(image):
# 获取图像的长和宽
height, width = image.shape
# 定义Prewitt算子
prewitt_x = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=np.float32)
prewitt_y = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]], dtype=np.float32)
# 定义输出矩阵
output = np.zeros((height, width), dtype=np.float32)
# 将图像进行灰度化处理
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# 对图像进行卷积操作
for i in range(1, height - 1):
for j in range(1, width - 1):
gx = np.sum(prewitt_x * gray[i-1:i+2, j-1:j+2])
gy = np.sum(prewitt_y * gray[i-1:i+2, j-1:j+2])
output[i, j] = np.sqrt(gx ** 2 + gy ** 2)
# 对输出矩阵进行归一化处理
output = cv2.normalize(output, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
return output
```