Reputation: 29
Hi I have a set of images and I want to do edge detection for all the images at once. I can do it manually for each image but I believe that is not the right way to do so. How can I do it for all the images at once? I think it should be in a loop but I don't know how to implement that
I have read multiple images as grayscale and now I want to do edge detection for all the images. How do we select the maximum and minimum value parameters for the Canny function. The images can be accessed here
import glob
import cv2
images = [cv2.imread(file,0) for file in glob.glob("images/*.jpg")]
edges = cv2.Canny(images,100,200)
Upvotes: 2
Views: 2306
Reputation: 46660
To automatically select the maximum and minimum values for cv2.Canny()
you can use the auto_canny()
function created by Adrian Rosebrock in his blog Zero-parameter, automatic Canny edge detection with Python and OpenCV. The idea is to compute the median of the pixel intensities in the image then take this median value to determine the lower
and upper
thresholds. For a more detailed explanation, check out his blog. Here's the function
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)
To perform edge detection on multiple images, you can use the glob
library to iterate through each image, apply canny edge detection, then save the image. Here's the results
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
Upvotes: 1