OpenCV implements image edge detection (sobel operator, laplacian operator, Canny edge detection)

Edge detection principle

Insert image description here
Insert image description here
Insert image description here
Insert image description here

1. Sobel operator

Insert image description here
Insert image description here
Insert image description here
Insert image description here
Insert image description here

1.1 Code implementation

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

img = cv.imread("lena.png",0)

#计算sobel卷积结果
x = cv.Sobel(img,cv.CV_16S,1,0)
y = cv.Sobel(img,cv.CV_16S,0,1)

#将数据进行转换
Scale_absX = cv.convertScaleAbs(x)   #convert 转换  scale  缩放
Scale_absY = cv.convertScaleAbs(y)

#结果合成
result = cv.addWeighted(Scale_absX,0.5,Scale_absY,0.5,0)


#图像显示
plt.figure(figsize=(5,4),dpi=100)
plt.subplot(121),plt.imshow(img,cmap=plt.cm.gray),plt.title("原图")
plt.xticks([]),plt.yticks([])

plt.subplot(122),plt.imshow(result,cmap = plt.cm.gray),plt.title("sobel滤波后结果")
plt.xticks([]),plt.yticks([])

plt.show()

1.2 Result display

Insert image description here

2 Laplacian operator (Laplacian)

Insert image description here
Insert image description here

2.1 Code implementation

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

img = cv.imread("lena.png",0)

#laplacian转换
result = cv.Laplacian(img ,cv.CV_16S)
'''cv.Laplacian 函数用于对图像进行 Laplacian 边缘检测。img 是输入的灰度图像,cv.CV_16S 是输出结果的数据类型,
表示存储边缘检测结果的图像矩阵的元素类型为 16 位带符号整数。'''
Scale_abs = cv.convertScaleAbs(result)
'''使用 cv.convertScaleAbs 函数将 result 转换为绝对值图像,使其在显示时不受正负值影响。'''

#图像显示
plt.figure(figsize=(5,4),dpi=100)
plt.subplot(121),plt.imshow(img,cmap=plt.cm.gray),plt.title("原图")
plt.xticks([]),plt.yticks([])

plt.subplot(122),plt.imshow(Scale_abs,cmap=plt.cm.gray),plt.title("laplacian检测后结果")
plt.xticks([]),plt.yticks([])
plt.show()

2.2 Result display

Insert image description here

3 Canny edge detection algorithm

Insert image description here
Insert image description here
Insert image description here
Insert image description here
Insert image description here

3.1 Code implementation

import cv2 as cv
import numpy as np
import  matplotlib.pyplot as plt
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei']

img = cv.imread("lena.png",0)

#canny边缘检测
lowThreshold = 0
max_lowThreshold = 100

canny = cv.Canny(img,lowThreshold,max_lowThreshold)

#图像显示
plt.figure(figsize=(5,4),dpi=100)
plt.subplot(121),plt.imshow(img, cmap=plt.cm.gray),plt.title("原图")
plt.xticks([]),plt.yticks([])

plt.subplot(122),plt.imshow(canny,cmap=plt.cm.gray),plt.title("Canny检测后结果")
plt.xticks([]),plt.yticks([])

plt.show()

3.2 Results display

Insert image description here

Guess you like

Origin blog.csdn.net/qq_53545309/article/details/133211191