0% found this document useful (0 votes)
62 views

DIP Lab File

The document provides programs and explanations for various image processing techniques including histogram equalization, smoothing filters, morphological operations like opening and closing, edge detection, sharpening, and DCT/IDCT computation. Specifically, it includes: 1) Programs for implementing smoothing/averaging filters in the spatial domain to reduce noise and blur images. 2) Programs for performing opening and closing morphological operations on images to restore eroded images, smooth contours, and remove small holes/breaks. 3) Explanations of histogram equalization for contrast enhancement by modifying the dynamic range and contrast of an image to have a desired intensity histogram shape.

Uploaded by

Aniket Kumar 10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

DIP Lab File

The document provides programs and explanations for various image processing techniques including histogram equalization, smoothing filters, morphological operations like opening and closing, edge detection, sharpening, and DCT/IDCT computation. Specifically, it includes: 1) Programs for implementing smoothing/averaging filters in the spatial domain to reduce noise and blur images. 2) Programs for performing opening and closing morphological operations on images to restore eroded images, smooth contours, and remove small holes/breaks. 3) Explanations of histogram equalization for contrast enhancement by modifying the dynamic range and contrast of an image to have a desired intensity histogram shape.

Uploaded by

Aniket Kumar 10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

PRACTICAL FILE

DIGITAL IMAGE PROCESSING

Submitted by: Submitted To:


Aniket Kumar Mr. Kanwalpreet Singh Malhi
CSE (7th)
SG20310
UIET (PUSSGRC)
INDEX

S. No. Title Page No.

1. To Study the Image Processing Concept 3-4

2. To Obtain Histogram Equalization 4

3. To Implement smoothing and averaging filter in spatial domain 4-5

4. Program fir Opening and Closing of an image 5-8

5. To fill the region of interest for the Image 8-9

6. Program for Edge Detection Algorithm 9-10

7. Program for Sharpen Image using Gradient Mask 10-11

8. Program for Morphological operation: Erosion and Dilation 11-12

9. Program for DCT/ IDCT computation 12-13

1
Experiment 1 – To Study the Image Processing concept
Digital Image Processing means processing digital image by means of a digital computer. We can also
say that it is a use of computer algorithms, in order to get enhanced image either to extract some
useful information.

The basic steps involved in digital image processing are:

Image acquisition: This involves capturing an image using a digital camera or scanner, or importing an
existing image into a computer.

Image enhancement: This involves improving the visual quality of an image, such as increasing
contrast, reducing noise, and removing artifacts.

Image restoration: This involves removing degradation from an image, such as blurring, noise, and
distortion.

Image segmentation: This involves dividing an image into regions or segments, each of which
corresponds to a specific object or feature in the image.

Image representation and description: This involves representing an image in a way that can be
analyzed and manipulated by a computer, and describing the features of an image in a compact and
meaningful way.

Image analysis: This involves using algorithms and mathematical models to extract information from
an image, such as recognizing objects, detecting patterns, and quantifying features.

Image synthesis and compression: This involves generating new images or compressing existing
images to reduce storage and transmission requirements.

Digital image processing is widely used in a variety of applications, including medical imaging, remote
sensing, computer vision, and multimedia.

Types of an image

BINARY IMAGE– The binary image as its name suggests, contain only two pixel elements i.e 0 &
1,where 0 refers to black and 1 refers to white. This image is also known as Monochrome.

BLACK AND WHITE IMAGE– The image which consist of only black and white color is called BLACK
AND WHITE IMAGE.

8 bit COLOR FORMAT– It is the most famous image format.It has 256 different shades of colors in it
and commonly known as Grayscale Image. In this format, 0 stands for Black, and 255 stands for
white, and 127 stands for gray.

16 bit COLOR FORMAT– It is a color image format. It has 65,536 different colors in it.It is also known
as High Color Format. In this format the distribution of color is not as same as Grayscale image.

Image as a Matrix

As we know, images are represented in rows and columns we have the following syntax in which
images are represented:

2
The right side of this equation is digital image by definition. Every element of this matrix is called
image element , picture element , or pixel.

Experiment 2 – To obtain Histogram Equalization Image


A histogram is a representation of frequency distribution. It is the basis for numerous spatial domain
processing techniques. Histogram manipulation can be used for image enhancement.

Histogram equalization is a widely used contrast-enhancement technique in image processing


because of its high efficiency and simplicity. It is one of the sophisticated methods for modifying the
dynamic range and contrast of an image by altering that image such that its intensity histogram has
the desired shape. It can be classified into two branches as per the transformation function is used.

Steps Involved

1. Get the input image


2. Generate the histogram for the image
3. Find the local minima of the image
4. Divide the histogram based on the local minima
5. Have the specific gray levels for each partition of the histogram
6. Apply the histogram equalization on each partition

Algorithm

1. Compute the histogram of pixel values of the input image. The histogram places the value of
each pixel 𝑓[𝑥,𝑦] into one of L uniformly-spaced buckets ℎ[𝑖]
2. Where 𝐿=2^8 and the image dimension is 𝑀×𝑁
3. Calculate the cumulative distribution function
4. Scale the input image using the cumulative distribution function to produce the output
image.

Where CDFmin is the smallest non-zero value of the cumulative distribution function

Experiment 3 – To implement smoothing or averaging filter in a spatial domain


In image processing, a smoothing or averaging filter is commonly used to reduce noise and blur an
image. The basic idea is to replace each pixel value with the average value of its neighboring pixels.
This is typically done using a convolution operation with a filter or kernel.

Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be
added in size so that it has a specific center pixel. This mask is moved on the image such that the
center of the mask traverses all image pixels.

3
Neighborhood processing in spatial domain: Here, to modify one pixel, we consider values of the
immediate neighboring pixels also. For this purpose, 3X3, 5X5, or 7X7 neighborhood mask can be
considered. An example of a 3X3 mask is shown below.

f(x-1, y-1) f(x-1, y) f(x-1, y+1)

f(x, y-1) f(x, y) f(x, y+1)

f(x+1, y-1) f(x+1, y) f(x+1, y+1)

Program for Averaging Filter in Python

# Low Pass Spatial Domain Filtering


# to observe the blurring effect
import cv2
import numpy as np

# Read the image


img = cv2.imread('sample.png', 0)

# Obtain number of rows and columns


# of the image
m, n = img.shape

# Develop Averaging filter(3, 3) mask


mask = np.ones([3, 3], dtype = int)
mask = mask / 9

# Convolve the 3X3 mask over the image


img_new = np.zeros([m, n])
for i in range(1, m-1):
for j in range(1, n-1):
temp = img[i-1, j-1]*mask[0, 0]+img[i-1, j]*mask[0, 1]+img[i-1, j + 1]*mask[0,
2]+img[i, j-1]*mask[1, 0]+ img[i, j]*mask[1, 1]+img[i, j + 1]*mask[1, 2]+img[i + 1, j-1]*mask[2,
0]+img[i + 1, j]*mask[2, 1]+img[i + 1, j + 1]*mask[2, 2]
img_new[i, j]= temp
img_new = img_new.astype(np.uint8)
cv2.imwrite('blurred.tif', img_new)

Experiment 4 – Program for opening and closing of the image


Opening and Closing are dual operations used in Digital Image Processing for restoring an eroded
image. Opening is generally used to restore or recover the original image to the maximum possible
extent. Closing is generally used to smoother the contour of the distorted image and fuse back the
narrow breaks and long thin gulfs. Closing is also used for getting rid of the small holes of the
obtained image. The combination of Opening and Closing is generally used to clean up artifacts in the
segmented image before using the image for digital analysis.

Properties of Opening are:

1. XoY is a subset (subimage of X)

4
2. If X is a subset of Z then XoY is a subset of ZoY

3.(XoY)oY = XoY

Properties of Closing are:

1. X is a subset subimage of X.Y

2. (X.Y).Y = X.Y

Program for Opening

# Python program to illustrate


# Opening morphological operation
# on an image

# organizing imports
import cv2
import numpy as np

# return video from the first webcam on your computer.


screenRead = cv2.VideoCapture(0)

# loop runs if capturing has been initialized.


while(1):
# reads frames from a camera
_, image = screenRead.read()

# Converts to HSV color space, OCV reads colors as BGR


# frame is converted to hsv
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# defining the range of masking


blue1 = np.array([110, 50, 50])
blue2 = np.array([130, 255, 255])

# initializing the mask to be


# convoluted over input image
mask = cv2.inRange(hsv, blue1, blue2)

# passing the bitwise_and over


# each pixel convoluted
res = cv2.bitwise_and(image, image, mask = mask)

# defining the kernel i.e. Structuring element


kernel = np.ones((5, 5), np.uint8)

# defining the opening function


# over the image and structuring element
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# The mask and opening operation


# is shown in the window

5
cv2.imshow('Mask', mask)
cv2.imshow('Opening', opening)

# Wait for 'a' key to stop the program


if cv2.waitKey(1) & 0xFF == ord('a'):
break

# De-allocate any associated memory usage


cv2.destroyAllWindows()

# Close the window / Release webcam


screenRead.release()

Program for Closing

# Python program to illustrate


# Closing morphological operation
# on an image

# organizing imports
import cv2
import numpy as np

# return video from the first webcam on your computer.


screenRead = cv2.VideoCapture(0)

# loop runs if capturing has been initialized.


while(1):
# reads frames from a camera
_, image = screenRead.read()

# Converts to HSV color space, OCV reads colors as BGR


# frame is converted to hsv
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# defining the range of masking


blue1 = np.array([110, 50, 50])
blue2 = np.array([130, 255, 255])

# initializing the mask to be


# convoluted over input image
mask = cv2.inRange(hsv, blue1, blue2)

# passing the bitwise_and over


# each pixel convoluted
res = cv2.bitwise_and(image, image, mask = mask)

# defining the kernel i.e. Structuring element


kernel = np.ones((5, 5), np.uint8)

# defining the closing function

6
# over the image and structuring element
closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

# The mask and closing operation


# is shown in the window
cv2.imshow('Mask', mask)
cv2.imshow('Closing', closing)

# Wait for 'a' key to stop the program


if cv2.waitKey(1) & 0xFF == ord('a'):
break

# De-allocate any associated memory usage


cv2.destroyAllWindows()

# Close the window / Release webcam


screenRead.release()

Experiment 5 – To fill the region of interest in an Image


A region of interest is a place on an image where we want to search for something.

For example, let's say that we have a car and there is a camera centered in the middle of the car.
Let's say we want to establish autonomous features in the car like lane centering assistance. So, in
order to do this, we need to be able to identify lanes on the image. Now when you're looking for
lanes with the camera centered maybe in the center of the car, you're not going to look for lanes in
the sky or in all the way to the right or the left. The lane will be somewhat to the left and right and
near the ground, not in the sky. So establishing a region of interest in the image is important because
it allows us to zoom into a certain region to look for something, which helps to narrow our focus.

You can also think of it like searching for something. If you lost your keys and you know you've only
been to the kitchen and your bedroom, you'll only search the kitchen and bedroom. You're not going
to search the bathroom or living room when you know you didn't leave it there.

Program in Python

import cv2
import numpy as np

image= cv2.imread('Road-lanes.jpg')

height, width= image.shape[:2]


image_gray= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

ROI= np.array([[(120,height),(120,220),(750,220),(750,height)]], dtype= np.int32)

blank= np.zeros_like(image_gray)
region_of_interest= cv2.fillPoly(blank, ROI,255)
region_of_interest_image= cv2.bitwise_and(image_gray, region_of_interest)

cv2.imshow('Region of Interest', region_of_interest_image)

7
cv2.waitKey()
cv2.destroyAllWindows()

Experiment 6 – Program for Edge Detection Algorithm


Edge detection: In an image, an edge is a curve that follows a path of rapid change in intensity of that
image. Edges are often associated with the boundaries of the object in a scene environment. Edge
detection is used to identify the edges in an image to make image processing easy. Edge detection
works by detecting discontinuities in brightness. Edge detection is mainly used for image
segmentation and data extraction in areas such as image processing, computer vision, and machine
vision.

Program in Matlab

% importing the image


I = rgb2gray(imread("flowers.jpg"));
subplot(2, 4, 1),
imshow(I);
title("Gray Scale Image");

% Sobel Edge Detection


J = edge(I, 'Sobel');
subplot(2, 4, 2),
imshow(J);
title("Sobel");

% Prewitt Edge detection


K = edge(I, 'Prewitt');
subplot(2, 4, 3),
imshow(K);
title("Prewitt");

% Robert Edge Detection


L = edge(I, 'Roberts');
subplot(2, 4, 4),
imshow(L);
title("Robert");

% Log Edge Detection


M = edge(I, 'log');
subplot(2, 4, 5),
imshow(M);
title("Log");

% Zerocross Edge Detection


M = edge(I, 'zerocross');
subplot(2, 4, 6),
imshow(M);
title("Zerocross");

8
% Canny Edge Detection
N = edge(I, 'Canny');
subplot(2, 4, 7),
imshow(N);
title("Canny");

Experiment 7 – Program for Sharpen Image using gradient Mask


Image sharpening is an effect applied to digital images to give them a sharper appearance.
Sharpening enhances the definition of edges in an image. The dull images are those which are poor
at the edges. There is not much difference in background and edges. On the contrary, the sharpened
image is that in which the edges are clearly distinguishable by the viewer.

Sharpening an image using a gradient mask involves enhancing the high-frequency components,
which correspond to edges in the image. One common method for sharpening is to use a Laplacian
or high-pass filter. Here's a Python script using OpenCV to sharpen an image using a gradient mask:

Program in Python

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

# Load an image from file


image_path = 'path/to/your/image.jpg'
original_image = cv2.imread(image_path)

# Convert the image to grayscale


gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)

# Apply Laplacian filter for edge detection


laplacian = cv2.Laplacian(gray_image, cv2.CV_64F)

# Add the Laplacian image to the original image to sharpen it


sharpened_image = cv2.addWeighted(gray_image, 1.5, laplacian, -0.5, 0)

# Display the original, Laplacian, and sharpened images side by side


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

plt.subplot(1, 3, 1)
plt.title('Original Image')
plt.imshow(cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB))
plt.axis('off')

plt.subplot(1, 3, 2)
plt.title('Laplacian Filter')
plt.imshow(laplacian, cmap='gray')
plt.axis('off')

9
plt.subplot(1, 3, 3)
plt.title('Sharpened Image')
plt.imshow(sharpened_image, cmap='gray')
plt.axis('off')

plt.show()

Experiment 8 – Program for Morphological operation: Erosion and Dilation


Morphological operations are a set of operations that process images based on shapes. They apply a
structuring element to an input image and generate an output image.
The most basic morphological operations are two: Erosion and Dilation

Working of erosion:

A kernel(a matrix of odd size(3,5,7) is convolved with the image.

A pixel in the original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel
are 1, otherwise, it is eroded (made to zero).

Thus all the pixels near the boundary will be discarded depending upon the size of the kernel.

So the thickness or size of the foreground object decreases or simply the white region decreases in
the image.

Working of dilation:

A kernel(a matrix of odd size(3,5,7) is convolved with the image

A pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’.

It increases the white region in the image or the size of the foreground object increases

Program in Python

# Python program to demonstrate erosion and


# dilation of images.
import cv2
import numpy as np

# Reading the input image


img = cv2.imread('input.png', 0)

# Taking a matrix of size 5 as the kernel


kernel = np.ones((5, 5), np.uint8)

# The first parameter is the original image,


# kernel is the matrix with which image is
# convolved and third parameter is the number
# of iterations, which will determine how much
# you want to erode/dilate a given image.
img_erosion = cv2.erode(img, kernel, iterations=1)

10
img_dilation = cv2.dilate(img, kernel, iterations=1)

cv2.imshow('Input', img)
cv2.imshow('Erosion', img_erosion)
cv2.imshow('Dilation', img_dilation)

cv2.waitKey(0)

Experiment 9 – Program for DCT and IDCT computation


Discrete Cosine Transform is used in lossy image compression because it has very strong energy
compaction, i.e., its large amount of information is stored in very low frequency component of a
signal and rest other frequency having very small data which can be stored by using very less number
of bits (usually, at most 2 or 3 bit).
To perform DCT Transformation on an image, first we have to fetch image file information (pixel value
in term of integer having range 0 – 255) which we divides in block of 8 X 8 matrix and then we apply
discrete cosine transform on that block of data.

Program in C++

#include <bits/stdc++.h>
using namespace std;
#define pi 3.142857
const int m = 8, n = 8;
int dctTransform(int matrix[][n])
{
int i, j, k, l;

// dct will store the discrete cosine transform


float dct[m][n];

float ci, cj, dct1, sum;

for (i = 0; i < m; i++) {


for (j = 0; j < n; j++) {

// ci and cj depends on frequency as well as


// number of row and columns of specified matrix
if (i == 0)
ci = 1 / sqrt(m);
else
ci = sqrt(2) / sqrt(m);
if (j == 0)
cj = 1 / sqrt(n);
else
cj = sqrt(2) / sqrt(n);

// sum will temporarily store the sum of


// cosine signals

11
sum = 0;
for (k = 0; k < m; k++) {
for (l = 0; l < n; l++) {
dct1 = matrix[k][l] *
cos((2 * k + 1) * i * pi / (2 * m)) *
cos((2 * l + 1) * j * pi / (2 * n));
sum = sum + dct1;
}
}
dct[i][j] = ci * cj * sum;
}
}

for (i = 0; i < m; i++) {


for (j = 0; j < n; j++) {
printf("%f\t", dct[i][j]);
}
printf("\n");
}
}
int main()
{
int matrix[m][n] = { { 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 } };
dctTransform(matrix);
return 0;
}

12

You might also like