Last active
February 14, 2021 10:45
-
-
Save ericeasthope/062d715b7edee83d1069d46bdcbdd75c to your computer and use it in GitHub Desktop.
Detect edges in colour photos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Minimalist RGB edge detection w/ NumPy, PIL | |
Authored by Eric Easthope | |
MIT License | |
""" | |
from numpy import asarray, pi, pad, zeros | |
from numpy.fft import fft2, ifft2 | |
from PIL.Image import open, fromarray | |
# Open image as Numpy array | |
image = asarray(open("foo.png")) | |
# Define edge filtering kernel | |
kernel = asarray([ | |
[-1, -1, -1], | |
[-1, 10 * pi, -1], | |
[-1, -1, -1] | |
]) | |
# Add padding to kernel | |
padded_kernel = pad( | |
kernel, | |
((0, image.shape[0] - kernel.shape[0]), (0, image.shape[1] - kernel.shape[1])), | |
) | |
# Check that padded kernel has same shape as image | |
assert padded_kernel.shape[:2] == image.shape[:2] | |
# Filter image for all three RGB channels | |
filtered_image = zeros(shape=image.shape) | |
for i in range(3): | |
# Filter colour channel using Fourier Transform with padded kernel | |
channel = ifft2(fft2(image[:, :, i]) * fft2(padded_kernel)).real | |
# Zero values not in RGB colour range | |
channel[channel < 0] = 0 | |
channel[channel > 255] = 0 | |
filtered_image[:, :, i] = channel | |
# Get and show filtered image from Numpy array | |
fromarray(filtered_image.astype("uint8")).show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment