0% found this document useful (0 votes)
153 views10 pages

Experiment 6 - Removing Noise From Images and Applying Inverse Filtering

It's about how to reduce noise in image through computer vision

Uploaded by

nandinisharda06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views10 pages

Experiment 6 - Removing Noise From Images and Applying Inverse Filtering

It's about how to reduce noise in image through computer vision

Uploaded by

nandinisharda06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Experiment: Removing Noise from Images and Applying Inverse Filtering

Objectives:

1. Upload a noisy image.


2. Remove noise using spatial domain filtering.
3. Apply inverse filtering in the frequency domain.
4. Display results at each step.

Prerequisites:

● Basic understanding of image filtering techniques (spatial and frequency domain).


● Familiarity with Python libraries: OpenCV, NumPy, and Matplotlib.

Steps:

1. Install and Import Libraries: We'll need OpenCV for image processing, Matplotlib for
plotting, and NumPy for matrix operations.
2. User-Uploaded Image Functionality in Google Colab: Google Colab allows you to
upload images directly using a file upload function.
3. Noise Removal: Use Gaussian filters to remove noise in the spatial domain.
4. Inverse Filtering: Apply inverse filtering in the frequency domain using Fourier
Transforms.

Code Implementation:

# Step 1: Install necessary libraries


!pip install opencv-Python-headless
import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab import files

# Step 2: Upload an image


uploaded = files.upload()

# Step 3: Read the image


for filename in uploaded.keys():
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # Read the image
in grayscale
# Step 4: Add noise to the image (simulating a noisy image)
def add_gaussian_noise(image):
row, col = image.shape
mean = 0
sigma = 25
gauss = np.random.normal(mean, sigma, (row, col))
noisy_image = image + gauss
noisy_image = np.clip(noisy_image, 0, 255) # Clipping to keep
pixel values in valid range
return noisy_image

noisy_img = add_gaussian_noise(img)

# Step 5: Display the original and noisy images


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(img, cmap='gray')

plt.subplot(1, 2, 2)
plt.title('Noisy Image')
plt.imshow(noisy_img, cmap='gray')
plt.show()

# Step 6: Noise removal using Gaussian filter (spatial domain)


def gaussian_filter(noisy_image, kernel_size=5):
return cv2.GaussianBlur(noisy_image, (kernel_size, kernel_size),
0)

filtered_img = gaussian_filter(noisy_img)

# Step 7: Display the filtered image


plt.figure(figsize=(5, 5))
plt.title('Filtered Image (Spatial Domain)')
plt.imshow(filtered_img, cmap='gray')
plt.show()
# Step 8: Inverse Filtering (Frequency Domain)
def inverse_filtering(image):
# Step 8.1: Apply Fourier Transform to convert the image to
frequency domain
dft = np.fft.fft2(image)
dft_shifted = np.fft.fftshift(dft)

# Step 8.2: Create a Gaussian filter in frequency domain


rows, cols = image.shape
crow, ccol = rows // 2, cols // 2
mask = np.ones((rows, cols), np.float32)
sigma = 10
for i in range(rows):
for j in range(cols):
distance = (i - crow) ** 2 + (j - ccol) ** 2
mask[i, j] = np.exp(-distance / (2 * sigma ** 2))

# Step 8.3: Apply the filter (multiply DFT with Gaussian mask)
filtered_dft = dft_shifted * mask

# Step 8.4: Inverse DFT to convert back to the spatial domain


dft_inverse_shifted = np.fft.ifftshift(filtered_dft)
img_back = np.fft.ifft2(dft_inverse_shifted)
img_back = np.abs(img_back)
return img_back

inverse_filtered_img = inverse_filtering(noisy_img)

# Step 9: Display the inverse filtered image


plt.figure(figsize=(5, 5))
plt.title('Inverse Filtered Image (Frequency Domain)')
plt.imshow(inverse_filtered_img, cmap='gray')
plt.show()

Explanation:

1. Upload the Image: We use files.upload() to upload an image directly in Google


Colab.
2. Adding Noise: A Gaussian noise is simulated and added to the uploaded image to
create a noisy image.
3. Spatial Filtering: A Gaussian filter is applied using OpenCV’s GaussianBlur()
function to remove the noise in the spatial domain.
4. Inverse Filtering:
○ The Fourier Transform is applied to move the image into the frequency domain.
○ A Gaussian filter is applied in the frequency domain to remove noise.
○ The inverse Fourier Transform is applied to bring the image back to the spatial
domain.

Results:

● Original Image: The image uploaded by the user.


● Noisy Image: Image with Gaussian noise.
● Filtered Image (Spatial Domain): Image after applying Gaussian filtering in the spatial
domain.
● Inverse Filtered Image (Frequency Domain): Image after applying inverse filtering in
the frequency domain.

This experiment showcases how noise can be reduced using both spatial and frequency domain
filtering techniques.
Explanation of program

Step 1: Install Necessary Libraries

!pip install opencv- -headless


import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab import files

● OpenCV (cv2): Used for image processing tasks.


● NumPy (np): Handles numerical operations, like adding noise to an image or performing
mathematical functions.
● Matplotlib (plt): Used to display images.
● files: The files module from Google Colab allows us to upload files, including images.

The line !pip install opencv- -headless ensures that OpenCV is installed, even if it's
not available in your environment.

Step 2: Upload an Image

uploaded = files.upload()

● files.upload(): Opens a file selector dialog in Google Colab, allowing the user to upload
an image.
● After uploading, the image is saved in the uploaded dictionary where the key is the
filename.

Step 3: Read the Image

for filename in uploaded.keys():


img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # Read the image
in grayscale

● cv2.imread(filename, cv2.IMREAD_GRAYSCALE): Reads the uploaded image as a


grayscale image. Grayscale images are easier to process in filtering applications as they
only have intensity values (1 channel) rather than RGB values (3 channels).

Step 4: Add Gaussian Noise to the Image

def add_gaussian_noise(image):
row, col = image.shape
mean = 0
sigma = 25
gauss = np.random.normal(mean, sigma, (row, col)) # Generate
Gaussian noise
noisy_image = image + gauss # Add noise to the image
noisy_image = np.clip(noisy_image, 0, 255) # Ensure pixel values
are within valid range (0-255)
return noisy_image

noisy_img = add_gaussian_noise(img)

● add_gaussian_noise():
○ Generates random Gaussian noise using np.random.normal() with a mean
of 0 and standard deviation sigma=25.
○ This noise is added to the grayscale image to simulate a noisy image.
○ The np.clip() function ensures that the noisy image pixel values remain
between 0 (black) and 255 (white) to avoid overflows.

Step 5: Display the Original and Noisy Images

plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(img, cmap='gray')

plt.subplot(1, 2, 2)
plt.title('Noisy Image')
plt.imshow(noisy_img, cmap='gray')
plt.show()

● plt.subplot(): Displays two images side-by-side. The first subplot shows the original
image, and the second shows the noisy image.
● plt.imshow(): Renders the images in grayscale (cmap='gray').

Step 6: Remove Noise Using Gaussian Filter (Spatial Domain)

def gaussian_filter(noisy_image, kernel_size=5):


return cv2.GaussianBlur(noisy_image, (kernel_size, kernel_size),
0)

filtered_img = gaussian_filter(noisy_img)

● cv2.GaussianBlur(): A Gaussian filter (a type of low-pass filter) is applied to the noisy


image to remove high-frequency noise.
○ The kernel size is 5x5, which determines the amount of smoothing applied to the
image. Larger kernel sizes result in more smoothing.
○ This step works in the spatial domain, where the image is treated as a collection
of pixels.

Step 7: Display the Filtered Image

plt.figure(figsize=(5, 5))
plt.title('Filtered Image (Spatial Domain)')
plt.imshow(filtered_img, cmap='gray')
plt.show()
● Filtered Image: The result of Gaussian filtering is displayed here. The noise should
appear less pronounced due to the smoothing effect of the Gaussian filter.

Step 8: Apply Inverse Filtering in the Frequency Domain

8.1: Fourier Transform

def inverse_filtering(image):
# Apply Fourier Transform to convert the image to the frequency
domain
dft = np.fft.fft2(image)
dft_shifted = np.fft.fftshift(dft)

● np.fft.fft2(): Computes the 2D Fast Fourier Transform (FFT) of the image, converting it
from the spatial domain to the frequency domain.
● np.fft.fftshift(): Shifts the zero-frequency component to the center of the frequency
spectrum, making it easier to apply filters.

8.2: Create a Gaussian Filter in the Frequency Domain

rows, cols = image.shape


crow, ccol = rows // 2, cols // 2
mask = np.ones((rows, cols), np.float32)
sigma = 10
for i in range(rows):
for j in range(cols):
distance = (i - crow) ** 2 + (j - ccol) ** 2
mask[i, j] = np.exp(-distance / (2 * sigma ** 2))

● Gaussian Filter in Frequency Domain: A Gaussian filter is created based on the


distance of each frequency component from the center (crow, ccol). This mask will
emphasize low frequencies and attenuate high frequencies (noise).

8.3: Apply the Filter in the Frequency Domain


filtered_dft = dft_shifted * mask

● Apply Mask: The filter is applied by multiplying the frequency-domain image


(dft_shifted) with the Gaussian mask, reducing noise in the frequency domain.

8.4: Inverse Fourier Transform

dft_inverse_shifted = np.fft.ifftshift(filtered_dft)
img_back = np.fft.ifft2(dft_inverse_shifted)
img_back = np.abs(img_back)
return img_back

● np.fft.ifftshift(): Shifts the frequency components back to their original positions.


● np.fft.ifft2(): Inverse Fast Fourier Transform (IFFT) brings the filtered image back from
the frequency domain to the spatial domain.
● np.abs(): Ensures all pixel values are positive, as the inverse Fourier transform can
produce complex numbers.

Step 9: Display the Inverse Filtered Image

plt.figure(figsize=(5, 5))
plt.title('Inverse Filtered Image (Frequency Domain)')
plt.imshow(inverse_filtered_img, cmap='gray')
plt.show()

● Inverse Filtered Image: The result of inverse filtering is displayed, showing an image
that has been filtered to remove noise in the frequency domain.

Summary of the Process:

1. Image Upload: The user uploads an image.


2. Add Noise: Gaussian noise is added to the image to simulate a noisy input.
3. Spatial Domain Filtering: A Gaussian filter is applied in the spatial domain to reduce
noise.
4. Frequency Domain Filtering: The noisy image is transformed into the frequency
domain, where inverse filtering is applied to remove noise. Then, the image is
transformed back to the spatial domain.
5. Results: The original, noisy, spatially filtered, and inverse filtered images are displayed
for comparison.

You might also like