OpenCV__Python canny边缘检测_教程20

OpenCV__Python canny边缘检测_教程20_第1张图片

#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys


#canny
def canny_test(img):
    blurred = cv.GaussianBlur(img,(3,3),0)
    gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)

    grad_x = cv.Sobel(gray,cv.CV_16SC1,1,0)
    grad_y = cv.Sobel(gray,cv.CV_16SC1,0,1)
    edge_output = cv.Canny(grad_x,grad_y,50,150)
    cv.namedWindow("canny_edge",cv.WINDOW_NORMAL)
    cv.imshow("canny_edge",edge_output)

    dst = cv.bitwise_and(img,img,mask=edge_output)
    cv.namedWindow("color_edge",cv.WINDOW_NORMAL)
    cv.imshow("color_edge",dst)


#canny direct
def canny_direct_test(img):
    blurred = cv.GaussianBlur(img,(3,3),0)
    gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
    edge_output = cv.Canny(gray,50,150)
    cv.namedWindow("canny_direct_edge",cv.WINDOW_NORMAL)
    cv.imshow("canny_direct_edge",edge_output)

    dst = cv.bitwise_and(img,img,mask=edge_output)
    cv.namedWindow("color_direct_edge",cv.WINDOW_NORMAL)
    cv.imshow("color_direct_edge",dst)


def img_test():
    img = cv.imread('E:/chenopencvblogimg/lena22.jpg')
    #判断是否读取成功
    if img is None:
        print("Could not read the image,may be path error")
        return
    cv.namedWindow("origin Pic",cv.WINDOW_NORMAL)
    cv.imshow("origin Pic",img)
    canny_test(img)
    canny_direct_test(img)
    #让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
    cv.waitKey(0)
    #销毁窗口
    cv.destroyAllWindows()

if __name__ == '__main__':
    sys.exit(img_test() or 0)

OpenCV__Python canny边缘检测_教程20_第2张图片

你可能感兴趣的:(OpenCV__Python canny边缘检测_教程20)