Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views20 pages

DIP Practical File

This document is a practical file for a Digital Image Processing course, detailing various experiments conducted using Python. It includes objectives, theories, procedures, and applications for tasks such as image processing concepts, histogram equalization, smoothing filters, morphological operations, edge detection, and image sharpening. Each experiment is structured with code implementations and expected results, aimed at enhancing understanding of image processing techniques.

Uploaded by

Akshay kumar 09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views20 pages

DIP Practical File

This document is a practical file for a Digital Image Processing course, detailing various experiments conducted using Python. It includes objectives, theories, procedures, and applications for tasks such as image processing concepts, histogram equalization, smoothing filters, morphological operations, edge detection, and image sharpening. Each experiment is structured with code implementations and expected results, aimed at enhancing understanding of image processing techniques.

Uploaded by

Akshay kumar 09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

DIGITAL IMAGE PROCESSING

(CS 751)
PRACTICAL FILE

SUBMITTED BY: SUBMITTED TO:


Prince Gothwal Mr. Kanwalpreet Singh Malhi
SG21338
CSE 7th Semester

DEPARTMENT OF COMPUTER SCIENCE


UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY
PANJAB UNIVERSITY SSG REGIONAL CENTRE
BAJWARA, HOSHIARPUR

1
TABLE OF CONTENTS

S.NO. NAME OF THE EXPERIMENT PAGE REMARKS


NO.

01. TO STUDY THE IMAGE PROCESSING 03


CONCEPT
02. TO OBTAIN HISTOGRAM 05
EQUALIZATION IMAGE

03. TO IMPLEMENT SMOOTHING OR 07


AVERAGING FILTER IN SPATIAL
DOMAIN

04. PROGRAM FOR OPENING AND 09


CLOSING OF THE IMAGE

05. TO FILL THE REGION OF INTEREST FOR 11


THE IMAGE
06. PROGRAM FOR EDGE DETECTION 13
ALGORITHM

07. PROGRAM TO SHARPEN IMAGE USING 15


GRADIENT MASK

08. PROGRAM FOR MORPHOLOGICAL 17


OPERATION : EROSION AND DILATION

09. PROGRAM FOR DCT/IDCT 19


COMPUTATION

2
EXPERIMENT NO. 01
TO STUDY THE IMAGE PROCESSING CONCEPT

Objective:

To explore the fundamentals of image processing by performing basic operations like reading,
displaying, modifying, and analyzing images using Python.

Theory:

Image processing involves manipulating digital images to enhance, extract information, or prepare them
for further analysis. It includes tasks such as filtering, edge detection, segmentation, and more.

Procedure:

1. Import Required Libraries:

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

2. Load and Display an Image:

 Read the image:

img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

 Display using Matplotlib:

plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.show()

3. Perform Basic Operations:

a. Resize the Image:

resized_img = cv2.resize(img, (200, 200))


plt.imshow(cv2.cvtColor(resized_img, cv2.COLOR_BGR2RGB))
plt.title('Resized Image')
plt.show()

b. Convert to Grayscale:

plt.imshow(gray_img, cmap='gray')

3
plt.title('Grayscale Image')
plt.show()

c. Apply Gaussian Blurring:

blurred_img = cv2.GaussianBlur(gray_img, (5, 5), 0)


plt.imshow(blurred_img, cmap='gray')
plt.title('Blurred Image')
plt.show()

4. Apply Basic Image Processing Techniques:

a. Edge Detection (Canny):

edges = cv2.Canny(gray_img, 100, 200)


plt.imshow(edges, cmap='gray')
plt.title('Edge Detection')
plt.show()

b. Image Thresholding:

_, thresh_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)


plt.imshow(thresh_img, cmap='gray')
plt.title('Thresholded Image')
plt.show()

5. Display Histogram:

plt.hist(gray_img.ravel(), bins=256, range=[0, 256])


plt.title('Image Histogram')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.show()

Results:

 The image was successfully processed using various operations like resizing, blurring, edge
detection, and thresholding.

Applications:

 Pre-processing in computer vision.


 Feature extraction in machine learning.
 Enhancing images for visual inspection.

4
EXPERIMENT NO. 02
TO OBTAIN HISTOGRAM EQUALIZATION IMAGE

Aim:

To perform histogram equalization on a grayscale image and obtain an enhanced image with improved
contrast.

Theory:

Histogram equalization is a technique used to enhance the contrast of an image by redistributing the
pixel intensity values to span the entire range of intensity levels. This is achieved by modifying the
histogram of the image to be more uniform.

Steps:

1. Input Image: Select a grayscale image to process.


2. Compute Histogram: Calculate the histogram of the original image.
3. Cumulative Distribution Function (CDF): Compute the cumulative sum of the histogram,
normalizing it to fit within the intensity range (0–255).
4. Mapping Function: Use the CDF to map the original intensity values to new values.
5. Generate Equalized Image: Replace the original pixel values with the mapped values using
the computed transformation function.
6. Compare Results: Display the original and histogram-equalized images along with their
histograms.

Code Implementation:

Using Python and OpenCV:

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

# Load the grayscale image


image = cv2.imread('input_image.jpg', cv2.IMREAD_GRAYSCALE)

# Apply Histogram Equalization


equalized_image = cv2.equalizeHist(image)

# Plot original and equalized images with histograms


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

# Original Image and Histogram


plt.subplot(2, 2, 1)
plt.imshow(image, cmap='gray')

5
plt.title('Original Image')
plt.axis('off')

plt.subplot(2, 2, 2)
plt.hist(image.ravel(), bins=256, range=(0, 256), color='blue', alpha=0.7)
plt.title('Histogram of Original Image')

# Equalized Image and Histogram


plt.subplot(2, 2, 3)
plt.imshow(equalized_image, cmap='gray')
plt.title('Equalized Image')
plt.axis('off')

plt.subplot(2, 2, 4)
plt.hist(equalized_image.ravel(), bins=256, range=(0, 256), color='green', alpha=0.7)
plt.title('Histogram of Equalized Image')

plt.tight_layout()
plt.show()

Expected Output:

1. Original Image: The image with uneven intensity distribution.


2. Equalized Image: A new image with enhanced contrast.
3. Histograms:
o Original histogram is unevenly distributed.
o Equalized histogram is more uniform.

Applications:

 Medical Imaging (e.g., X-ray and MRI contrast enhancement)


 Remote Sensing (e.g., satellite imagery)
 Object Detection and Pattern Recognition

6
EXPERIMENT NO. 03
TO IMPLEMENT SMOOTHING OR AVERAGING FILTER IN
SPATIAL DOMAIN

Objective:

To reduce image noise and smooth an image by applying an averaging filter in the spatial domain.

Theory:

A smoothing filter is used to reduce noise and minor variations in an image. The averaging filter
replaces each pixel's value with the average of the pixel values in its neighborhood, effectively blurring
the image and reducing sharp transitions. It is implemented using convolution with a kernel.

Procedure:

1. Import Required Libraries:


o Use Python or MATLAB.

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

2. Load the Input Image:


o Convert it to grayscale for simplicity:

img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

3. Define the Smoothing Kernel:


o Create an averaging kernel, e.g., a 3x3 matrix:

kernel = np.ones((3, 3), np.float32) / 9

4. Apply the Averaging Filter:


o Perform convolution using OpenCV's filter2D function:

smoothed_img = cv2.filter2D(img, -1, kernel)

5. Display and Compare Results:


o Show the original and smoothed images:

plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(img, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 2, 2), plt.imshow(smoothed_img, cmap='gray'), plt.title('Smoothed
Image')
plt.show()

7
6. Save the Smoothed Image:
o Save the result:

cv2.imwrite('smoothed_image.jpg', smoothed_img)

Results:

 The output image will have reduced noise and smoother transitions compared to the original
image.

Applications:

 Image pre-processing to remove noise.


 Smoothing for feature extraction in computer vision.

8
EXPERIMENT NO. 04
PROGRAM FOR OPENING AND CLOSING OF THE IMAGE

Objective:

To perform morphological operations opening and closing on a binary or grayscale image to


demonstrate their effects.

Theory:

 Opening: An erosion operation followed by dilation. It removes small objects/noise.


 Closing: A dilation operation followed by erosion. It fills small holes and gaps.
Both operations are fundamental in morphological image processing, widely used in noise
reduction and shape analysis.

Procedure:

1. Import Necessary Libraries:

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

2. Load the Input Image:

img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

3. Define a Structuring Element:

 Use a kernel (e.g., 3x3 matrix):

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

4. Apply Morphological Opening:

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

5. Apply Morphological Closing:

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

6. Display the Results:

plt.figure(figsize=(15, 10))
plt.subplot(1, 3, 1), plt.imshow(img, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 3, 2), plt.imshow(opening, cmap='gray'), plt.title('Opening')

9
plt.subplot(1, 3, 3), plt.imshow(closing, cmap='gray'), plt.title('Closing')
plt.show()

7. Save the Results (Optional):

cv2.imwrite('opening_image.jpg', opening)
cv2.imwrite('closing_image.jpg', closing)

Results:

 Opening removes noise like small white regions in a binary image.


 Closing fills small black holes in objects or regions.

Applications:

 Noise removal in binary and grayscale images.


 Object segmentation and feature extraction.

10
EXPERIMENT NO. 05
TO FILL THE REGION OF INTEREST FOR THE IMAGE

Objective:

To identify and fill a specified region of interest (ROI) in an image using image processing techniques.

Theory:

Filling the region of interest involves identifying a specific area within an image (based on criteria like
shape, intensity, or location) and modifying its pixel values. This technique is widely used in
segmentation, masking, and highlighting significant regions in an image.

Procedure:

1. Import Necessary Libraries:

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

2. Load the Input Image:

img = cv2.imread('image.jpg', cv2.IMREAD_COLOR) # Load in color


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale

3. Define the Region of Interest (ROI):

 Manually or programmatically select the ROI.


 Example: Use a binary mask to mark the ROI:

roi = np.zeros_like(gray)
cv2.rectangle(roi, (50, 50), (200, 200), 255, -1) # Define a rectangle ROI

4. Apply Filling Operation:

 Use flood fill or mask the ROI with a specific value:

filled_img = img.copy()
cv2.floodFill(filled_img, None, (100, 100), (0, 255, 0)) # Fill with green

5. Highlight the ROI (Optional):

 Mask and modify the ROI values:

img[roi == 255] = (0, 0, 255) # Fill ROI with red

11
6. Display the Results:

plt.figure(figsize=(10, 5))
plt.subplot(1, 3, 1), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)), plt.title('Original
Image')
plt.subplot(1, 3, 2), plt.imshow(roi, cmap='gray'), plt.title('Region of Interest')
plt.subplot(1, 3, 3), plt.imshow(cv2.cvtColor(filled_img, cv2.COLOR_BGR2RGB)), plt.title('Filled
ROI')
plt.show()

7. Save the Output (Optional):

cv2.imwrite('filled_roi.jpg', filled_img)

Results:

 The specified ROI is filled with a particular value or color, making it distinct in the image.

Applications:

 Object filling in image segmentation.


 Masking and highlighting regions for analysis.
 Pre-processing for machine vision tasks.

12
EXPERIMENT NO. 06
PROGRAM FOR EDGE DETECTION ALGORITHM

Objective:

To detect edges in an image using edge detection algorithms.

Theory:

Edge detection is a process of identifying and locating sharp discontinuities in an image. These
discontinuities are caused by changes in pixel intensity. Popular algorithms include:

1. Sobel/Prewitt: Detects edges based on gradients.


2. Laplacian: Highlights regions of rapid intensity change.
3. Canny: A multi-stage algorithm for precise edge detection.

Procedure:

1. Import Necessary Libraries:

import cv2
import matplotlib.pyplot as plt

2. Load the Input Image:

 Convert the image to grayscale:

img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

3. Apply Edge Detection Algorithms:

a. Sobel Operator:

sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)


sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
sobel = cv2.magnitude(sobel_x, sobel_y)

b. Laplacian Operator:

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

c. Canny Edge Detection:

canny = cv2.Canny(img, 100, 200)

4. Display Results:

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

13
plt.subplot(2, 2, 1), plt.imshow(img, cmap='gray'), plt.title('Original Image')
plt.subplot(2, 2, 2), plt.imshow(sobel, cmap='gray'), plt.title('Sobel Edges')
plt.subplot(2, 2, 3), plt.imshow(laplacian, cmap='gray'), plt.title('Laplacian Edges')
plt.subplot(2, 2, 4), plt.imshow(canny, cmap='gray'), plt.title('Canny Edges')
plt.show()

5. Save the Results (Optional):

cv2.imwrite('sobel_edges.jpg', sobel)
cv2.imwrite('laplacian_edges.jpg', laplacian)
cv2.imwrite('canny_edges.jpg', canny)

Results:

 The edges in the image are detected and displayed for each algorithm.

Applications:

 Object detection and feature extraction.


 Image segmentation.
 Motion detection in video frames.

14
EXPERIMENT NO. 07
PROGRAM TO SHARPEN IMAGE USING GRADIENT MASK

Objective:

To sharpen an image by applying a gradient mask, enhancing the high-frequency components (edges)
of the image.

Theory:

Sharpening an image enhances its details by highlighting edges. The gradient mask highlights
transitions between areas of different intensities, thus making the image appear sharper. It is done by
applying a high-pass filter or a gradient operator.

Procedure:

1. Import Required Libraries:

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

2. Load and Display the Original Image:

 Read the image:

img = cv2.imread('image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray_img, cmap='gray')
plt.title('Original Image')
plt.show()

3. Create Gradient Mask for Sharpening:

 A simple gradient mask (kernel) can be created using the Laplacian operator or using the Sobel
operator.

kernel = np.array([[0, -1, 0],


[-1, 5,-1],
[0, -1, 0]]) # Example kernel for sharpening

4. Apply the Gradient Mask:

 Convolve the image with the gradient mask to sharpen it:

sharpened_img = cv2.filter2D(gray_img, -1, kernel)


plt.imshow(sharpened_img, cmap='gray')
plt.title('Sharpened Image Using Gradient Mask')

15
plt.show()

5. (Optional) Adjust the Sharpening:

 To enhance or reduce the sharpening, you can multiply the kernel by a scaling factor:

kernel = kernel * 1.5 # Increase sharpening effect


sharpened_img = cv2.filter2D(gray_img, -1, kernel)
plt.imshow(sharpened_img, cmap='gray')
plt.title('Enhanced Sharpened Image')
plt.show()

6. Save the Resulting Image:

cv2.imwrite('sharpened_image.jpg', sharpened_img)

Results:

 The image has been sharpened, enhancing edges and high-frequency components.

Applications:

 Image enhancement for clearer details.


 Edge detection and feature extraction in computer vision tasks.
 Preparation for object recognition or image segmentation.

16
EXPERIMENT NO. 08
PROGRAM FOR MORPHOLOGICAL OPERATION : EROSION AND
DILATION

Objective:

To apply the morphological operations erosion and dilation on an image, which are used to process
binary and grayscale images in various ways, such as removing noise or enhancing object shapes.

Theory:

 Erosion: Reduces the size of objects in a binary image by eroding away the boundaries. It
removes small white regions or noise.
 Dilation: Expands the boundaries of objects in a binary image, filling small holes and gaps.

Procedure:

1. Import Necessary Libraries:

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

2. Load the Input Image:

 Load the image in grayscale:

img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

 Convert to binary by thresholding (if needed):

_, binary_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

3. Define the Structuring Element:

 Define a kernel (structuring element) to perform erosion and dilation:

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

4. Apply Erosion:

 Apply the erosion operation to the binary image:

eroded_img = cv2.erode(binary_img, kernel, iterations=1)

5. Apply Dilation:

17
 Apply the dilation operation to the binary image:

dilated_img = cv2.dilate(binary_img, kernel, iterations=1)

6. Display the Results:

plt.figure(figsize=(15, 10))
plt.subplot(1, 3, 1), plt.imshow(binary_img, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 3, 2), plt.imshow(eroded_img, cmap='gray'), plt.title('Erosion')
plt.subplot(1, 3, 3), plt.imshow(dilated_img, cmap='gray'), plt.title('Dilation')
plt.show()

7. Save the Output (Optional):

cv2.imwrite('eroded_image.jpg', eroded_img)
cv2.imwrite('dilated_image.jpg', dilated_img)

Results:

 Erosion reduces the object size and removes noise in the image.
 Dilation enlarges objects and fills small holes.

Applications:

 Noise removal (erosion).


 Filling small holes or gaps in objects (dilation).
 Object boundary extraction and analysis.

18
EXPERIMENT NO. 09
PROGRAM FOR DCT/IDCT COMPUTATION

Objective:

To compute the Discrete Cosine Transform (DCT) and Inverse Discrete Cosine Transform (IDCT)
on an image, which are widely used for image compression and feature extraction.

Theory:

 DCT: Transforms an image from the spatial domain to the frequency domain. It concentrates
the energy in a smaller number of coefficients, which makes it useful in image compression
(e.g., JPEG compression).
 IDCT: Inverse transform that converts the image from the frequency domain back to the spatial
domain.

Procedure:

1. Import Required Libraries:

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

2. Load the Input Image:

 Load the image and convert it to grayscale (for simplicity):

img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

3. Apply DCT:

 Use OpenCV to apply the DCT to the image:

dct_img = cv2.dct(np.float32(img)) # DCT on the image


plt.imshow(np.log(np.abs(dct_img)), cmap='gray')
plt.title('DCT of Image')
plt.show()

4. Apply IDCT:

 Use OpenCV to apply the IDCT and reconstruct the image:

idct_img = cv2.idct(dct_img) # Inverse DCT to get the image back


plt.imshow(idct_img, cmap='gray')
plt.title('Reconstructed Image after IDCT')
plt.show()

19
5. Display Results:

plt.figure(figsize=(10, 10))
plt.subplot(1, 3, 1), plt.imshow(img, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 3, 2), plt.imshow(np.log(np.abs(dct_img)), cmap='gray'), plt.title('DCT Image')
plt.subplot(1, 3, 3), plt.imshow(idct_img, cmap='gray'), plt.title('IDCT Reconstructed Image')
plt.show()

6. Save the Output (Optional):

cv2.imwrite('dct_image.jpg', dct_img)
cv2.imwrite('idct_image.jpg', idct_img)

Results:

 The image is transformed to the frequency domain using DCT.


 The image is reconstructed back using IDCT with minimal loss if compression is not applied.

Applications:

 Image Compression (JPEG).


 Feature Extraction for image recognition and analysis.
 Signal Processing in image and video data.

20

You might also like