1 Code For Converting RGB, Grayscale, and HSI Image: Author: Atik Ishrak October 1, 2024

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Author: Atik Ishrak

October 1, 2024

1 Code for Converting RGB, Grayscale, and HSI Image

Listing 1: Python Script: Image Conversion


pip install matplotlib numpy scikit - image pillow
import matplotlib . pyplot as plt
from PIL import Image
import numpy as np
from skimage . color import rgb2gray , rgb2hsv

# Load the indexed image


image = Image . open ( ’/ content / sample_data / canoe . tif ’)

# Convert indexed image to RGB using the palette


rgb_image = image . convert ( " RGB " )

# Convert RGB image to Grayscale


g ra ys ca l e_ im ag e = rgb2gray ( np . array ( rgb_image ))

# Convert RGB to HSI ( HSI is analogous to HSV in skimage )


hsi_image = rgb2hsv ( np . array ( rgb_image ))

# Display all the images


fig , ax = plt . subplots (1 , 3 , figsize =(20 , 10))

# # Show original indexed image


# ax [0]. imshow ( image )
# ax [0]. set_title (" Indexed Image ")
# ax [0]. axis ( ’ off ’)

# Show RGB image


ax [0]. imshow ( rgb_image )
ax [0]. set_title ( " RGB ␣ Image " )
ax [0]. axis ( ’ off ’)

# Show Grayscale image


ax [1]. imshow ( grayscale_image , cmap = ’ gray ’)
ax [1]. set_title ( " Grayscale ␣ Image " )
ax [1]. axis ( ’ off ’)

# Show HSI image


ax [2]. imshow ( hsi_image )
ax [2]. set_title ( " HSI ␣ Image " )
ax [2]. axis ( ’ off ’)

plt . show ()

1
1.1 Input

Figure 1: Original Indexed Image

1.2 Output: Converted RGB, Gray scale and HSI Image

Figure 2: Converted RGB, Gray scale and HSI Image

2 Code for Display the 8 bit planes of Cameraman.tf. Again


show the image setting the LSB to zero and then MSB to
zero

2
Listing 2: Python Script: Image Conversion
import matplotlib . pyplot as plt
import numpy as np
from PIL import Image

# Load the gray - level image


image = Image . open ( ’/ content / sample_data / cameraman . tif ’ ). convert ( " L " )
image_array = np . array ( image )

# Function to extract a specific bit plane


def e x t r a c t _ b i t _ p l a n e ( image , bit_position ):
# Use bitwise shift and mask to extract the specific bit plane
bit_plane = ( image >> bit_position ) & 1
# Multiply by 255 to visualize the bit plane in binary form (0 or 255)
return bit_plane * 255

# Display the 8 bit planes


fig , axes = plt . subplots (2 , 4 , figsize =(15 , 8))
fig . suptitle ( ’ Bit ␣ Planes ␣ of ␣ the ␣ Gray - level ␣ Image ’ , fontsize =16)

for i in range (8):


row , col = divmod (i , 4)
b it _p la n e_ im ag e = e x t r a c t _ b i t _ p l a n e ( image_array , i )
axes [ row , col ]. imshow ( bit_plane_image , cmap = ’ gray ’)
axes [ row , col ]. set_title ( f ’ Bit ␣ Plane ␣ { i } ’)
axes [ row , col ]. axis ( ’ off ’)

# Create an image with LSB set to zero ( bit plane 0 set to zero )
lsb_ zero_ima ge = image_array & ~1 # Set LSB to 0 using bitwise AND

# Create an image with MSB set to zero ( bit plane 7 set to zero )
msb_ zero_ima ge = image_array & ~(1 << 7) # Set MSB to 0 using bitwise AND

# Display the images with LSB and MSB set to zero


fig , ( ax2 , ax3 ) = plt . subplots (1 , 2 , figsize =(15 , 5))
fig . suptitle ( ’ LSB ␣ and ␣ MSB ␣ Modifications ’ , fontsize =16)

# Show the image with LSB set to zero


ax2 . imshow ( lsb_zero_image , cmap = ’ gray ’)
ax2 . set_title ( ’ Image ␣ with ␣ LSB ␣ Set ␣ to ␣ Zero ’)
ax2 . axis ( ’ off ’)

# Show the image with MSB set to zero


ax3 . imshow ( msb_zero_image , cmap = ’ gray ’)
ax3 . set_title ( ’ Image ␣ with ␣ MSB ␣ Set ␣ to ␣ Zero ’)
ax3 . axis ( ’ off ’)

# Display all images


plt . tight_layout ()
plt . show ()

3
2.1 Input: Cameraman.tf

2.2 Output: 8 bit plane Image

4
2.3 Output: Image setting the LSB to zero and then MSB to zero

3 Code for mirror image of the cameraman.tif

Listing 3: Python Script: Image Conversion


from PIL import Image
import matplotlib . pyplot as plt

# Load the image


image = Image . open ( " / content / sample_data / cameraman . tif " )

# Create a mirror image ( flip horizontally )


mirror_image = image . transpose ( Image . F LI P_ LE F T_ RI GH T )

# Display the original and mirrored images side - by - side


fig , ( ax2 ) = plt . subplots (1 , figsize =(12 , 6))

# Show the mirrored image


ax2 . imshow ( mirror_image , cmap = ’ gray ’)
ax2 . set_title ( ’ Mirror ␣ Image ’)
ax2 . axis ( ’ off ’)

# Display the images


plt . show ()

5
3.1 Input: Cameraman.tf

3.2 Output: Mirror Image

4 Histogram specification method

6
Listing 4: Python Script: Image Conversion
import numpy as np
import matplotlib . pyplot as plt
from PIL import Image

# Function to perform histogram specification


def h i s t o g r a m _ m a t c h i n g ( original , reference ):
# Compute the histogram and CDF for the original image
original_hist , bins = np . histogram ( original . flatten () , 256 , [0 , 256])
original_cdf = original_hist . cumsum ()
o r i g i n a l _ c d f _ n o r m a l i z e d = original_cdf * (255 / original_cdf [ -1]) # Normalize

# Compute the histogram and CDF for the reference image


reference_hist , bins = np . histogram ( reference . flatten () , 256 , [0 , 256])
reference_cdf = referen ce_hist . cumsum ()
r e f e r e n c e _ c d f _ n o r m a l i z e d = reference_cdf * (255 / reference_cdf [ -1]) # Normalize

# Use the reference CDF to find the mapping for histogram specification
mapping = np . zeros (256)
for i in range (256):
ref_val = np . abs ( r e f e r e n c e _ c d f _ n o r m a l i z e d - o r i g i n a l _ c d f _ n o r m a l i z e d [ i ]). argmin ()
mapping [ i ] = ref_val

# Apply the mapping to the original image


matched_image = np . interp ( original . flatten () , bins [: -1] , mapping )

return matched_image . reshape ( original . shape )

# Load the original and reference images and convert them to grayscale
orig inal_ima ge = np . array ( Image . open ( " / content / sample_data / cameraman . tif " ). convert ( " L " ))
r ef er en c e_ im ag e = np . array ( Image . open ( " / content / sample_data / canoe . tif " ). convert ( " L " ))
# Replace with any reference image

# Apply histogram matching


matched_image = h i s t o g r a m _ m a t c h i n g ( original_image , re f er en ce _ im ag e )

# Plot the original , reference , and histogram matched images


fig , ( ax1 , ax2 , ax3 ) = plt . subplots (1 , 3 , figsize =(18 , 6))

# Original image
ax1 . imshow ( original_image , cmap = ’ gray ’)
ax1 . set_title ( " Original ␣ Image " )
ax1 . axis ( ’ off ’)

# Reference image
ax2 . imshow ( reference_image , cmap = ’ gray ’)
ax2 . set_title ( " Reference ␣ Image " )
ax2 . axis ( ’ off ’)

# Histogram matched image


ax3 . imshow ( matched_image , cmap = ’ gray ’)
ax3 . set_title ( " Histogram ␣ Matched ␣ Image " )
ax3 . axis ( ’ off ’)

plt . show ()

7
4.1 Input: Origial Image (cameraman.tf ) and Reference Image (canoe.ttf )

4.2 Output: Histogram Match Image

Figure 3: Caption

5 Code for FFT of Cameraman.tf

Listing 5: Python Script: Image Conversion


import numpy as np
import matplotlib . pyplot as plt

8
from PIL import Image

# Load the image and convert to grayscale


image = Image . open ( " / content / sample_data / cameraman . tif " ). convert ( " L " )
image_np = np . array ( image )

# Compute the 2 D FFT of the image


fft_image = np . fft . fft2 ( image_np )
# Shift the zero frequency component to the center of the spectrum
fft_shifted = np . fft . fftshift ( fft_image )
# Compute the magnitude spectrum ( log scale for better visualization )
m a g n i t u d e _ s p e c t r u m = np . log ( np . abs ( fft_shifted ) + 1) # Adding 1 to avoid log (0)

# Plot the original image and its FFT magnitude spectrum


fig , ( ax2 ) = plt . subplots (1 , figsize =(12 , 6))

# Display the magnitude spectrum of the FFT


ax2 . imshow ( magnitude_spectrum , cmap = ’ gray ’)
ax2 . set_title ( " FFT ␣ Magnitude ␣ Spectrum " )
ax2 . axis ( ’ off ’)

plt . show ()

5.1 Input: Cameraman.tf

Figure 4: Caption

9
5.2 Output: FFT of cameraman.tf

6 Code for Implementing Morphological Operations

Listing 6: Python Script: Image Conversion


pip install opencv - python numpy matplotlib
import cv2
import numpy as np
import matplotlib . pyplot as plt

# Load the image in grayscale


image = cv2 . imread ( ’/ content / sample_data / cameraman . tif ’ , 0)

# Define a kernel for morphological operations


kernel = np . ones ((5 , 5) , np . uint8 ) # 5 x5 kernel of ones

# Perform Erosion
erosion = cv2 . erode ( image , kernel , iterations =1)

# Perform Dilation
dilation = cv2 . dilate ( image , kernel , iterations =1)

# Perform Opening ( Erosion followed by Dilation )


opening = cv2 . morphologyEx ( image , cv2 . MORPH_OPEN , kernel )

# Perform Closing ( Dilation followed by Erosion )


closing = cv2 . morphologyEx ( image , cv2 . MORPH_CLOSE , kernel )

# Display the original and processed images


fig , axes = plt . subplots (2 , 2 , figsize =(12 , 8))

# Display Erosion

10
axes [0 , 0]. imshow ( erosion , cmap = ’ gray ’)
axes [0 , 0]. set_title ( ’ Erosion ’)
axes [0 , 0]. axis ( ’ off ’)

# Display Dilation
axes [0 , 1]. imshow ( dilation , cmap = ’ gray ’)
axes [0 , 1]. set_title ( ’ Dilation ’)
axes [0 , 1]. axis ( ’ off ’)

# Display Opening
axes [1 , 0]. imshow ( opening , cmap = ’ gray ’)
axes [1 , 0]. set_title ( ’ Opening ’)
axes [1 , 0]. axis ( ’ off ’)

# Display Closing
axes [1 , 1]. imshow ( closing , cmap = ’ gray ’)
axes [1 , 1]. set_title ( ’ Closing ’)
axes [1 , 1]. axis ( ’ off ’)

# Remove the last empty subplot


# axes [1 , 2]. axis ( ’ off ’)

# Display the plots


plt . tight_layout ()
plt . show ()

6.1 Input: cameraman.tf

Figure 5: Caption

11
6.2 Output: Morphological Operation of the cameraman.tf

Figure 6: Caption

12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy