I want to filter an image with a simple convolution kernel in python-pillow. However, to achieve optimal results, I need a 9x9 kernel. This is not possible in pillow, at least when using ImageFilter.Kernel and the built-in filter() method, which are limited to 5x5 kernels.
Short of implementing my own convolution code, is there a way to filter/convolve an image with a kernel size larger than 5x5?
I'm quite surprised to see that PIL doesn't have support beyond 5 x 5 kernels. As such, it may be prudent to look at other Python packages, such as OpenCV or scipy... for the interest of saving time, let's use scipy. OpenCV is a pain to configure even though it's quite powerful.
I would recommend using scipy to load in your image with imread from the ndimage package, convolve the image with your kernel, then convert to a PIL image when you're done. Use convolve from the ndimage package, then convert back to a PIL image by Image.fromArray. It does have support to convert a numpy.ndarray (which is what is loaded in when you use scipy.ndimage.imread), which is great.
Something like this, assuming a 9 x 9 averaging filter:
# Import relevant packages
import numpy as np
from scipy import ndimage
from PIL import Image
# Read in image - change filename to whatever you want
img = ndimage.imread('image.jpg')
# Create kernel
ker = (1/81.0)*np.ones((9,9))
# Convolve
out = ndimage.convolve(img, ker)
# Convert back to PIL image
out = Image.fromArray(out, 'RGB')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With