Canny算子:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread("../test_1_1.png")
edges = cv.Canny(img, 100, 200)
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
Roberts算子:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
img = cv2.imread(r'../test_1_1.png')
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #转成RGB 方便后面显示
# 灰度化处理图像
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 自定义Roberts算子
kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
kernely = np.array([[0, -1], [1, 0]], dtype=int)
x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx)
y = cv2.filter2D(grayImage, cv2.CV_16S, kernely)
# 转uint8
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
#按照相同的权重相加
Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
# 显示图形
plt.subplot(121),plt.imshow(img_RGB),plt.title('原始图像'), plt.axis('off') #坐标轴关闭
plt.subplot(122),plt.imshow(Roberts, cmap=plt.cm.gray ),plt.title('Roberts算子'), plt.axis('off')
plt.show()
Sobel算子:
# 边缘检测(Sobel、Laplace、Canny)
import cv2 as cv
# Sobel一阶微分算子
def Sobel():
# 1、对X和Y方向求微分
x = cv.Sobel(img, cv.CV_16S, 1, 0)
y = cv.Sobel(img, cv.CV_16S, 0, 1)
#深度 x方向阶数 y方向阶数
# 2、取绝对值
absX = cv.convertScaleAbs(x) # 转回uint8
absY = cv.convertScaleAbs(y)
# 3、线性混合
dst = cv.addWeighted(absX, 0.5, absY, 0.5, 0)
# 比例 比例 常数
# 4、显示
# cv.imshow("absX", absX)
# cv.imshow("absY", absY)
cv.imshow("dst", dst)
if __name__ == '__main__':
# 读取图片
img = cv.imread("../test_1_4.png")
#cv.imshow("img", img)
Sobel() # Sobel一阶微分算子
cv.waitKey(0)