Open In App

Noise Removing Technique in Computer Vision

Last Updated : 19 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

Figure_5

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:

Figure_6

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:

Figure_7

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:

Figure_8

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:

Figure_9

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