python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python OpenCV图像边缘检测

Python+OpenCV 图像边缘检测四种实现方法

投稿:newname

本文主要介绍了通过OpenCV中Sobel算子、Schaar算子、Laplacian算子以及Canny分别实现图像边缘检测并总结了四者的优缺点,感兴趣的同学可以参考一下
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 设置兼容中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
D:\Anaconda\AZWZ\lib\site-packages\numpy\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:
D:\Anaconda\AZWZ\lib\site-packages\numpy\.libs\libopenblas.NOIJJG62EMASZI6NYURL6JBKM4EVBGM7.gfortran-win_amd64.dll
D:\Anaconda\AZWZ\lib\site-packages\numpy\.libs\libopenblas.WCDJNK7YVMPZQ2ME2ZZHJJRJ3JIKNDB7.gfortran-win_amd64.dll
  warnings.warn("loaded more than 1 DLL from .libs:\n%s" %
horse = cv.imread('img/horse.jpg',0)
plt.imshow(horse,cmap=plt.cm.gray)
plt.imshow(horse,cmap=plt.cm.gray)

1.Sobel算子

# 1,0 代表沿x方向做sobel算子
x = cv.Sobel(horse,cv.CV_16S,1,0)
# 0,1 代表沿y方向做sobel算子
y = cv.Sobel(horse,cv.CV_16S,0,1)
# 格式转换
absx = cv.convertScaleAbs(x)
absy = cv.convertScaleAbs(y)
# 边缘检测结果
res = cv.addWeighted(absx,0.5,absy,0.5,0)
plt.figure(figsize=(20,20))
plt.subplot(1,2,1)
m1 = plt.imshow(horse,cmap=plt.cm.gray)
plt.title("原图")
plt.subplot(1,2,2)
m2 = plt.imshow(res,cmap=plt.cm.gray)
plt.title("Sobel算子边缘检测")
Text(0.5, 1.0, 'Sobel算子边缘检测')

2.Schaar算子(更能体现细节)

# 1,0 代表沿x方向做sobel算子
x = cv.Sobel(horse,cv.CV_16S,1,0,ksize=-1)
# 0,1 代表沿y方向做sobel算子
y = cv.Sobel(horse,cv.CV_16S,0,1,ksize=-1)
# 格式转换
absx = cv.convertScaleAbs(x)
absy = cv.convertScaleAbs(y)
# 边缘检测结果
res = cv.addWeighted(absx,0.5,absy,0.5,0)
plt.figure(figsize=(20,20))
plt.subplot(1,2,1)
m1 = plt.imshow(horse,cmap=plt.cm.gray)
plt.title("原图")
plt.subplot(1,2,2)
m2 = plt.imshow(res,cmap=plt.cm.gray)
plt.title("Schaar算子边缘检测")
Text(0.5, 1.0, 'Schaar算子边缘检测')

3.Laplacian算子(基于零穿越的,二阶导数的0值点)

res = cv.Laplacian(horse,cv.CV_16S)
res = cv.convertScaleAbs(res)
plt.figure(figsize=(20,20))
plt.subplot(1,2,1)
m1 = plt.imshow(horse,cmap=plt.cm.gray)
plt.title("原图")
plt.subplot(1,2,2)
m2 = plt.imshow(res,cmap=plt.cm.gray)
plt.title("Laplacian算子边缘检测")
Text(0.5, 1.0, 'Laplacian算子边缘检测')

4.Canny边缘检测(被认为是最优的边缘检测算法)

res = cv.Canny(horse,0,100)
# res = cv.convertScaleAbs(res) Canny边缘检测是一种二值检测,不需要转换格式这一个步骤
plt.figure(figsize=(20,20))
plt.subplot(1,2,1)
m1 = plt.imshow(horse,cmap=plt.cm.gray)
plt.title("原图")
plt.subplot(1,2,2)
m2 = plt.imshow(res,cmap=plt.cm.gray)
plt.title("Canny边缘检测")
Text(0.5, 1.0, 'Canny边缘检测')

总结

以上就是Python+OpenCV 图像边缘检测四种实现方法的详细内容,更多关于Python OpenCV图像边缘检测的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文