Home >Backend Development >Python Tutorial >Image Filtering in Python
Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue.
Image filtering is a key image processing technique used to remove noise and unwanted features, resulting in a clearer, enhanced image. There are two main filter types: linear (e.g., mean, Laplacian) and non-linear (e.g., median, minimum, maximum, Sobel). Each filter serves a specific purpose in noise reduction or image enhancement.
Image filtering utilizes a filter or mask, typically a square window with equal dimensions. This window contains numerical coefficients that determine the filter's effect on the output image.
The blur()
method in OpenCV applies a mean filter. The example below demonstrates this, resulting in a smoother image compared to the original noisy input.
Gaussian blurring is another noise reduction technique. While the underlying mathematics is complex, OpenCV simplifies its application. However, Gaussian blurring can blur sharp edges.
The bilateralFilter()
method offers a solution by using a Gaussian filter that considers pixel intensity differences. This preserves edges better than a standard Gaussian blur. The code snippet below demonstrates its use:
import cv2, argparse ap = argparse.ArgumentParser() ap.add_argument('-i', '--image', required=True, help='Path to the input image') args = vars(ap.parse_args()) image = cv2.imread(args['image']) processed_image = cv2.bilateralFilter(image, 9, 80, 80) cv2.imwrite('processed_image.png', processed_image) cv2.waitKey(0)
To illustrate the difference, let's examine an image with texture and sharp edges, such as a plank image. A standard Gaussian blur will soften the edges, while the bilateral filter maintains sharper lines while still reducing noise.
Original Plank Image:
Gaussian Blurred Plank Image:
Bilateral Filtered Plank Image:
OpenCV's Python interface simplifies advanced image processing tasks like filtering. This tutorial demonstrates the power and ease of using these techniques for noise reduction and image enhancement.
This post includes contributions from Nitish Kumar, a web developer experienced in eCommerce website creation.
The above is the detailed content of Image Filtering in Python. For more information, please follow other related articles on the PHP Chinese website!