python opencv edge detection (sobel, Schaer operator, Laplacian operator, Canny)
In this experiment, we used opencv's sobel operator, Shar operator, and Laplacian operator for edge detection, and then used the Canny algorithm for edge detection.
Looking at the code directly, the code is relatively simple and not very complicated:
Note: cv2.convertScaleAbs performs an absolute value operation, because the calculated gradient may be negative.
from ctypes.wintypes import SIZE
from multiprocessing.pool import IMapUnorderedIterator
import cv2
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os
path=r'ls.jpg'
img=cv2.imread(path,1)
img_gray=cv2.imread(path,0)
def cv_show(name,img):
cv2.imshow(name,img)
#cv2.waitKey(0),接收0,表示窗口暂停
cv2.waitKey(0)
#销毁所有窗口
cv2.destroyAllWindows()
#cv_show('img_gray',img_gray)
#Sobel算子
img_sobel_x=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)#1,0 表示选择水平还是竖直放心计算梯度
img_sobel_y=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)#1,0 表示选择水平还是竖直放心计算梯度
sobel_img_x_abs=cv2.convertScaleAbs(img_sobel_x)
img_sobel_y_abs=cv2.convertScaleAbs(img_sobel_y)
img_sobel_xy_abs=cv2.addWeighted(sobel_img_x_abs,0.5,img_sobel_y_abs,0.5,0)
plt.subplot(231)
#img_gray=BGR_TO_RGB(img_gray,'gray')
plt.imshow(img_sobel_x[:,:,::-1])
plt.title('img_sobel_x')
plt.subplot(232)
plt.imshow(sobel_img_x_abs[:,:,::-1])
plt.title('sobel_img_x_abs')
plt.subplot(233)
#result=BGR_TO_RGB(result)
plt.imshow( img[:,:,::-1])
plt.title('img')
plt.subplot(234)
#result=BGR_TO_RGB(result)
plt.imshow( img_sobel_y[:,:,::-1])
plt.title('img_sobel_y')
plt.subplot(235)
#result=BGR_TO_RGB(result)
plt.imshow( img_sobel_y_abs[:,:,::-1])
plt.title('img_sobel_y_abs')
plt.subplot(236)
#result=BGR_TO_RGB(result)
plt.imshow( img_sobel_xy_abs[:,:,::-1])
plt.title('img_sobel_xy_abs')
plt.show()
#沙尔算子
scharrx=cv2.Scharr(img,cv2.CV_64F,dx=1,dy=0)
scharry=cv2.Scharr(img,cv2.CV_64F,dx=0,dy=1)
scharry_img_x_abs=cv2.convertScaleAbs(scharrx)
scharry_img_y_abs=cv2.convertScaleAbs(scharry)
img_scharry_xy_abs=cv2.addWeighted(scharry_img_x_abs,0.5,scharry_img_y_abs,0.5,0)
#拉普拉斯算子
lap_img=cv2.Laplacian(img,cv2.CV_64F)
lap_img_abs=cv2.convertScaleAbs(lap_img)
plt.subplot(121)
#img_gray=BGR_TO_RGB(img_gray,'gray')
plt.imshow(scharry_img_y_abs[:,:,::-1])
plt.title('scharry_img_y_abs')
plt.subplot(122)
plt.imshow(lap_img_abs[:,:,::-1])
plt.title('lap_img_abs')
plt.show()
#result=BGR_TO_RGB(r
path=r'D:\learn\photo\cv\lena.jpg'
img=cv2.imread(path,0)
img_canny1=cv2.Canny(img,80,150)
img_canny2=cv2.Canny(img,50,150)
plt.subplot(131)
#img_gray=BGR_TO_RGB(img_gray,'gray')
plt.imshow(img,'gray')
plt.title('img')
plt.subplot(132)
#img_gray=BGR_TO_RGB(img_gray,'gray')
plt.imshow(img_canny1,'gray')
plt.title('img_canny1')
plt.subplot(133)
plt.imshow(img_canny2,'gray')
plt.title('img_canny2')
plt.show()
os.system("pause")