canny阈值越高,检测到的边缘数量越少
python
# 导入OpenCV库,用于图像处理
import cv2
import numpy as np
# 从matplotlib库中导入pyplot模块,用于绘制图像
from matplotlib import pyplot as plt
# 创建一个名为'window'的窗口,窗口大小自动调整
cv2.namedWindow('window', cv2.WINDOW_AUTOSIZE) # cv2.WINDOW_AUTOSIZE: 窗口大小自动调整,不允许用户改变窗口大小
# 使用OpenCV的imread函数读取名为"mao.jpg"的图片,参数1表示读取彩色图像
cat = cv2.imread("mao.jpg", 0) # cat变量存储读取的图像数据,OpenCV默认以BGR格式读取
# 在名为'window'的窗口中显示图像
cv2.imshow('window', cat)
sobelx = cv2.Sobel(cat,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(cat,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0)
scharrx = cv2.Scharr(cat,cv2.CV_64F,1,0)
scharry = cv2.Scharr(cat,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx) ![](https://gitee.com/lindongcms/blog/raw/master/img/202412131548505.png)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(sobelxy, 0.5, sobely, 0.5,0)
laplacian = cv2.Laplacian(cat,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
res = np.hstack((sobelxy,scharrxy,laplacian))
cv2.imshow('window1', res)
res1 = cv2.Canny(cat,80,150)
res2 = cv2.Canny(cat,50,100)
res = np.hstack((res1,res2))
cv2.imshow('window3', res)
key = cv2.waitKey(0)
# 检查按下的键是否是'q',如果是则销毁所有窗口
if key & 0xFF == ord('q'): # 0xFF是掩码,用于确保只检查最低8位
print("准备销毁窗口")
cv2.destroyAllWindows()
检测效果图