Mahak DIP

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

Lab File

Digital Image Processing


CS3EA14(P)

Branch: CSE
Section: 5CSE-
AI
Year/Semester: III Year/ V

SUBMITTED TO: SUBMITTED BY:


Prof. Ankita Chourasia Mahak Dalal
(EN22CS304040)

Department of Computer Science & Engineering


Faculty of Engineering
MEDI-CAPS UNIVERSITY, INDORE-453331
Session :August-December 2024
INDEX

Experiment Submission
S.No. Experiment Name Signature Remark
Date Date

Introduction to MATLAB
1

Image Sampling and Quantization


2

Intensity Transformation of Images


3

DFT analysis of Images


4

Histogram Processing
5
Image Enhancement- Spatial filtering
6

7
Image Enhancement-Filtering
in frequency domain

8 Edge detection

Line detection
9

Point detection
10
EXPERIMENT NO.– 01

Introduction to MATLAB

Theory:
- MATLAB (Matrix Laboratory) is a high-performance programming language and computing
environment developed by MathWorks, Inc. in 1984. It is designed for numerical computations, including
matrix manipulations, plotting of functions and data, implementation of algorithms, and creating user
interfaces.

MATLAB consists of:


- Command Window: For entering and executing commands interactively. Commands entered here are not
saved.
- Editor (Script): Used for writing and saving larger programs. Files created here have the .m extension.
- Workspace: Displays variables created during a session, helping track data.
- Command History: Logs previously executed commands, showing a timeline of all commands used in
current and previous sessions.

- Key Features of MATLAB for Digital Image Processing


1. Image Representation and Data Types:
Supports various formats: JPEG, PNG, TIFF.
Works with images as data types like uint8 and double.

2. Image Import and Export


Read and write images using imread and imwrite functions.
img = imread('example.png'); % Load an image
imwrite(img, 'output_image.jpg'); % Save the image

3. Image Enhancement
Adjust contrast with imadjust.
Perform histogram equalization using histeq.
enhanced_img = imadjust(img); % Adjust contrast
eq_img = histeq(img); % Perform histogram equalization

4. Image Filtering and Noise Reduction


Apply Gaussian filtering or smoothing.
Reduce noise using median filtering.
gaussian_filter = fspecial('gaussian');
filtered_img = imfilter(img, gaussian_filter); % Apply Gaussian filter
denoised_img = medfilt2(img); % Apply median filtering

5. Image Transformation
Resize, rotate, or crop images using built-in functions.
resized_img = imresize(img, 0.5); % Scale down the image by half
rotated_img = imrotate(img, 45); % Rotate the image by 45 degreescropped_img = imcrop(img, [x y
width height]); % Crop image to a specific region

3
Mahak Dalal
EN22CS304040
6. Image Segmentation
Convert to binary using imbinarize.
Measure region properties with regionprops.
binary_img = imbinarize(rgb2gray(img)); % Convert to binary image
region_info = regionprops(binary_img, 'Area', 'Centroid'); % Extract region properties

7. Feature Extraction
Detect edges using edge detection algorithms like Canny.
Find corners in the image using detectHarrisFeatures.
edges = edge(rgb2gray(img), 'Canny'); % Detect edges
corners = detectHarrisFeatures(rgb2gray(img)); % Detect corners

8. Image Analysis with Fourier and Wavelet Transform


Analyze frequency components with Fourier Transform.
Decompose images using Wavelet Transform.
% Fourier Transform:
freq_img = fft2(img); % Frequency domain representation
freq_shifted = fftshift(freq_img); % Shift zero frequency to the center
% Wavelet Transform:
[C, S] = wavedec2(img, 2, 'haar'); % Decompose image with Wavelet transform

9. Morphological Operations
Perform morphological operations like dilation and erosion using imdilate and imerode.
se = strel('disk', 5); % Create a disk-shaped structuring element
dilated_img = imdilate(binary_img, se); % Apply dilation

10. Image Restoration and Reconstruction


Apply noise reduction and reconstruct missing parts of an image.
% Median filtering for noise reduction:
denoised_img = medfilt2(img); % Apply median filter to remove noise

11. Machine Learning and Deep Learning


Leverage machine learning models for classification tasks, including using pre-trained deep learning
networks for image classification and object detection.
net = alexnet; % Load a pre-trained deep learning network
label = classify(net, img); % Classify the image using the deep learning model

12. Custom Algorithms


Develop and implement custom image processing functions based on your requirements.
function output_img = customProcessing(input_img)
% Example of a custom image processing function
% Adjust contrast and apply Gaussian blur
output_img = imadjust(input_img);
output_img = imfilter(output_img, fspecial('gaussian', [3 3], 0.5));
end

4
Mahak Dalal
EN22CS304040
13. Integration with Other Tools
Integrate MATLAB with Simulink for real-time processing or with other programming languages like C,
C++, and Python for custom workflows.
% Example: Call external C function in MATLAB
mex myFunction.c % Compile C code to be used in MATLAB
output = myFunction(input); % Call the compiled C function

14. Interactive Tools


Use the App Designer to create custom Graphical User Interfaces (GUIs) for interactive image processing
applications.
% Example: Create an app with interactive image processing tools
app = uifigure;
ax = uiaxes('Parent', app);
imshow(img, 'Parent', ax); % Display an image in the app
.

5
Mahak Dalal
EN22CS304040
EXPERIMENT NO.– 02
Image Sampling and Quantization

Theory:
Image sampling and quantization are fundamental concepts in digital image processing, used to convert
analog images into a digital form that can be processed, stored, and displayed by digital systems. Here's an
overview of these concepts:

Image Sampling:
Sampling refers to the process of converting a continuous image into a discrete image. It involves selecting a
finite number of sample points from the continuous image. In simpler terms, it’s about how often you capture
data points from an image.

1. Grid Formation: The continuous image is divided into a grid of pixels. Each pixel represents a specific area
of the image.

2. Resolution: The resolution of an image is determined by the grid's density. Higher resolution means a higher
number of pixels per unit area, which translates to more detail.

3. Sampling Rate: The sampling rate, or spatial resolution, is the number of samples (pixels) taken per unit
distance in the image. A higher sampling rate captures more detail but requires more data.

Image Quantization:
Quantization refers to the process of mapping the sampled values to a finite range of discrete values. This
step is crucial because it reduces the infinite range of possible colors (or intensities) to a manageable number
of levels that a digital system can handle.

1. Color Depth: The number of bits used to represent each pixel's color or intensity. For instance, an 8-bit depth
allows for 256 possible values (levels), while a 24-bit depth (often used for color images) allows for over 16
million colors.

2. Gray Levels: For grayscale images, quantization determines the number of different shades of gray that can
be represented. A common example is 256 gray levels (8-bit grayscale).

3. Color Quantization: For color images, quantization involves mapping color values to a limited palette of
colors, which simplifies storage and processing but can affect image quality.

CODE:
% Load a grayscale image
img = imread('cameraman.tif'); % You can replace this with your own image file

% Display original image


figure; imshow(img);
title('Original Image');

% Quantization: Reduce the number of gray levels


% Convert the image to double precision
imgDouble = im2double(img);

% Define the number of quantization levels


numLevels = 16; % For example, reducing to 16 gray levels

6
Mahak Dalal
EN22CS304040
% Quantize the image
quantizedImg = round(imgDouble * (numLevels - 1)) / (numLevels - 1);

% Convert quantized image to uint8 for display


quantizedImg = im2uint8(quantizedImg);

% Display quantized image


figure; imshow(quantizedImg);
title(['Quantized Image']);

OUTPUT:

Original Image Quantized Image

7
Mahak Dalal
EN22CS304040
EXPERIMENT NO.– 03
Intensity Transformation of Images

Theory:

Intensity transformation is a fundamental concept in image processing that involves modifying the brightness and
contrast of an image. It focuses on changing the pixel intensity values to enhance certain features or to prepare the
image for further analysis. Here’s a breakdown of the theory behind intensity transformations:

Basic Concepts

1. Pixel Intensity: Each pixel in an image has an intensity value, typically ranging from 0 (black) to
255 (white) in an 8-bit grayscale image. The intensity determines the brightness of the pixel.

2. Transformation Function: An intensity transformation involves applying a function \( T \) to


the intensity values of the pixels. The output pixel value is computed as:
\[ g(x, y) = T(f(x, y)) \]
where \( f(x, y) \) is the input pixel intensity at coordinates \( (x, y) \), and \( g(x, y) \) is the transformed
pixel intensity.

Types of Intensity Transformations

1. Linear Transformations:
- Contrast Stretching: Increases the range of intensity values to improve contrast. The
transformation can be expressed as:
\[ g = \frac{(f - f_{min})}{(f_{max} - f_{min})} \cdot (L - 1) \]
where \( L \) is the number of intensity levels.

2. Non-linear Transformations:
- Logarithmic Transformation: Useful for enhancing dark regions in an image. The transformation function is:
\[ g = c \cdot \log(1 + f)\]
where \( c \) is a constant that adjusts the brightness.

- Exponential Transformation: Enhances bright regions and can be defined as:


\[g = c \cdot e^{f} \]

- Power Law (Gamma Correction): Adjusts the brightness and contrast using a power function:
\[g = c \cdot f^\gamma \]
where \( \gamma \) is the gamma value that determines the nature of the transformation (e.g., \( \gamma < 1 \)
for lightening, \( \gamma > 1 \) for darkening).

3. Piecewise Linear Transformations:


- Involves defining different linear transformations over different intensity ranges. This can
enhance specific features in the image.

4. Histogram Equalization
A specific intensity transformation technique aimed at improving contrast is histogram equalization,
which redistributes the intensity values across the histogram for better visual representation. This is achieved by:

1. Calculating the histogram of the image.


2. Computing the cumulative distribution function (CDF).
3. Mapping the original intensity values to new values based on the CDF.

8
Mahak Dalal
EN22CS304040
CODE:
% Read the image
img = imread('your_image.jpg'); % Replace with your image path
img_gray = rgb2gray(img); % Convert to grayscale if it's a color image
imshow(img_gray);

% Linear Transformation
% Define the transformation parameters
a = 1; % scaling factor
b = 0; % bias

% Apply linear transformation


img_linear = a * double(img_gray) + b;
img_linear = uint8(min(max(img_linear, 0), 255)); % Ensure values are in [0, 255]
figure;
imshow(img_linear);
title('Linear Intensity Transformation');

% Save the transformed images if needed


imwrite(img_linear, 'linear_transformed_image.jpg');

Output:

9
Mahak Dalal
EN22CS304040
EXPERIMENT NO.– 04
DFT analysis of Images
Theory:
The Discrete Fourier Transform (DFT) is a powerful mathematical tool used in image processing to
analyze the frequency components of digital images. By transforming spatial data (pixel values) into the
frequency domain, DFT allows us to understand how different frequency elements contribute to the overall
image.

Concept of DFT
In the context of images, DFT decomposes an image into its sinusoidal components. Each pixel's
intensity is represented in terms of frequency, where low frequencies correspond to smooth variations
(such as gradual color changes) and high frequencies correspond to sharp edges and noise. The DFT of a 2D
image \( f(x, y) \) is defined as:

\[F(u, v) = \sum_{x=0}^{M-1} \sum_{y=0}^{N-1} f(x, y) \cdot e^{-j2\pi\left(\frac{ux}{M}


+ \frac{vy}{N}\right)}\]

where \( M \) and \( N \) are the dimensions of the image, and \( F(u, v) \) represents the frequency
domain representation.

Applications
1. Image Filtering: DFT enables the design of filters to enhance or suppress certain frequencies. Low-pass
filters can smooth images by removing high-frequency noise, while high-pass filters can highlight
edges.

2. Compression: Techniques like JPEG compression utilize DFT (specifically, a related transform
called the Discrete Cosine Transform) to reduce the amount of data required to represent an image
while maintaining visual quality.

3. Feature Extraction: DFT can help in identifying and extracting features from images, which
is crucial in tasks like pattern recognition and computer vision.

4. Image Reconstruction: By manipulating frequency components, DFT facilitates image


reconstruction from incomplete data, commonly used in applications like MRI imaging.

Code:
% Read the image
img = imread('your_image.jpg'); % Replace with your image file
gray_img = rgb2gray(img); % Convert to grayscale if it's a color image

% Display the original image


figure;
subplot(1, 2, 1);
imshow(gray_img);

% Perform the 2D Fast Fourier Transform


F = fft2(double(gray_img));
F_shifted = fftshift(F); % Shift zero frequency component to the center

% Compute the magnitude spectrum


magnitude_spectrum = log(abs(F_shifted) + 1); % Use log scale for better visualization

1
Mahak Dalal 0
EN22CS304040
% Display the magnitude spectrum

1
Mahak Dalal 1
EN22CS304040
subplot(1, 2, 2);
imshow(magnitude_spectrum, []);
title('Magnitude Spectrum');
colormap jet; % Optional: Change colormap for better visualization

% Optionally, apply a low-pass filter (example)


[M, N] = size(gray_img);
[x, y] = meshgrid(1:N, 1:M);
D0 = 30; % Cutoff frequency
H = double(sqrt((x - N/2).^2 + (y - M/2).^2) <= D0); % Low-pass filter

% Apply the filter in the frequency domain


F_filtered = F_shifted .* H;

% Compute the inverse FFT to get the filtered image


filtered_img = ifft2(ifftshift(F_filtered));
filtered_img = abs(filtered_img); % Take the absolute value

% Display the filtered


image figure;
imshow(filtered_img, []);

Output:

1
Mahak Dalal 2
EN22CS304040

You might also like