要自动选择最大值和最小值,cv2.Canny()可以使用auto_canny()Adrian Rosebrock 在他的博客Zero-parameter, automatic Canny edge detection with Python and OpenCV中创建的函数。这个想法是计算图像中像素强度的中值,然后取这个中值来确定阈值lower和upper阈值。有关更详细的说明,请查看他的博客。这是功能
def auto_canny(image, sigma=0.33):
# Compute the median of the single channel pixel intensities
v = np.median(image)
# Apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
return cv2.Canny(image, lower, upper)
要对多张图像执行边缘检测,您可以使用该glob库遍历每张图像,应用精明的边缘检测,然后保存图像。这是结果

import cv2
import numpy as np
import glob
def auto_canny(image, sigma=0.33):
# Compute the median of the single channel pixel intensities
v = np.median(image)
# Apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
return cv2.Canny(image, lower, upper)
# Read in each image and convert to grayscale
images = [cv2.imread(file,0) for file in glob.glob("images/*.jpg")]
# Iterate through each image, perform edge detection, and save image
number = 0
for image in images:
canny = auto_canny(image)
cv2.imwrite('canny_{}.png'.format(number), canny)
number += 1