You are on page 1of 32

MADHAV INSTITUTE OF TECHNOLOGY AND SCIENCE,

GWALIOR
Deemed to be University
(Declared under Distinct Category by Ministry of Education, Government of India)
(NAAC Accredited with A++ Grade)

Lab Report
On

Digital Image Processing


(150616)

Submitted by:
Yash Gupta
(0901CS211135)

Faculty Mentor:
Prof. Khushboo Agarwal
Assistant Professor
Department of Computer Science and Engineering

Submitted to:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


MADHAV INSTITUTE OF TECHNOLOGY AND
SCIENCE GWALIOR (474005) (MP) est.1957
JAN-JUNE 2024
INDEX

S.no EXPERIMENT Date Of Submission Grade Remarks


Experiment Date

1. Program to read an image


and display it on the
screen.
Program to determine image
2. negative.

Read an image and perform


3. different filtering operations
(Average, Median etc.)
Program to create
4. motion blur.

Program performs gray


5. level slicing without
background.
Program to perform
6. brightness enhancement and
brightness suppression of an
image
To create a vision program
7. to find histogram value
and display histograph of a
grayscale and color image.
Read an RGB image and
8. segment it using
threshold method.
Read a colour image and
9. separate the colour image
into red green and
blue planes.
Perform gamma
10. correction for the given
colour image
Program to perform
11. different image conversion
techniques

To create a color image


12. and perform read and write
operation

Code to implement
13. watermarking in
spatial domain.

Code to generate different


14. levels of Gaussian
Pyramid.
Experiment No.1

Objective : Program to read an image and display it on the screen

THEORY:

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning
software library. It provides various functions to manipulate images and videos. In this experiment, we aim
to implement a simple program using Python and OpenCV to read an image file and display it on the
screen.

IMPLEMENTATION:

For every experiment import the following python libraries in your IDE:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img

Image = img.imread('/content/rabbu.png')Image.shape

Image

plt.imshow(Image)
3|Page
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to read an
image file and display it on the screen. This demonstrates the basic functionality of image processing using
OpenCV in Python.

4|Page
Experiment No.2

Objective : Program to determine image negative

THEORY:
In image processing, the negative of an image is obtained by subtracting each pixel value from the
maximum intensity value. For example, in an 8-bit grayscale image with pixel values ranging from 0 to
255, the negative of a pixel value p can be calculated as 255 - p. In this experiment, we aim to implement a
Python program using the OpenCV library to determine the negative of an input image.

IMPLEMENTATION:

Image = img.imread('/content/rabbu.png')Image.shape

Image

image_negative=255-image_array

plt.figure(figsize=(14, 8))
plt.subplot(1, 2, 1)
plt.imshow(image_array)
5|Page
plt.title("Original Image")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(image_negative)
plt.title("Negative Image")
plt.axis('off')

OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to determine
the negative of an input grayscale image. This demonstrates the basic functionality of image processing
using OpenCV in Python..

6|Page
Experiment No.3

Objective : Read an image and perform different filtering operations (Average, Median etc.)

THEORY:
Filtering operations are commonly used in image processing to enhance or modify images. Two widely
used filtering operations are the average filter and the median filter. The average filter replaces each pixel
value with the average value of its neighboring pixels, while the median filter replaces each pixel value
with the median value of its neighboring pixels. In this experiment, we aim to implement Python programs
using the OpenCV library to perform both average and median filtering operations on an input image.

IMPLEMENTATION:

Image = img.imread('/content/rabbu.png')from scipy import ndimage


from scipy.ndimage import uniform_filter
gaussian_blur = ndimage.gaussian_filter(image_array, sigma=2)
filter_size=3
mean_filter = uniform_filter(image_array, size=filter_size)
median_filter = ndimage.median_filter(image_array, size=3)
plt.figure(figsize=(10, 10))

plt.subplot(2, 2, 1)
plt.imshow(image_array)
plt.title("Original Image")
plt.axis('off')

plt.subplot(2, 2, 2)
plt.imshow(gaussian_blur)
plt.title("Gaussian Blur")
plt.axis('off')

plt.subplot(2, 2, 3)
plt.imshow(mean_filter)
plt.title("Average Filter")
plt.axis('off')

plt.subplot(2, 2, 4)
plt.imshow(median_filter)
plt.title("Median Filter")
plt.axis('off')

7|Page
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented Python programs using the OpenCV library to perform
average and median filtering operations on an input image. This demonstrates the basic functionality of
image processing using OpenCV in Python..

8|Page
Experiment No.4

Objective : Program to create motion blur

THEORY:
Motion blur is a common effect used in image processing to simulate the blurring caused by the relative
motion between the camera and the scene being captured. It is often used to convey a sense of movement
or speed in images. In this experiment, we aim to implement a Python program using the OpenCV library
to create a motion blur effect on an input image.

IMPLEMENTATION:

Image = img.imread('/content/rabbu.png')from scipy.ndimage import


convolve1d
image_array = np.array(image)

length=40
angle=60
angle = np.deg2rad(angle)
kernel = np.zeros(length)

center = length
kernel[:] = 1 / length
blurred_image_array = np.zeros_like(image_array)

for i in range(image_array.shape[2]):

blurred_image_array[:, :, i] = convolve1d(image_array[:, :, i], kernel, axis=1)

blurred_image_array[:, :, i] = convolve1d(blurred_image_array[:, :, i], kernel,


axis=0)

plt.figure(figsize=(20, 10))

plt.subplot(1, 2, 1)
plt.imshow(image_array)
plt.title("Original Image")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(blurred_image_array)
plt.title(f"Motion Blur (Length = {length}, Angle = {angle}°)")
plt.axis('off')

9|Page
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to create a
motion blur effect on an input image. This demonstrates the basic functionality of image processing using
OpenCV in Python.

10 | P a g e
Experiment No.5

Objective : Program performs gray level slicing without background.

THEORY:
Gray level slicing without background is a technique used in image processing to highlight specific
intensity levels in an image while removing the background. This technique is particularly useful for
enhancing the visibility of objects or features in an image. In this experiment, we aim to implement a
Python program using the OpenCV library to perform gray level slicing without background on an input
grayscale image..

IMPLEMENTATION:

Image = img.imread('/content/rabbu.png')from PIL import Image

image = Image.open('/content/rabbu.png').convert('L')min_level=125
max_level=195

image_array = np.array(image)
output_array =
np.zeros_like(image_array)

output_array[(image_array >= min_level) & (image_array <= max_level)] = 255

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.imshow(image_array, cmap='gray')
plt.title("Original Image (Grayscale)")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(output_array, cmap='gray')
plt.title(f"Gray Level Slicing ({min_level} to {max_level})")
plt.axis('off')

11 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented Python programs using the OpenCV library to perform
average and median filtering operations on an input image. This demonstrates the basic functionality of
image processing using OpenCV in Python..

12 | P a g e
Experiment No.6

Objective : Program to perform brightness enhancement and brightness suppression of an image.

THEORY:
Brightness enhancement and suppression are common techniques used in image processing to adjust the
overall brightness of an image. Brightness enhancement increases the brightness of an image, making it
appear lighter, while brightness suppression decreases the brightness, making it appear darker. In this
experiment, we aim to implement Python programs using the OpenCV library to perform both brightness
enhancement and suppression on an input image.

IMPLEMENTATION:

enhancement_value=60
suppression_value=-60

image = Image.open('/content/rabbu.png')image_array = np.array(image)

enhanced_image_array = np.clip(image_array + enhancement_value, 0, 255).astype(np.uint8)

suppressed_image_array = np.clip(image_array + suppression_value, 0, 255).astype(np.uint8)

plt.figure(figsize=(15, 5))

plt.subplot(1, 3, 1)
plt.imshow(image_array)
plt.title("Original Image")
plt.axis('off')

plt.subplot(1, 3, 2)
plt.imshow(enhanced_image_array)
plt.title(f"Brightness Enhancement (+{enhancement_value})")
plt.axis('off')

plt.subplot(1, 3, 3)
plt.imshow(suppressed_image_array)
plt.title(f"Brightness Suppression ({suppression_value})")
plt.axis('off')

13 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented Python programs using the OpenCV library to perform
brightness enhancement and suppression on an input image. These techniques allow us to adjust the overall
brightness of the image to achieve desired visual effects.

14 | P a g e
Experiment No.7

Objective :
To create a vision program to find histogram value and display histograph of a grayscale and color image..

THEORY:
A histogram is a graphical representation of the distribution of pixel intensities in an image. It provides
valuable insights into the contrast, brightness, and dynamic range of an image. In this experiment, we aim
to implement Python programs using the OpenCV library to calculate and display histograms for both
grayscale and color images.

IMPLEMENTATION:

image = Image.open('/content/rabbu.png')grayscale_image =

image.convert('L')
grayscale_array = np.array(grayscale_image)
grayscale_hist, grayscale_bins = np.histogram(grayscale_array, bins=256, range=(0, 256))
color_array = np.array(image)

color_hist_r, color_bins_r = np.histogram(color_array[:, :, 0], bins=256, range=(0, 256))


color_hist_g, color_bins_g = np.histogram(color_array[:, :, 1], bins=256, range=(0, 256))
color_hist_b, color_bins_b = np.histogram(color_array[:, :, 2], bins=256, range=(0, 256))

plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.imshow(grayscale_array, cmap='gray')
plt.title("Grayscale Image")
plt.axis('off')

plt.subplot(2, 2, 2)
plt.bar(grayscale_bins[:-1], grayscale_hist, width=1, color='gray')
plt.title("Grayscale Histogram")
plt.xlim(0, 255)
plt.xlabel("Intensity Value")
plt.ylabel("Frequency")

plt.subplot(2, 2, 3)
plt.imshow(color_array)
plt.title("Color Image")
plt.axis('off')

plt.subplot(2, 2, 4)

15 | P a g e
plt.bar(color_bins_r[:-1], color_hist_r, width=1, color='red', alpha=0.7, label='Red
Channel')
plt.bar(color_bins_g[:-1], color_hist_g, width=1, color='green', alpha=0.7, label='Green
Channel')
plt.bar(color_bins_b[:-1], color_hist_b, width=1, color='blue', alpha=0.7, label='Blue
Channel')
plt.title("Color Histograms")
plt.xlim(0, 255)
plt.xlabel("Intensity Value")
plt.ylabel("Frequency")
plt.legend(loc='upper right')

plt.tight_layout()

OBSERVATION:

Conclusion:

In this experiment, we successfully implemented Python programs using the OpenCV library to calculate
and display histograms for both grayscale and color images. Histograms provide valuable insights into the
distribution of pixel intensities, which can aid in image analysis and enhancement.
16 | P a g e
Experiment No.8

Objective : Read an RGB image and segment it using threshold method.


THEORY:
Image segmentation is the process of partitioning an image into multiple segments or regions to simplify its
representation or to facilitate further analysis. Thresholding is a simple yet effective segmentation method
where pixels in an image are classified into two groups based on their intensity values: those above a
specified threshold and those below it. In this experiment, we aim to implement a Python program using
the OpenCV library to read an RGB image and segment it using the thresholding method.

IMPLEMENTATION:

from PIL import Image


import numpy as np
import matplotlib.pyplot as plt
threshold=128
image = Image.open('/content/rabbu.png')grayscale_image =
image.convert('L')

grayscale_array = np.array(grayscale_image)

segmented_array = np.where(grayscale_array > threshold, 255, 0).astype(np.uint8)


plt.figure(figsize=(15, 5))

plt.subplot(1, 3, 1)
plt.imshow(image)
plt.title("Original RGB Image")
plt.axis('off')

plt.subplot(1, 3, 2)
plt.imshow(grayscale_array, cmap='gray')
plt.title("Grayscale Image")
plt.axis('off')

plt.subplot(1, 3, 3)
plt.imshow(segmented_array, cmap='gray')
plt.title(f"Segmented Image (Threshold = {threshold})")
plt.axis('off')

17 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to segment an
RGB image using the thresholding method. Thresholding provides a simple yet effective way to partition an
image into regions based on intensity values, which can be useful for various image analysis tasks.

18 | P a g e
Experiment No.9

Objective : Read a colour image and separate the colour image into red green and blue planes.

THEORY:
A color image consists of three color channels: red, green, and blue. Each channel represents the intensity
of its respective color in the image. In this experiment, we aim to implement a Python program using the
OpenCV library to read a color image and separate it into its red, green, and blue channels.

IMPLEMENTATION:

image = Image.open('/content/rabbu.png')image_array = np.array(image)

red_channel = image_array[:, :, 0]
green_channel = image_array[:, :, 1]
blue_channel = image_array[:, :, 2]

plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.imshow(image)
plt.title("Original RGB Image")
plt.axis('off')

plt.subplot(2, 2, 2)
plt.imshow(red_channel, cmap='Reds')
plt.title("Red Channel")
plt.axis('off')

plt.subplot(2, 2, 3)
plt.imshow(green_channel, cmap='Greens')
plt.title("Green Channel")
plt.axis('off')

plt.subplot(2, 2, 4)
plt.imshow(blue_channel, cmap='Blues')
plt.title("Blue Channel")
plt.axis('off')

19 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to separate a
color image into its red, green, and blue channels. This technique allows us to analyze and manipulate
individual color components of the image separately.

20 | P a g e
Experiment No.10

Objective : Perform gamma correction for the given colour image.

THEORY:
Gamma correction is a nonlinear operation used to adjust the brightness of an image. It involves applying a
power-law function to the pixel values, which can effectively modify the image's contrast and brightness.
In this experiment, we aim to implement a Python program using the OpenCV library to perform gamma
correction for a given color image.

IMPLEMENTATION:

image = Image.open('/content/rabbu.png')gamma=2.9
image_array = np.array(image) / 255.0

corrected_array = np.power(image_array, gamma)

corrected_array = (corrected_array * 255).astype(np.uint8)

corrected_image = Image.fromarray(corrected_array)

plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.imshow(image)
plt.title("Original RGB Image")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(corrected_image)
plt.title(f"Gamma Corrected Image (Gamma = {gamma})")
plt.axis('off')

21 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to perform
gamma correction for a given color image. Gamma correction can be used to adjust the image's brightness
and contrast according to specific requirements. Adjusting the gamma parameter allows for fine-tuning of
the correction effect.

22 | P a g e
Experiment No.11

Objective : Program to perform different image conversion techniques.

THEORY:
Image conversion involves transforming an image from one color space or data format to another. This
process is commonly used in image processing and computer vision applications to preprocess images
before further analysis or processing. In this experiment, we aim to implement a Python program using the
OpenCV library to perform different image conversion techniques, including color space conversions and
data format conversions.

IMPLEMENTATION:

image = Image.open('/content/rabbu.png')grayscale_image =

image.convert('L')

hsv_image = image.convert('HSV')

lab_image = image.convert('LAB')

resized_image = image.resize((image.width // 2, image.height // 2))

rotated_image = image.rotate(45)

flipped_vertical_image = image.transpose(Image.FLIP_TOP_BOTTOM)
flipped_horizontal_image = image.transpose(Image.FLIP_LEFT_RIGHT)

plt.figure(figsize=(12, 12))

plt.subplot(3, 3, 1)
plt.imshow(image)
plt.title("Original RGB Image")
plt.axis('off')

plt.subplot(3, 3, 2)
plt.imshow(grayscale_image, cmap='gray')
plt.title("Grayscale Image")
plt.axis('off')

plt.subplot(3, 3, 3)
plt.imshow(hsv_image)
23 | P a g e
plt.title("HSV Image")
plt.axis('off')

plt.subplot(3, 3, 4)
plt.imshow(lab_image)
plt.title("LAB Image")
plt.axis('off')

plt.subplot(3, 3, 5)
plt.imshow(resized_image)
plt.title("Resized Image")
plt.axis('off')

plt.subplot(3, 3, 6)
plt.imshow(rotated_image)
plt.title("Rotated Image (45 degrees)")
plt.axis('off')

plt.subplot(3, 3, 7)
plt.imshow(flipped_horizontal_image)
plt.title("Flipped Horizontally")
plt.axis('off')

plt.subplot(3, 3, 8)
plt.imshow(flipped_vertical_image)
plt.title("Flipped Vertically")
plt.axis('off')

24 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented a Python program using the OpenCV library to perform
different image conversion techniques. These techniques allow us to transform images into different color
spaces or data formats, which can be useful for various image processing tasks and analyses.

25 | P a g e
Experiment No.12

Objective : To create a color image and perform read and write operation.
THEORY:
Creating, reading, and writing color images are fundamental operations in image processing. A color image
is typically represented as a three-dimensional array, where each element represents the intensity of one of
the three color channels (red, green, and blue) at a particular pixel. In this experiment, we will create a
color image programmatically, read it from the disk, and then write it back to the disk using the OpenCV
library.

IMPLEMENTATION:

from PIL import Image, ImageDraw,ImageFont


image = Image.new("RGB", (100, 100), "white")

draw = ImageDraw.Draw(image)

draw.rectangle([0, 0, 50, 50],

fill="red")

draw.rectangle([50, 50, 100, 100], fill="green")


draw.rectangle([50, 0, 100, 50], fill="blue")
draw.rectangle([0, 50, 50, 100], fill="yellow")

image.save("color_image.png")
print("Image saved as
'color_image.png'")

plt.imshow(image)
plt.title("Created Color Image")
plt.axis('off')
plt.show()

read_image = Image.open("color_image.png")

plt.imshow(read_image)
plt.title("Read Color Image")
plt.axis('off')

26 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully created a color image programmatically, wrote it to the disk, and then
read it back from the disk using the OpenCV library. These operations are fundamental in image processing
and form the basis for various image manipulation tasks.

27 | P a g e
Experiment No.13

Objective : Code to implement watermarking in spatial domain.

THEORY:
Watermarking is a technique used to embed a watermark, which can be a logo, text, or any other
identifying information, into an image for copyright protection or authentication purposes. Spatial domain
watermarking directly modifies the pixel values of the original image to embed the watermark. Alpha
blending is a common method used for spatial domain watermarking, where the watermark is combined
with the original image by adjusting the intensity of pixel values.

IMPLEMENTATION:

from PIL import Image, ImageDraw, ImageFont


image = Image.open('/content/patricio-giusti-dQEbetDkxSg-unsplash.jpg')
position = (30, 100) # The position of the watermark text (x, y)
opacity = 0.5
image = image.convert('RGBA')
watermark_text = 'Watermark'

watermark_image = Image.new('RGBA', image.size, (0, 0, 0, 0))

draw = ImageDraw.Draw(watermark_image)

font_size = 90
font = ImageFont.truetype("/content/Roboto-BoldItalic.ttf", font_size)

draw.text(position, watermark_text, fill=(255, 255, 255, int(255 * opacity)), font=font)

watermarked_image = Image.alpha_composite(image, watermark_image)

watermarked_image = watermarked_image.convert('RGB')

plt.imshow(watermarked_image)
plt.title("Watermarked Image")
plt.axis('off')
plt.show()

28 | P a g e
OBSERVATION:

Conclusion:

In this experiment, we successfully implemented spatial domain watermarking using alpha blending
technique in Python with the OpenCV library. Spatial domain watermarking directly modifies the pixel
values of the original image to embed the watermark, which can be useful for copyright protection or
authentication purposes. Adjusting the alpha parameter in the add_watermark function allows controlling
the transparency of the watermark.

29 | P a g e
Experiment No.14

Objective : Code to generate different levels of Gaussian Pyramid.


THEORY:
A Gaussian pyramid is a series of downsampled images, each with reduced resolution and increased
blurring, created by applying Gaussian smoothing and downsampling to an original image. Each level of
the pyramid represents a different scale of the image, with higher levels containing lower-resolution
versions. Generating a Gaussian pyramid with different levels involves iteratively applying Gaussian
smoothing and downsampling to the original image to create multiple levels.

IMPLEMENTATION:

from PIL import Image


import cv2
import numpy as np
import matplotlib.pyplot as plt

image = Image.open('/content/rabbu.png')image_np = np.array(image)


levels=8

# Convert the image from RGB to BGR format (required by OpenCV)


image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)

# Create a list to store the images at each level of the Gaussian pyramid
gaussian_pyramid = []

# Add the original image as the first level of the pyramid


gaussian_pyramid.append(image_np)

for level in range(1, levels):

blurred_image = cv2.GaussianBlur(gaussian_pyramid[-1], (5, 5), 0)

# Downsample the blurred image


downsampled_image = cv2.pyrDown(blurred_image)

# Add the downsampled image to the pyramid


gaussian_pyramid.append(downsampled_image)

# Display the images at each level of the pyramid


plt.figure(figsize=(25, 10))
for level, img in enumerate(gaussian_pyramid):
# Convert the image from BGR to RGB format (for display)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

30 | P a g e
plt.figure(figsize=(12, 12))
plt.subplot(1, levels, level + 1)
plt.imshow(img_rgb)
plt.title(f'Level {level}')
plt.axis('off')

OBSERVATION:

Conclusion:

In this experiment, we successfully implemented the generation of a Gaussian pyramid with different levels
in Python using the OpenCV library. Gaussian pyramids are useful for various image processing tasks, such
as image blending, image compression, and multi-scale analysis. Adjusting the number of levels allows
controlling the scale and resolution of the pyramid.

31 | P a g e
32 | P a g e

You might also like