操作小记(图像梯度处理)
程序员文章站
2022-07-14 09:47:19
...
图像梯度处理
描述:使用sobel算子、scharr算子和Laplacian算子处理同一幅图像(核的大小相同),观察其结果的不同
代码
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
img = cv2.imread("rice.png", 1)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# sobel
# 参数1,0为只在x方向求一阶导数
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
# 参数0,1为只在y方向求一阶导数
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
sobely = cv2.convertScaleAbs(sobely)
# 叠加
sobelxy = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0)
# scharrx
# 参数1,0为只在x方向求一阶导数
scharrx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=-1)
scharrx = cv2.convertScaleAbs(sobelx)
# 参数0,1为只在y方向求一阶导数
scharry = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=-1)
scharry = cv2.convertScaleAbs(sobely)
# 叠加
scharrxy = cv2.addWeighted(scharrx, 0.5, scharry, 0.5, 0)
# Laplacian
laplacian = cv2.Laplacian(img, cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
titles = ['ori', 'sobel x', 'sobel y',
'sobel xy', 'scharr xy', 'laplacian']
images = [img, sobelx, sobely, sobelxy, scharrxy, laplacian]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i])
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
效果