亲宝软件园·资讯

展开

Python OpenCV图像边缘检测

人气:0
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边缘检测')

总结

加载全部内容

相关教程
猜你喜欢
用户评论