2

嗨,我有一组图像,我想一次对所有图像进行边缘检测。我可以为每个图像手动执行此操作,但我认为这不是正确的方法。我怎样才能一次为所有图像做这件事?我认为它应该在一个循环中,但我不知道如何实现它

我已经将多张图像读取为灰度图像,现在我想对所有图像进行边缘检测。我们如何选择 Canny 函数的最大值和最小值参数。图片可以在这里访问

import glob
import cv2

images = [cv2.imread(file,0) for file in glob.glob("images/*.jpg")]
edges = cv2.Canny(images,100,200)
4

1 回答 1

1

要自动选择最大值和最小值,cv2.Canny()可以使用auto_canny()Adrian Rosebrock 在他的博客Zero-parameter, automatic Canny edge detection with Python and OpenCV中创建的函数。这个想法是计算图像中像素强度的中值,然后取这个中值来确定阈值lowerupper阈值。有关更详细的说明,请查看他的博客。这是功能

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
于 2019-10-10T02:10:37.523 回答