Image Processing From Color To Gray
Image Processing From Color To Gray
Below is the Python code for loading a color image, converting it to grayscale for smoothing, applying a 3x3
averaging filter, and displaying both the original and smoothed images. The explanations describe each line
or logical block.
1 import numpy as np
2 from PIL import Image
3 import matplotlib . pyplot as plt
4
11 # Smoothing kernel
12 kernel = np . ones ((3 , 3) ) / 9
13 smoothed = np . zeros_like ( img_gray )
14
20 # Display results
21 plt . figure ( figsize =(10 , 5) )
22 plt . subplot (121) , plt . imshow ( original_img ) , plt . title ( " Original ( Color ) " )
23 plt . subplot (122) , plt . imshow ( smoothed , cmap = " gray " ) , plt . title ( " Smoothed (
Grayscale ) " )
24 plt . show ()
import numpy as np Imports the NumPy library with alias np for efficient array operations and mathematical
functions used in image processing.
from PIL import Image Imports the Image module from the Pillow library for opening and manipulating
image files like sample.jpg.
import matplotlib.pyplot as plt Imports Matplotlib’s pyplot module with alias plt for visualizing the
original and smoothed images.
original_img = np.array(Image.open("sample.jpg")) Loads the image sample.jpg using Image.open()
and converts it to a NumPy array, retaining RGB format as a 3D array of shape (height, width, 3).
img_gray = np.array(Image.open("sample.jpg").convert("L")) Loads sample.jpg again, converts it
to grayscale using convert("L"), and stores it as a 2D NumPy array of shape (height, width) with intensity
values.
kernel = np.ones((3, 3)) / 9 Creates a 3x3 smoothing kernel, a matrix of ones divided by 9, so each
element is 19 , for averaging pixel intensities.
smoothed = np.zeros_like(img_gray) Initializes a zero-filled array smoothed with the same shape and
type as img_gray to store the smoothed image.
for i in range(1, img_gray.shape[0]-1): Loops over row indices of img_gray, excluding the first and
last rows to handle the 3x3 kernel without boundary issues.
1
for j in range(1, img_gray.shape[1]-1): Loops over column indices, excluding the first and last
columns, for the same reason.
smoothed[i, j] = np.sum(img_gray[i-1:i+2, j-1:j+2] * kernel) Computes the smoothed value at
position (i, j) by multiplying a 3x3 patch of img_gray with the kernel and summing the result, storing it
in smoothed[i, j].
plt.figure(figsize=(10, 5)) Creates a new figure with dimensions 10 inches wide and 5 inches tall for
displaying the images.
plt.subplot(121), plt.imshow(original_img), plt.title("Original (Color)") Creates a subplot
(1 row, 2 columns, position 1), displays the RGB original_img, and sets the title to “Original (Color)”.