Noise Removing Technique in Computer Vision
Last Updated :
19 Jan, 2025
Noise is random variations in pixel values that distort an image often caused by factors like sensor imperfections, low-light conditions, etc. For example, photos taken in low light may appear grainy due to this noise. Effective noise reduction enhances feature extraction by making edges and textures clearer and hence ensures that models remains robust and perform well in real-world.
Techniques for Noise Removal in Computer Vision
Now let’s learn some commonly used techniques and filters for reducing noise in images along with their implementation in python:
1. Median Filtering
Median filtering replaces each pixel’s value with the median value of its neighboring pixels and is ideal for images affected by salt-and-pepper noise.
Python
import numpy as np
import cv2
from matplotlib import pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmKTFI_7r2TKR0sknfK_7GJX8sHItxbf-zh_jOJIBde2-L69K29IAzFLrD&s"
# Fetch the image from the URL
response = requests.get(url)
img_data = response.content
# Open the image using PIL
img = Image.open(BytesIO(img_data))
# Convert the PIL image to a numpy array
img = np.array(img)
# If the image is in RGB, no need for conversion, else convert from BGR to RGB
if img.shape[2] == 3: # Check if it's RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Removing noise in the image using Median Filtering
dst = cv2.medianBlur(img, 5) # 5 is the kernel size (must be an odd number)
# Plotting the source and destination images
plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(img), plt.title('Original Image')
plt.subplot(122), plt.imshow(dst), plt.title('Denoised Image (Median Filter)')
plt.show()
Output:
The original image displays considerable amount of salt-and-pepper noise hindering fine details like puppy's fur and facial expressions. The median filter effectively eliminates these noisy pixels while preserving the edges and structures of the image. As a result, the denoised image appears smoother and visually clearer, enhancing the visibility of important features.
2. Bilateral Filtering
Bilateral filtering is an advanced technique that reduces noise while preserving sharp edges. The filter averages neighboring pixels based on both their spatial proximity and intensity similarity and making areas of similar intensity smooth while maintaining edges.
Python
import numpy as np
import cv2
from matplotlib import pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmKTFI_7r2TKR0sknfK_7GJX8sHItxbf-zh_jOJIBde2-L69K29IAzFLrD&s"
# Fetch the image from the URL
response = requests.get(url)
img_data = response.content
# Open the image using PIL
img = Image.open(BytesIO(img_data))
# Convert the PIL image to a numpy array
img = np.array(img)
# If the image is in RGB, no need for conversion, else convert from BGR to RGB
if img.shape[2] == 3: # Check if it's RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Removing noise in the image using Bilateral Filtering
dst = cv2.bilateralFilter(img, 9, 75, 75) # Parameters: d, sigmaColor, sigmaSpace
# Plotting the source and destination images
plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(img), plt.title('Original Image')
plt.subplot(122), plt.imshow(dst), plt.title('Denoised Image (Bilateral Filter)')
plt.show()
Output:
The denoised image shows how bilateral filter help noise while maintaining details of image and edge sharpness resulting in a smoother and more visually appealing image.
3. Gaussian Filtering
Gaussian filtering applies a Gaussian blur to the image by averaging pixel values within a defined neighborhood. This algorithm convolute the image with a Gaussian kernel and is useful for general noise reduction where slight blurring effect is acceptable.
Python
import numpy as np
import cv2
from matplotlib import pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmKTFI_7r2TKR0sknfK_7GJX8sHItxbf-zh_jOJIBde2-L69K29IAzFLrD&s"
# Fetch the image from the URL
response = requests.get(url)
img_data = response.content
# Open the image using PIL
img = Image.open(BytesIO(img_data))
# Convert the PIL image to a numpy array
img = np.array(img)
# If the image is in RGB, no need for conversion, else convert from BGR to RGB
if img.shape[2] == 3: # Check if it's RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Removing noise in the image using Gaussian Filtering
dst = cv2.GaussianBlur(img, (5, 5), 1.5) # Parameters: kernel size, standard deviation
# Plotting the source and destination images
plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(img), plt.title('Original Image')
plt.subplot(122), plt.imshow(dst), plt.title('Denoised Image (Gaussian Filter)')
plt.show()
Output:
The denoised image shows the effectiveness of the Gaussian filter in noise. However, it's important to note that the Gaussian filter can also blur edges to some extent, which can affect the sharpness of the image.
4. Wavelet Denoising
Wavelet denoising transforms the image into the wavelet domain and then noise components are filtered out before reconstructing the image. Effective for complex noise pattern.
Python
import numpy as np
import cv2
from matplotlib import pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmKTFI_7r2TKR0sknfK_7GJX8sHItxbf-zh_jOJIBde2-L69K29IAzFLrD&s"
# Fetch the image from the URL
response = requests.get(url)
img_data = response.content
# Open the image using PIL
img = Image.open(BytesIO(img_data))
# Convert the PIL image to a grayscale numpy array
img = np.array(img.convert('L')) # Convert to grayscale
# Check if the image is loaded correctly
if img is None:
print("Error: Image file not found or unable to read. Please check the file path and format.")
exit()
# Function to perform wavelet-like denoising
def wavelet_approx_denoising(image, levels=2):
# Create Gaussian pyramid
gaussian_pyramid = [image]
for i in range(levels):
gaussian_pyramid.append(cv2.pyrDown(gaussian_pyramid[-1]))
# Create Laplacian pyramid
laplacian_pyramid = []
for i in range(levels, 0, -1):
# Upsample to the exact size of the next Gaussian layer
upsampled = cv2.pyrUp(gaussian_pyramid[i])
upsampled = cv2.resize(upsampled, (gaussian_pyramid[i-1].shape[1], gaussian_pyramid[i-1].shape[0]))
laplacian = cv2.subtract(gaussian_pyramid[i-1], upsampled)
laplacian_pyramid.append(laplacian)
# Apply thresholding to reduce noise in the Laplacian layers
threshold = np.sqrt(2 * np.log(image.size)) # Universal threshold approximation
denoised_laplacian_pyramid = [cv2.threshold(l, threshold, 255, cv2.THRESH_TOZERO)[1] for l in laplacian_pyramid]
# Reconstruct the denoised image
reconstructed = gaussian_pyramid[-1]
for i in range(levels-1, -1, -1):
# Upsample to the exact size of the Laplacian layer
upsampled = cv2.pyrUp(reconstructed)
upsampled = cv2.resize(upsampled, (denoised_laplacian_pyramid[i].shape[1], denoised_laplacian_pyramid[i].shape[0]))
reconstructed = cv2.add(upsampled, denoised_laplacian_pyramid[i])
return np.clip(reconstructed, 0, 255).astype(np.uint8)
# Applying wavelet-like denoising
dst = wavelet_approx_denoising(img, levels=2)
# Plotting the source and destination images
plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(img, cmap='gray'), plt.title('Original Image')
plt.subplot(122), plt.imshow(dst, cmap='gray'), plt.title('Denoised Image (Wavelet filter)')
plt.show()
Output:
The denoised image shows the performance of wavelet filters in reducing noise while effectively preserving edges, fine details and texture of the image. This makes wavelet denoising a valuable technique for image restoration and enhancement.
5. Non-Local Means Denoising
Non-Local Means (NLM) compares all pixels in an image rather than just neighboring ones to find similar patches for averaging.
Python
import numpy as np
import cv2
from matplotlib import pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmKTFI_7r2TKR0sknfK_7GJX8sHItxbf-zh_jOJIBde2-L69K29IAzFLrD&s"
# Fetch the image from the URL
response = requests.get(url)
img_data = response.content
# Open the image using PIL
img = Image.open(BytesIO(img_data))
# Convert the PIL image to a numpy array
img = np.array(img)
# If the image is in RGB, no need for conversion, else convert from BGR to RGB
if img.shape[2] == 3: # Check if it's RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Removing noise in image using Non-Local Means Denoising
dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
# Plotting the source and destination images
plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(img), plt.title('Original Image')
plt.subplot(122), plt.imshow(dst), plt.title('Denoised Image (Non-Local Means Denoising)')
plt.show()
Output:
The noise has been effectively removed resulting in a smoother and more visually pleasing image but it also blur out some important details like edges and other details like fur.
Noise is unavoidable part of digital imaging but with the right techniques and tools available in OpenCV, we can significantly eliminate its effects. Whether we're working on restoring image quality to improve accuracy of computer vision model or enhancing the quality of medical images it is important to remove noise.
Similar Reads
Image Thresholding Techniques in Computer Vision Image thresholding is a technique in computer vision that converts a grayscale image into a binary image by setting each pixel to either black or white based on a specific threshold value. The article provides a comprehensive overview of various image thresholding techniques used in computer vision,
7 min read
Object Tracking in Computer Vision Object tracking in computer vision involves identifying and following an object or multiple objects across a series of frames in a video sequence. This technology is fundamental in various applications, including surveillance, autonomous driving, human-computer interaction, and sports analytics. In
11 min read
What are the different Image denoising techniques in computer vision? Image denoising techniques in computer vision are essential for enhancing the quality of images corrupted by noise, thereby improving the accuracy of subsequent image processing tasks. Noise in images can arise from various sources such as sensor limitations, transmission errors, or environmental fa
8 min read
A Quick Overview to Computer Vision Computer vision means the extraction of information from images, text, videos, etc. Sometimes computer vision tries to mimic human vision. Itâs a subset of computer-based intelligence or Artificial intelligence which collects information from digital images or videos and analyze them to define the a
3 min read
How to learn Computer Vision? Computer vision is about teaching computers to perceive and interpret the world around them, even though they lack the lifetime experiences we have. This article covers the basics of computer vision, strategies for learning it, recommended resources and courses, and its various applications. To lear
9 min read
Computer Vision - Introduction Ever wondered how are we able to understand the things we see? Like we see someone walking, whether we realize it or not, using the prerequisite knowledge, our brain understands what is happening and stores it as information. Imagine we look at something and go completely blank. Into oblivion. Scary
3 min read