环境:Python3.8 和 OpenCV
内容:Sobel-Feldman 算子 和 Scharr 算子
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 封装图片显示函数
def image_show(image):
if image.ndim == 2:
plt.imshow(image, cmap='gray')
else:
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
if __name__ == '__main__':
# 读取灰度图像
img_desk = cv.imread('desk.png', 0)
image_show(img_desk)
# Sobel-Feldman 算子,进行边缘检测
img_sob_x = cv.Sobel(img_desk, cv.CV_64F, 1, 0, ksize=3)
img_sob_y = cv.Sobel(img_desk, cv.CV_64F, 0, 1, ksize=3)
# 得到卷积后图像
img_sob_out = (np.abs(img_sob_x) + np.abs(img_sob_y)).clip(0, 255)
# 显示图像
image_show(img_sob_out)
# Scharr 算子,进行边缘检测
img_sch_x = cv.Scharr(img_desk, cv.CV_64F, 1, 0)
img_sch_y = cv.Scharr(img_desk, cv.CV_64F, 0, 1)
# 得到卷积后图像
img_sch_out = np.sqrt(img_sch_x ** 2 + img_sch_y ** 2).clip(0, 255)
# 显示图像
image_show(img_sch_out)