Name-Bhavya Jain College id-19CS19 Batch-C1 Digital Image Processing Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Name-Bhavya Jain

College id-19CS19
Batch-C1
Digital Image Processing lab
1.Gray-level Mapping (input images)
Mapping functions:
Description: All Image Processing Techniques focused on gray
level transformation as it operates directly on pixels. The gray level
image involves 256 levels of gray and in a histogram, horizontal axis
spans from 0 to 255, and the vertical axis depends on the number of
pixels in the image.
(i). g(x,y) = f(x,y) +10:
Solution Code:
# importing Image module from PIL
package from PIL import Image
# creating image object
img = Image.open(r"C:\Users\Asus\.matplotlib\8.png")
# using image transform method
img1 = img.transform((300, 300), Image.EXTENT, data =[10, 0, img.width +10
, img.height+10 ])
img1.show()

Input Image Output Image


(ii). g(x,y) = f(x,y)*0.5 +20
Solution Code:
# importing Image module from PIL
package from PIL import Image

# creating image object


img = Image.open(r"C:\Users\Asus\.matplotlib\8.png")

# using image transform method


img1 = img.transform((300, 300), Image.EXTENT, data =[10,
0, (img.width*0.5)+20 , (img.height*0.5)+20 ])
img1.show()

Input Image Output Image


2.Negative Transformations(input images 1,2,3).
=>Description: The negative of an image is achieved by replacing
the intensity ‘i’ in the original image by ‘i-1’, i.e. the darkest pixels
will become the brightest and the brightest pixels will become the
darkest. Image negative is produced by subtracting each pixel from
the maximum intensity value.
Solution Code:
from pylab import *
from skimage import img_as_float
skI = imread("/content/1.jpg");
#subplot(1, 2, 1),
L=2^8;
neg = (L - 1) - skI;
subplot(1, 2, 2),
imshow(neg);
title("Negative Image")
Input Image Output Image
Image No.1:

Image No.2:

Image No.3:
3.Gamma Transformation(input image 11):

Take the following values of gamma:0.50,0.10,2.0,4.0.
Description: Gamma correction is important for displaying images on a
screen correctly, to prevent bleaching or darkening of images when
viewed from different types of monitors with different display settings
Gamma correction controls the overall brightness of an image. Images
which are not properly corrected can look either bleached out, or too
dark.Varying the amount of gamma correction changes not only the
brightness, but also the ratios of red to green to blue.
Solution Code:
import cv2
import numpy as np
# Open the image.
img = cv2.imread('/content/11.png')
# Trying 4 gamma values.
for gamma in [0.50,0.10,2.0,4.0]:
# Apply gamma correction.
gamma_corrected = np.array(255*(img / 255) ** gamma, dtype = 'uint8')
# Save edited images.
cv2.imwrite('gamma_transformed'+str(gamma)+'.jpg', gamma_corrected)

Input Image
Output Images:

Gamma=0.50 Gamma=0.10

Gamma=2.0 Gamma=4.0
4.Logarithm Mapping(input images 9,10).Calculate
“c” first.
Description: Mathematically, log transformations can be expressed
as s = clog(1+r). Here, s is the output intensity, r>=0 is the input
intensity of the pixel, and c is a scaling constant. c is given by
255/(log (1 + m)), where m is the maximum pixel value in the image.
It is done to ensure that the final pixel value does not exceed (L-1), or
255. Practically, log transformation maps a narrow range of
low-intensity input values to a wide range of output values.
Solution Code:
import cv2
import numpy as np

# Open the image.


img = cv2.imread('/content/9.png')
img1=cv2.imread('/content/10.png')

# Apply log transform formula


c = 255/(np.log(1 + np.max(img)))
c1 = 255/(np.log(1 + np.max(img1)))

log_transformed = c * np.log(1 + img)


log_transformed1 = c1 * np.log(1 + img1)

# Specify the data type.


log_transformed = np.array(log_transformed, dtype = np.uint8)
log_transformed1 = np.array(log_transformed1, dtype = np.uint8)
# Save the output.
cv2.imwrite('log_transformed.jpg', log_transformed)
cv2.imwrite('log_transformed1.jpg', log_transformed1)

Input Images:
Image No.9: Image No. 10:

Output Images:
After logarithmic Transformation Images will be:

Image No. 9: Image No.10:


5.Exponential Mapping(input images 4,5,6,7,8).Calculate
“c” first.
Description: The exponential operator is a point process where the mapping
function is an exponential curve. This means that each pixel intensity value in
the output image is equal to a basis value raised to the value of the
corresponding pixel value in the input image. Which basis number is used
depends on the desired degree of compression of the dynamic range. In order
to enhance the visibility of a normal photograph, values just above 1 are
suitable. For display, the image must be scaled such that the maximum value
becomes 255 (assuming an 8-bit display).
Solution Code:
import numpy as np
from skimage import io
import matplotlib.pyplot as plt
from matplotlib.colors import NoNorm
r = np.arange(0,256)
c =255/(np.log(1+255))
y =c*np.log(1+r)
plt.plot(r,y);
o = io.imread("/content/4.png")
c= 255/(np.log(1+255))
log_image = c*np.log(o +1)
log_image = np.array(log_image, dtype = np.uint8)
plt.figure(figsize =(15,4))
plt.subplot(1,3,1)
plt.imshow(o, cmap = "gray",norm =
NoNorm()); plt.subplot(1,3,2)
plt.imshow(log_image, cmap = "gray" , norm=NoNorm())
plt.show()
Input image Output Image

Image No.4:

Image No.5:
Input Image Output Image

Image No.6:

Image No.7:

Image No.8:
6.Intensity-level slicing(input image 15).
Description: Intensity level slicing means highlighting a specific
range of intensities in an image. In other words, we segment
certain gray level regions from the rest of the image.
Suppose in an image, your region of interest always take value
between say 80 to 150. So, intensity level slicing highlights this
range and now instead of looking at the whole image, one can now
focus on the highlighted region of interest.
Solution Code:
import numpy as np
from google.colab.patches import cv2_imshow
# Load the image
img = cv2.imread('/content/15.png',0)
# Find width and height of image
row, column = img.shape
# Create an zeros array to store the sliced image
img1 = np.zeros((row,column),dtype = 'uint8')
# Specify the min and max range
min_range = 10
max_range = 60
# Loop over the input image and if pixel value lies in desired range set it to
255 otherwise set it to 0.
for i in range(row):
for j in range(column):
if img[i,j]>min_range and img[i,j]<max_range:
img1[i,j] = 255
else:
img1[i,j] = 0
cv2_imshow(img)

Input image

Output Image
7.Bit-plane slicing(input image 18):
(i).Output-images of bit plane 1,2,3,4,5,6,7,8.
(ii).Reconstruct the image from bit plane images 5,6,7,8.
Description: In Bit-plane slicing, we divide the image into bit
planes. This is done by first converting the pixel values in the binary
form and then dividing it into bit planes.
(i).Solution Code:
import cv2
import matplotlib.pyplot as plt
import math
import numpy as np
# Read the image in greyscale
img = cv2.imread('/content/18.jpg', 0)
#Iterate over each pixel and change pixel value to binary using
np.binary_repr() and store it in a list.
lst = []
for i in range(img.shape[0]):
for j in range(img.shape[1]):
lst.append(np.binary_repr(img[i][j] ,width=8)) # width = no. of bits

# Multiply with 2^(n-1) and reshape to reconstruct the bit image.


eight_bit_img = (np.array([int(i[0]) for i in lst],dtype = np.uint8) *
128).reshape(img.shape[0],img.shape[1])
seven_bit_img = (np.array([int(i[1]) for i in lst],dtype = np.uint8) *
64).reshape(img.shape[0],img.shape[1])
six_bit_img = (np.array([int(i[2]) for i in lst],dtype = np.uint8) *
32).reshape(img.shape[0],img.shape[1])
five_bit_img = (np.array([int(i[3]) for i in lst],dtype = np.uint8)
* 16).reshape(img.shape[0],img.shape[1])
four_bit_img = (np.array([int(i[4]) for i in lst],dtype = np.uint8)
* 8).reshape(img.shape[0],img.shape[1])
three_bit_img = (np.array([int(i[5]) for i in lst],dtype = np.uint8) *
4).reshape(img.shape[0],img.shape[1])
two_bit_img = (np.array([int(i[6]) for i in lst],dtype = np.uint8) *
2).reshape(img.shape[0],img.shape[1])
one_bit_img = (np.array([int(i[7]) for i in lst],dtype = np.uint8)
* 1).reshape(img.shape[0],img.shape[1])

#Concatenate these images for ease of display using cv2.hconcat()


finalr = cv2.hconcat([eight_bit_img,seven_bit_img,six_bit_img,five_bit_img])
finalv =cv2.hconcat([four_bit_img,three_bit_img,two_bit_img,one_bit_img])
# Vertically concatenate
final = cv2.hconcat([finalr,finalv])
# Display the images
plt.imshow(eight_bit_img)
plt.show()

Input image:
Output Images:
Bit-plane 8: Bit-plane 7:

Bit-plane 6: Bit-plane 5:

Bit-plane 4: Bit-plane 3:

Bit-plane 2: Bit-plane 1:
(ii).Solution Code:
# Combining 4 bit planes-5,6,7,8
new_img = eight_bit_img+seven_bit_img+six_bit_img+five_bit_img
# Display the images
plt.imshow(new_img)
plt.show()

Output image:
8.Histogram processing
Write code for calculating the histogram of
the image(input image 19).
Display the output as the “Histogram Graph”.
Description: Histogram equalization is used to enhance
contrast. In digital image processing, the histogram is used
for graphical representation of a digital image. A graph is a
plot by the number of pixels for each tonal value. Nowadays,
image histogram is present in digital cameras. Photographers
use them to see the distribution of tones captured.
Solution Code:
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('/content/19.png',0)

# alternative way to find histogram of an


image plt.title('Histogram Graph')

plt.hist(img.ravel(),256,[0,256])
plt.show()
Input Image:

Output Image:
9. Contrast/Histogram Stretching (input image 20).
Description: Sometimes if the image is a dark, light, or low contrast,
then the histogram of that image might not have pixels with
minimum intensity (0) or maximum intensity(255) or both
respectively. In such cases, the histogram of that image can be
stretched by applying the following transformation.
Let a= maximum intensity level in the image
Let b= minimum intensity level in the image
Let rk= pixel value in the original image
Let sk= pixel value in the stretched image
constant= (255-0)/(a-b)
Then
sk= constant*rk
Solution Code:
# Contrast Stretching ....
from PIL import Image
# Method to process the red band of the
image def normalizeRed(intensity):
iI = intensity
minI = 86
maxI = 230
minO =0
maxO = 255
iO = (iI-minI)*(((maxO-minO)/(maxI-minI))+minO)
return iO
# Method to process the green band of the image
def normalizeGreen(intensity):
iI = intensity
minI = 90
maxI = 225
minO =0
maxO = 255
iO = (iI-minI)*(((maxO-minO)/(maxI-minI))+minO)
return iO
# Method to process the blue band of the
image def normalizeBlue(intensity):
iI = intensity
minI = 100
maxI = 210
minO =0
maxO = 255
iO = (iI-minI)*(((maxO-minO)/(maxI-minI))+minO)
return iO

# Create an image object


from PIL import Image
# creating image object
imageObject = Image.open(r"/content/20.jpg")
# Split the red, green and blue bands from the Image
multiBands = imageObject.split()

# Apply point operations that does contrast stretching on each color band
normalizedRedBand = multiBands[0].point(normalizeRed)
normalizedGreenBand = multiBands[1].point(normalizeGreen)

normalizedBlueBand = multiBands[2].point(normalizeBlue)

# Create a new image from the contrast stretched red, green and blue brands
normalizedImage = Image.merge("RGB", (normalizedRedBand,
normalizedGreenBand, normalizedBlueBand))
# Display the image before contrast
stretching imageObject.show()
# Display the image after contrast
stretching normalizedImage.show()

Input Image Ouput image

You might also like