Image Filtering Example with Scipy Functions

     In image processing, filters provide a range of techniques to modify, enhance, and extract valuable information from images. They are fundamental tools that enable us to improve image quality, detect important image characteristics, and facilitate subsequent analysis and interpretation of images. Filters can be used for a variety of tasks, including noise reduction, edge detection, feature extraction and enhancement, smoothing and blurring, and picture alteration and restoration.
    In this tutorial, I'll briefly explain some of the filtering methods available in scipy library. The tutorial cover:

  1. Gaussion filtering 
  2. Median filtering
  3. Maximum filtering
  4. Minimum filtering
  5. Sobel filter
  6. Laplacian filter
  7. Custom filter or convolution
  8. Source code listing

    Let's get started.

    
Gaussian filtering 
 
     Gaussian filtering is a popular smoothing technique that reduces noise and blurs the image. It applies a Gaussian distribution-based convolution kernel to each pixel, which gives more weight to nearby pixels. The sigma parameter controls the amount of blurring, with higher values resulting in more smoothing.
 
 
from scipy.ndimage import gaussian_filter

# Apply Gaussian filter to an image
smoothed_image = gaussian_filter(image, sigma=2
 
 
 
Median filtering 
 
     Median filtering is a non-linear filtering method that effectively removes salt-and-pepper noise from the image. It replaces each pixel's value with the median value of its neighboring pixels within a specified window size. The size parameter determines the size of the neighborhood window.
 

from scipy.ndimage import median_filter

# Apply median filter to an image
filtered_image = median_filter(image, size=3)
 
 
 
Maximum filtering 
 
     Maximum filtering enhances bright regions and highlights prominent features in an image. It replaces each pixel's value with the maximum value of its neighboring pixels within a specified window size. The size parameter controls the size of the neighborhood window.
 

from scipy.ndimage import maximum_filter

# Apply maximum filter to an image
max_filtered_image = maximum_filter(image, size=5) 
 
 
 
Minimum filtering 
 
     Minimum filtering enhances dark regions and suppresses noise in an image. It replaces each pixel's value with the minimum value of its neighboring pixels within a specified window size. The size parameter determines the size of the neighborhood window.
 

from scipy.ndimage import minimum_filter

# Apply minimum filter to an image
min_filtered_image = minimum_filter(image, size=3)
 
 
 
Sobel filter 
 
     Sobel filtering is a common technique for edge detection in images. It applies separate convolutions to the image with two small gradient filters (one for horizontal edges and one for vertical edges). The resulting edge image highlights regions with rapid intensity changes, representing edges in the original image.
 
 
from scipy.ndimage import sobel

# Apply Sobel filter to detect edges in an image
edge_image = sobel(image) 
 
 
 
Laplacian filter 
 
     The Laplacian filter is another method for edge detection. It calculates the second derivative of the image to detect regions of rapid intensity changes, which correspond to edges. The resulting edge image can be more sensitive to noise compared to the Sobel filter.
 
 
from scipy.ndimage import laplace

# Apply Laplacian filter to detect edges in an image
edge_image = laplace(image) 
 


Custom filter or convolution
 
     The custom filter allows you to define a kernel to convolve with the image. You can design a kernel to perform specific operations like sharpening, blurring, or extracting features. The convolve function applies the kernel to each pixel, combining their values based on the convolution operation.
 
 
from scipy.ndimage import convolve

# Define a custom filter kernel
kernel = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])

# Apply the custom filter to an image
filtered_image = convolve(image, kernel) 
 

     Now we can apply all of the above filtering methods and display the output image in graph.


import matplotlib.pyplot as plt
from scipy import ndimage
from PIL import Image
from numpy import array

# load image
image = Image.open("birds.jpg")
 
# convert to grayscale
image = image.convert('L')

# Apply Gaussian filter to an image
gaussian = ndimage.gaussian_filter(image, sigma=2)

# Apply median filter to an image
med_filtered = ndimage.median_filter(image, size=3)

# Apply maximum filter to an image
max_filtered = ndimage.maximum_filter(image, size=5)

# Apply minimum filter to an image
min_filtered = ndimage.minimum_filter(image, size=3)

# Apply Sobel filter to detect edges in an image
sobel = ndimage.sobel(image)

# Apply Laplacian filter to detect edges in an image
laplacian = ndimage.laplace(image)

# Define a custom filter kernel
kernel = array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])

# # Apply the custom filter to an image
custom = ndimage.convolve(image, kernel)

# Collect all methods
filters = {"Original": image,
"Gaissian": gaussian,
"Median": med_filtered,
"Maximum": max_filtered,
"Minimum": min_filtered,
"Sobel": sobel,
"Laplacian": laplacian,
"Custom": custom
}

# display in a graph
plt.figure(figsize=(6, 10))
plt.subplots_adjust(wspace=.1, hspace=.1)
plt.tight_layout()

for i, (key, value) in enumerate(filters.items()):
plt.subplot(4, 2, i + 1)
plt.tick_params(labelbottom=False)
plt.tick_params(labelleft=False)
plt.title("{}".format(key))
plt.imshow(value, cmap="gray")

plt.show()
 
 
    In the code snippet above, we loaded image file and converted it into the grayscale. We applied each filter into the image and collected outputs in a list. Finally, we displayed all the filtered images in graph.
 


Video tutorial


 
    In this tutorial, we've briefly explored the image filtering methods by using scipy library function.


No comments:

Post a Comment