21BEC1484- CONSOLIDATED
21BEC1484- CONSOLIDATED
(BECE316E)
LAB EXPERIMENTS
(Consolidated file)
Submitted to
Dr. P. Nirmala
Submitted by
Vadde Surya Teja
21BEC1484
1
Contents
2
LAB EXPERIMENT -1
Digital Image Processing
Aim: To apply basic operations of image processing on images and observe the
result accordingly
Procedure:
Code:
% Read the image
3
subplot(2, 2, 2);
imshow(redChannel);
title('Red Channel');
subplot(2, 2, 3);
imshow(greenChannel);
title('Green Channel');
subplot(2, 2, 4);
imshow(blueChannel);
title('Blue Channel');
Output:
2. Image negative
Code:
% Read the RGB image
img = imread('/MATLAB Drive/DIP/images/city.jpeg');
% Convert to grayscale
gray_img = rgb2gray(img);
% Define the center region (5x5 grid at the center)
center_x = size(gray_img, 2) / 2; % X-coordinate of the center of
the grid
center_y = size(gray_img, 1) / 2; % Y-coordinate of the center of
the grid
grid_size = 5; % Size of the grid
% Calculate the region of interest
x_start = round(center_x - grid_size / 2);
x_end = round(center_x + grid_size / 2);
y_start = round(center_y - grid_size / 2);
y_end = round(center_y + grid_size / 2);
% Ensure the region is within image bounds
x_start = max(x_start, 1);
x_end = min(x_end, size(gray_img, 2));
y_start = max(y_start, 1);
4
y_end = min(y_end, size(gray_img, 1));
% Extract the region of interest from grayscale image
gray_grid = gray_img(y_start:y_end, x_start:x_end);
% Create the negative grayscale image
negative_gray_img = 255 - gray_img;
% Extract the corresponding region from negative grayscale image
negative_gray_grid = negative_gray_img(y_start:y_end, x_start:x_end);
% Display the grayscale image, negative image, and grids in a figure
figure;
% Original grayscale image with grid
subplot(2, 2, 1);
imshow(gray_img);
hold on;
rectangle('Position', [x_start-0.5, y_start-0.5, grid_size,
grid_size], 'EdgeColor', 'r', 'LineWidth', 2);
title('Grayscale Image with Grid');
% Negative grayscale image with grid
subplot(2, 2, 2);
imshow(negative_gray_img);
hold on;
rectangle('Position', [x_start-0.5, y_start-0.5, grid_size,
grid_size], 'EdgeColor', 'r', 'LineWidth', 2);
title('Negative Grayscale Image with Grid');
% Grayscale grid
subplot(2, 2, 3);
imshow(gray_grid);
title('Grayscale Grid');
% Negative grayscale grid
subplot(2, 2, 4);
imshow(negative_gray_grid);
title('Negative Grayscale Grid');
Output:
5
3. Interpolation (Nearest Neighbour)
Code:
% Read the original image
original_img = imread('/MATLAB Drive/DIP/images/ave2.jpg');
% Display the original image
figure;
subplot(1, 2, 1);
imshow(original_img);
title('Original Image');
% Get original image resolution
[height_original, width_original, ~] = size(original_img);
disp(['Original Image Resolution: ', num2str(width_original), ' x ',
num2str(height_original)]);
% Define the scale factor for resizing
scale_factor = 2; % Enlarge the image by a factor of 2
% Perform nearest neighbor interpolation
resized_img = imresize(original_img, scale_factor, 'nearest');
% Display the resized image
subplot(1, 2, 2);
imshow(resized_img);
title('Nearest Neighbor Interpolation');
% Get resized image resolution
[height_resized, width_resized, ~] = size(resized_img);
disp(['Resized Image Resolution: ', num2str(width_resized), ' x ',
num2str(height_resized)]);
6
Output:
Interpolation ( Bilinear)
Code:
% Read the original image
original_img = imread('peppers.png');
% Display the original image
figure;
subplot(1, 2, 1);
imshow(original_img);
title('Original Image');
% Get original image resolution
[height_original, width_original, ~] = size(original_img);
disp(['Original Image Resolution: ', num2str(width_original), ' x ',
num2str(height_original)]);
% Define the scale factor for resizing
scale_factor = 2; % Enlarge the image by a factor of 2
% Perform bilinear interpolation
resized_img = imresize(original_img, scale_factor, 'bilinear');
% Display the resized image
subplot(1, 2, 2);
imshow(resized_img);
title('Bilinear Interpolation');
% Get resized image resolution
[height_resized, width_resized, ~] = size(resized_img);
disp(['Resized Image Resolution: ', num2str(width_resized), ' x ',
num2str(height_resized)]);
7
Output:
4. Flipping an image
Code:
% Read the image
img = imread('/MATLAB Drive/DIP/images/city.jpeg');
% Display the original image
figure;
subplot(2, 2, 1);
imshow(img);
title('Original Image');
% Flip the image horizontally
flipped_horizontal = fliplr(img);
% Display the horizontally flipped image
subplot(2, 2, 2);
imshow(flipped_horizontal);
title('Horizontally Flipped Image');
% Flip the image vertically
flipped_vertical = flipud(img);
% Display the vertically flipped image
subplot(2, 2, 3);
imshow(flipped_vertical);
title('Vertically Flipped Image');
% Flip the image both horizontally and vertically (equivalent to
rotating 180 degrees)
flipped_both = flipud(fliplr(img));
% Display the image flipped both horizontally and vertically
subplot(2, 2, 4);
imshow(flipped_both);
title('Horizontally and Vertically Flipped Image');
8
Output:
Result: Hence we have successfully observed all the changes and understood
the image processing techniques successfully.
Verification:
9
Lab Experiment -2
Aim: To perform given transformations on images using matlab and observe the result.
1. Histogram calculation
Algorithm:
Code:
10
Output:
2. Histogram Equalisation
Algorithm:
1. Take the input image using imread.
2. If the image is in RGB convert it into gray scale image.
3. Using imhist function calculate the histogram values as count and graylevels.
4. Convert the image into equalized hist using histeq function.
5. Plot the histogram as a bar plot using these values and specify the labels accordingly.
Code:
% Read the input image
imageFileName = '/MATLAB Drive/DIP/images/vibrant.jpg'; % Replace with your image file name
img = imread(imageFileName);
11
% Plot the histogram of the original image
figure;
subplot(2, 2, 1); % Create a 2x2 grid of plots and select the first
bar(grayLevels, counts);
xlabel('Pixel Intensity');
ylabel('Frequency');
title('Histogram of Original Image');
% Display counts and gray levels for original and equalized histograms
disp('Original Image Counts:');
disp(counts);
disp('Original Image Gray Levels:');
disp(grayLevels);
Output:
12
3. Logarithmic nd inverse log transformation
Algorithm:
Read Input Image:
a = imread('/MATLAB Drive/DIP/images/vibrant.jpg');
Convert to Grayscale:
b = rgb2gray(a);
b = double(b) / 255;
c = log(1 + b);
c = mat2gray(c);
d = exp(c) - 1;
d = mat2gray(d);
Display Original, Log Transformed, and Inverse Transformed Images with Histograms:
Code:
clc;
clear all;
close all;
a = imread('/MATLAB Drive/DIP/images/vibrant.jpg');
b = rgb2gray(a);
b = double(b) / 255;
c = log(1 + b);
c = mat2gray(c);
d = exp(c) - 1;
d = mat2gray(d);
figure;
subplot(3,2,1);
imshow(b);
13
title('Original Grayscale Image');
subplot(3,2,2);
imhist(b);
title('Histogram of Original Image');
xlabel('Intensity Level');
ylabel('Frequency');
subplot(3,2,3);
imshow(c);
title('Logarithmically Transformed Image');
subplot(3,2,4);
imhist(c);
title('Histogram of Transformed Image');
xlabel('Intensity Level');
ylabel('Frequency');
subplot(3,2,5);
imshow(d);
title('Inverse Logarithmically Transformed Image');
subplot(3,2,6);
imhist(d);
title('Histogram of Inverse Transformed Image');
xlabel('Intensity Level');
ylabel('Frequency');
Output:
14
4. Power law transformation
Algorithm:
a = imread('/MATLAB Drive/DIP/images/city.jpeg');
b = rgb2gray(a);
b = double(b) / 255; % Normalize to range [0, 1]
Extract grid from original image: originalGrid = b(rowStart:rowStart + gridSize - 1, colStart:colStart + gridSize - 1);
Extract grid from transformed image: powerLawGrid = c(rowStart:rowStart + gridSize - 1, colStart:colStart + gridSize -
1);
Display original grid pixel values: disp('Original 3x3 Grid Pixel Values:'); disp(originalGrid);
Display transformed grid pixel values: disp('Power Law Transformed 3x3 Grid Pixel Values:'); disp(powerLawGrid);
15
Code:
clc;
clear all;
close all;
% Original Image
subplot(2,2,1);
imshow(b);
title('Original Grayscale Image');
subplot(2,2,2);
imhist(b);
title('Histogram of Original Image');
xlabel('Intensity Level');
ylabel('Frequency');
subplot(2,2,4);
imhist(c);
title('Histogram of Transformed Image');
xlabel('Intensity Level');
ylabel('Frequency');
% Extract the 3x3 grid from the original and power-law transformed images
originalGrid = b(rowStart:rowStart + gridSize - 1, colStart:colStart + gridSize - 1);
powerLawGrid = c(rowStart:rowStart + gridSize - 1, colStart:colStart + gridSize - 1);
16
title('Original Image Grid (3x3)');
Output:
gamma: 2
17
Gamma scale =0.5
18
Output Verification:
Result: Hence we have successfully observed the use and effect of different transformations on the input
images and observed their effect on them.
19
LAB-3
DIGITAL IMAGE PROCESSING
Name: V Surya Teja
REG number: 21BEC1484
Aim: To perform different actions and apply filters on input images and observe the changes
accordingly.
Algorithm:
Use imread to load the image into MATLAB. Ensure the image is in grayscale (e.g.,
using 'coins.png').
Convert the extracted bit plane to a logical image using logical function, which
helps in visualizing the bit plane.
If the image has more than 8 bits per pixel (e.g., 16-bit image), repeat the above steps
for the remaining bit planes.
20
Code:
A=imread('coins.png');
B=bitget(A,1);
figure,
subplot(2,2,1);imshow(logical(B));title('Bit plane 1');
B=bitget(A,2);
subplot(2,2,2);imshow(logical(B));title('Bit plane 2');
B=bitget(A,3);
subplot(2,2,3);imshow(logical(B));title('Bit plane 3');
B=bitget(A,4);
subplot(2,2,4);imshow(logical(B));title('Bit plane 4');
B=bitget(A,5);
figure,
subplot(2,2,1);imshow(logical(B));title('Bit plane 5');
B=bitget(A,6);
subplot(2,2,2);imshow(logical(B));title('Bit plane 6');
B=bitget(A,7);
subplot(2,2,3);imshow(logical(B));title('Bit plane 7');
B=bitget(A,8);
subplot(2,2,4);imshow(logical(B));title('Bit plane 8');
Output:
21
2. Smoothening image
Algorithm:
Read and Convert Image:
Apply Gaussian filters with different standard deviations (2, 4, and 8) using
imgaussfilt.
Add Gaussian noise to the grayscale image using imnoise for demonstration
purposes.
Display Results:
Create a figure with subplots to show the original grayscale image, noisy image,
averaging-filtered image, and Gaussian-filtered image.
Create another figure to display the smoothed images with different Gaussian filter
parameters.
Create a figure with subplots to show histograms for the original image, noisy image,
averaging-filtered image, and Gaussian-filtered image.
Code:
clc;
clc;
clear all;
close all;
I = imread('/MATLAB Drive/DIP/images/feather.jpg');
I_gray = rgb2gray(I);
22
%gaussian filter applu
Iblur1 = imgaussfilt(I_gray,2);
Iblur2 = imgaussfilt(I_gray,4);
Iblur3 = imgaussfilt(I_gray,8);
figure;
%smoohening results
figure
23
subplot(2,2,2);imshow(Iblur2);title('Smoothed image, \sigma = 4');
figure;
Outputs:
24
25
3. Sharpening
Algorithm:
Load and Convert Image:
Display Images:
Create a figure with subplots to show the original grayscale image, sharpened image,
and high-pass filtered image.
Display Histograms:
Create a new figure with subplots to show the histograms for the original grayscale
image, sharpened image, and high-pass filtered image.
Code:
if size(inputImage, 3) == 3
grayImage = rgb2gray(inputImage);
else
grayImage = inputImage;
end
26
% Apply the Laplacian filter to the grayscale image
% Enure the sharpened image values are within valid range [0, 255]
% Ensure the high-pass filtered image values are within valid range [0, 255]
% Display the original, sharpened, and high-pass filtered images in one figure
figure;
subplot(1, 3, 1);
imshow(grayImage);
title('Original Image');
subplot(1, 3, 2);
imshow(sharpenedImage);
title('Sharpened Image');
subplot(1, 3, 3);
imshow(highPassFilteredImage);
27
% Display the histograms of the original, sharpened, and high-pass filtered images in another figure
figure;
subplot(1, 3, 1);
imhist(grayImage);
subplot(1, 3, 2);
imhist(sharpenedImage);
subplot(1, 3, 3);
imhist(highPassFilteredImage);
Output:
28
Output Verification:
Result: Hence we have successfully observed the changes in the input and output images accordingly.
29
Lab 4
I. Smootheing
Code:
% Read an example image
% Display images
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(smoothed_image_gaussian3x3);
title('Gaussian Filter 3x3');
subplot(2, 2, 3);
imshow(smoothed_image_gaussian5x5);
title('Gaussian Filter 5x5');
subplot(2, 2, 4);
30
imshow(smoothed_image_gaussian7x7);
title('Gaussian Filter 7x7');
output:
% Display images
31
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(smoothed_image_mean3x3);
title('Mean Filter 3x3');
subplot(2, 2, 3);
imshow(smoothed_image_mean5x5);
title('Mean Filter 5x5');
subplot(2, 2, 4);
imshow(smoothed_image_mean7x7);
title('Mean Filter 7x7');
32
3. Using laplacian filter
code:
% Display images
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(smoothed_image_gaussian3x3);
title('Gaussian Filter 3x3');
subplot(2, 2, 3);
imshow(smoothed_image_gaussian5x5);
title('Gaussian Filter 5x5');
subplot(2, 2, 4);
imshow(smoothed_image_gaussian7x7);
title('Gaussian Filter 7x7');
33
II. SHARPENING
1. Using Guassian
code:
% Read an example image
34
% Apply Gaussian blurs
blurred_image3x3 = imfilter(image, h_gaussian3x3, 'replicate');
blurred_image5x5 = imfilter(image, h_gaussian5x5, 'replicate');
blurred_image7x7 = imfilter(image, h_gaussian7x7, 'replicate');
% Display images
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(sharpened_image3x3);
title('Sharpened 3x3');
subplot(2, 2, 3);
imshow(sharpened_image5x5);
title('Sharpened 5x5');
subplot(2, 2, 4);
imshow(sharpened_image7x7);
title('Sharpened 7x7');
35
2. Laplace
code:
% Read an example image
% Display images
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(laplacian_image, []);
title('Laplacian Filtered Image');
subplot(2, 2, 3);
imshow(sharpened_image);
title('Sharpened Image');
36
3. mean filter
code:
% Read an example image
37
sharpened_image3x3 = uint8(mat2gray(sharpened_image3x3) * 255);
sharpened_image5x5 = uint8(mat2gray(sharpened_image5x5) * 255);
sharpened_image7x7 = uint8(mat2gray(sharpened_image7x7) * 255);
% Display images
figure;
subplot(2, 2, 1);
imshow(image);
title('Original Image');
subplot(2, 2, 2);
imshow(sharpened_image3x3);
title('Sharpened 3x3 Mean Filter');
subplot(2, 2, 3);
imshow(sharpened_image5x5);
title('Sharpened 5x5 Mean Filter');
subplot(2, 2, 4);
imshow(sharpened_image7x7);
title('Sharpened 7x7 Mean Filter');
38
Output Verification :
Inference:
Applying smoothing and sharpening processes using Gaussian, Laplace, and Mean filters of
various sizes (3x3, 5x5, 7x7) revealed that larger kernels produced stronger blurring effects in
smoothing, with Gaussian effectively reducing noise while preserving details. The Mean
filter uniformly smoothed the image, but larger kernels caused more blur. In sharpening, the
Laplace filter enhanced edges by emphasizing regions of rapid intensity change, though
larger kernels could also amplify noise. The filter choice and size determined the balance
between noise reduction, detail preservation, and edge enhancement.
Result:
Hence we have successfully performed smoothening and sharpening of input images using
different filters and observed the result accordingly.
39
LAB-5
Digital image processing
Aim: To perform DCT on input images using different grid sizes as well as perform inverse
DCT and analyze the errors using different techniques.
1.2D-DCT
Code:
% Read the input image
% Apply 2D DCT
dct_image = dct2(double(gray_image));
40
title('DCT Image (Log Scale)');
% Optionally, you can display the DCT coefficients with a colormap for better visibility
figure;
imshow(log(abs(dct_image) + 1), []); % Added 1 to avoid log(0) issue
colormap(jet);
colorbar;
title('DCT Coefficients (Log Scale with Colormap)');
Output:
Inference: We can observe that the output image after applying the transformation has lost
all the frequency contents and is hence without any clarity. Seeing the log scale image it is a
little better than the RAW image as it helps to enhance the details by a little.
41
2. Applying using 8x8 grid
Code:
% Read the input image
% Store the DCT coefficients in the corresponding location in the output image
dct_image(i:i+block_size-1, j:j+block_size-1) = dct_block;
end
end
subplot(1, 2, 1);
imshow(gray_image);
title('Original Image');
subplot(1, 2, 2);
imshow(log(abs(dct_image)), []);
title('DCT Image (8x8 block, log scale)');
% Optionally, you can display the DCT coefficients in a more visible way
figure;
42
imshow(log(abs(dct_image)), []);
colormap(jet);
colorbar;
title('DCT Coefficients (8x8 block, log scale, with colormap)');
Outputs:
Inference: Here we can observe the details in the output images after applying the 8x8 block
DCT. The respective color map also shows the detail orientation and distribution in the given
picture.
43
3. Using 16x16 grid:
code:
% Read the input image
% Store the DCT coefficients in the corresponding location in the output image
dct_image(i:i+block_size-1, j:j+block_size-1) = dct_block;
end
end
subplot(1, 2, 1);
imshow(gray_image);
title('Original Image');
subplot(1, 2, 2);
imshow(log(abs(dct_image)), []);
title('DCT Image (16x16 block, log scale)');
% Optionally, you can display the DCT coefficients in a more visible way
figure;
imshow(log(abs(dct_image)), []);
44
colormap(jet);
colorbar;
title('DCT Coefficients (16x16 block, log scale, with colormap)');
Output:
Inference: As we can see here similar to the 8x8 block the 16x16 also gave us the
transformed image accordingly but if we observe keenly the 16x16 is less detailed than the
8x8 because the 16x16 gets lesser number of blocks with the analyzing and hence lesser
frequencies get transformed .The same thing can be observed with the colormap as well.
45
4. Inverse DCT:
Code:
% Read the input image
% Store the DCT coefficients in the corresponding location in the output image
dct_image(i:i+block_size-1, j:j+block_size-1) = dct_block;
% Store the reconstructed block in the corresponding location in the reconstructed image
reconstructed_image(i:i+block_size-1, j:j+block_size-1) = idct_block;
end
end
subplot(1, 3, 1);
imshow(gray_image);
title('Original Image');
46
subplot(1, 3, 2);
imshow(log(abs(dct_image)), []);
title('DCT Image (8x8 block, log scale)');
subplot(1, 3, 3);
imshow(reconstructed_image);
title('Reconstructed Image (after IDCT)');
% Optionally, you can display the DCT coefficients in a more visible way
figure;
imshow(log(abs(dct_image)), []);
colormap(jet);
colorbar;
title('DCT Coefficients (8x8 block, log scale, with colormap)');
Output:
Inference: We have successfully applied the DCT using the 8x8 grid and also we have
applied the inverse DCT after every grid is done with the DCT, this finally gives us the
reconstructed image which is same to the original.
47
5. Error analysis
Code:
-mean square error
-root mean square error
-psnr
Code:
% Read the input image
% Store the DCT coefficients in the corresponding location in the output image
dct_image(i:i+block_size-1, j:j+block_size-1) = dct_block;
% Store the reconstructed block in the corresponding location in the reconstructed image
reconstructed_image(i:i+block_size-1, j:j+block_size-1) = idct_block;
end
end
48
% Calculate the Mean Square Error (MSE)
mse = mean((double(gray_image) - double(reconstructed_image)).^2, 'all');
subplot(1, 3, 1);
imshow(gray_image);
title('Original Image');
subplot(1, 3, 2);
imshow(log(abs(dct_image)), []);
title('DCT Image (8x8 block, log scale)');
subplot(1, 3, 3);
imshow(reconstructed_image);
title('Reconstructed Image (after IDCT)');
% Optionally, you can display the DCT coefficients in a more visible way
figure;
imshow(log(abs(dct_image)), []);
colormap(jet);
colorbar;
title('DCT Coefficients (8x8 block, log scale, with colormap)');
Output:
49
Inference: Hence we have successfully also calculated the errors for the taken input and the
transformed image accordingly, the error and the psnr values also can be viewed accordingly.
Output Verification:
Result: Hence we have successfully completed the DCT transformations on input image and
observed the results accordingly.
50
LAB EXPERIMENT -6
Aim: To perform Smoothing using Fast Fourier Transform on input image in frequency domain using
different mask’s size and observe the result.
1.Smoothening
Algorithm:
Multiply the shifted FFT of the image by the Gaussian filter to attenuate high
frequencies.
Shift the zero-frequency component back to the original position.
Compute the inverse FFT to get the filtered image back in the spatial domain.
Convert the result to an 8-bit unsigned integer format.
51
Code:
img = imread('/MATLAB Drive/DIP/images/feather.jpg');
img_gray = rgb2gray(img);
imshow(img_gray);
title('Original Image');
img_double = double(img_gray);
F = fft2(img_double);
F_shifted = fftshift(F);
[M, N] = size(img_double);
[X, Y] = meshgrid(1:N, 1:M);
centerX = N / 2;
centerY = M / 2;
D0 = 30;
H = exp(-((X - centerX).^2 + (Y - centerY).^2) / (2 * D0^2));
G_shifted = F_shifted .* H;
G = ifftshift(G_shifted);
img_smooth = ifft2(G);
img_smooth = uint8(real(img_smooth));
figure;
imshow(img_smooth);
title('Smoothened Image');
Output:
52
2. Smoothening with mask
Algorithm:
Multiply the shifted FFT of the image by the current filter mask.
Shift the zero-frequency component back to the original position and perform the
inverse FFT to obtain the filtered image.
Convert the resulting image to an 8-bit unsigned integer format.
Display the original image and each filtered image in separate figures, providing a
title indicating the mask size used.
Code:
53
% Display the Original Image
figure;
imshow(img_gray);
title('Original Image');
for i = 1:length(sizes)
D0 = sizes(i); % Mask size
Output:
54
55
3. Inverse fft on masked image
Algorithm:
Define a low-pass filter mask with a specified radius D0D0D0 (e.g., 40).
Generate a binary mask in the frequency domain based on the distance from the
center.
Apply this mask by multiplying it with the shifted FFT of the image.
Reverse the FFT shift and compute the inverse FFT to obtain the filtered image.
Convert the result to an 8-bit unsigned integer format.
Code:
56
[M, N] = size(img_double);
[X, Y] = meshgrid(1:N, 1:M);
centerX = N / 2;
centerY = M / 2;
H = double(sqrt((X - centerX).^2 + (Y - centerY).^2) <= D0);
Output:
57
58
Verification:
59
Lab Experiment -7
DIGITAL IMAGE PROCESSING
Name: Vadde Surya Teja
REG number: 21BEC1484
Read the input image and convert it to grayscale if it is a color image. Convert the
image to double precision for processing.
Compute FFT:
Perform the Fast Fourier Transform (FFT) on the image and shift the zero frequency
component to the center.
Define a range of mask sizes and create high-pass filter masks to block low
frequencies while retaining high frequencies.
For each mask size, apply the high-pass filter mask in the frequency domain, then
compute the inverse FFT to obtain the sharpened image.
Display Results:
Display the original image and the sharpened images for different mask sizes.
60
Code:
inputImage = imread('/MATLAB Drive/DIP/images/free.jpg');
if size(inputImage, 3) == 3
inputImage = rgb2gray(inputImage);
end
inputImage = im2double(inputImage);
F = fft2(inputImage);
Fshift = fftshift(F);
[rows, cols] = size(inputImage);
centerX = round(rows / 2);
centerY = round(cols / 2);
maskSizes = [5, 9, 13, 17, 21];
figure;
subplot(2, 3, 1);
imshow(inputImage);
title('Original Image');
for i = 1:length(maskSizes)
maskSize = maskSizes(i);
mask = ones(rows, cols);
mask(centerX - maskSize:centerX + maskSize, centerY - maskSize:centerY +
maskSize) = 0;
F_filtered = Fshift .* mask;
F_ishift = ifftshift(F_filtered);
sharpenedImage = real(ifft2(F_ishift));
subplot(2, 3, i + 1);
imshow(sharpenedImage, []);
title(['Sharpened Image (Mask Size: ', num2str(maskSize), ')']);
end
61
Output:
2. Inverse fft
Algorithm:
62
o Display the original image, the magnitude spectrum, and the reconstructed
image to verify that the original image is accurately recovered after applying
FFT and inverse FFT.
Code:
% Read the input image
inputImage = imread('/MATLAB Drive/DIP/images/free.jpg');
if size(inputImage, 3) == 3
inputImage = rgb2gray(inputImage);
end
% Apply inverse FFT without any modification to reconstruct the original image
reconstructedImage = real(ifft2(ifftshift(Fshift)));
subplot(1, 3, 2);
imshow(magnitudeSpectrum, []);
title('Magnitude Spectrum (FFT)');
subplot(1, 3, 3);
imshow(reconstructedImage, []);
title('Reconstructed Image (Inverse FFT)');
63
Output:
Inference :
When sharpening an image using high-pass filters of different mask sizes in the
frequency domain, the clarity and quality of the image are significantly affected.
Smaller mask sizes result in subtle sharpening, enhancing edges while
maintaining the overall structure. As the mask size increases, more low-
frequency components are removed, leading to stronger sharpening but also
increased noise and a loss of fine details, which can make the image appear
unnatural. When applying the inverse FFT to reconstruct the image after
filtering, the original image cannot be perfectly recovered due to the loss of
these low-frequency components. Thus, the larger the mask size, the greater the
difference between the original and reconstructed images. This demonstrates
that while sharpening can enhance details, it must be balanced to avoid
degrading the image's natural appearance.
Result: Hence, we have successfully performed the sharpening of image using
different mask sizes and also applied inverse to get back the original image.
64
LAB ASSIGNMENT-8
Aim: To apply HomoMorphic filter on low contrast image using MATLAB code.
Code:
clc;
clear all;
close all;
% Read the input image
I = imread('/MATLAB Drive/DIP/Images/pic_contrast.jpeg');
I = im2double(I);
I = rgb2gray(I);
% Display the original image in a separate figure
figure;
imshow(I);
title('Original Image');
% Convert the image to log domain
I_log = log(1 + I);
% Perform Fourier Transform
I_fft = fft2(I_log);
% Shift zero-frequency component to the center
I_fft_shifted = fftshift(I_fft);
% Get the size of the image
[M, N, C] = size(I); % Assume the image may have 3 color channels
u = 0:(M-1);
v = 0:(N-1);
u = u - M/2;
65
v = v - N/2;
[V, U] = meshgrid(v, u);
D = sqrt(U.^2 + V.^2);
% Define parameter sets for gammaH, gammaL, and D0
gammaH_values = [2.0, 2.5]; % Different values for higher gamma
gammaL_values = [0.5, 0.9]; % Different values for lower gamma
D0_values = [20, 30]; % Different cutoff frequencies
% Calculate the number of subplots needed
num_combinations = length(gammaH_values) * length(gammaL_values) *
length(D0_values);
rows = ceil(sqrt(num_combinations));
cols = ceil(num_combinations / rows);
% Create a figure for subplots
figure;
count = 1;
for gammaH = gammaH_values
for gammaL = gammaL_values
for D0 = D0_values
66
% Adjust the intensity for better visibility
I_exp = imadjust(I_exp, stretchlim(I_exp, [0.01, 0.99]), []);
count = count + 1;
end
end
end
% Adjust the layout of the subplots for better visibility
sgtitle('Filtered Images with Various Parameters'); % Add a super title
Algorithm:
1. Read and convert the input image to grayscale.
2. Apply log transformation to the image to separate illumination and reflectance.
3. Compute the 2D Fourier Transform of the log-transformed image.
4. Design a Gaussian high-pass filter using parameters \( \gamma_H \), \(
\gamma_L \), and cutoff frequency \( D_0 \).
5. Apply the filter in the frequency domain and perform the inverse Fourier
Transform.
6. Convert back from the log domain, normalize, and display the enhanced image.
Output:
67
Result: Applied Homomorphic filter on images using MATLAB code
68
LAB-9
DIGITAL IMAGE PROCESSING
Name: V. Surya Teja
REG number: 21BEC1484
Aim: Colour Space Conversion of RGB Images to YIQ and CMY Models and
Reconstruction using MATLAB.
Back Conversion:
Image Display:
Display the original RGB image, the YIQ image, the converted RGB image from
YIQ, the CMY image, and the converted RGB image from CMY.
Extract and display the red, green, and blue planes from the original RGB image.
Plotting:
Organize all images in a 3x3 subplot format for easy comparison and visualization.
Code:
function color_conversion_example()
img = imread('/MATLAB Drive/DIP/images/city.jpeg');
yiq = rgb2yiq(img);
rgb_converted = yiq2rgb(yiq);
cmy = rgb2cmy(img);
69
rgb_from_cmy = cmy2rgb(cmy);
figure;
subplot(3, 3, 1), imshow(img), title('Original RGB Image');
subplot(3, 3, 2), imshow(yiq), title('YIQ Image');
subplot(3, 3, 3), imshow(rgb_converted), title('Converted RGB from YIQ');
subplot(3, 3, 4), imshow(cmy), title('CMY Image');
subplot(3, 3, 5), imshow(rgb_from_cmy), title('Converted RGB from CMY');
displayColorPlanes(img);
end
70
C = 1 - rgb(:,:,1) / 255;
M = 1 - rgb(:,:,2) / 255;
Y = 1 - rgb(:,:,3) / 255;
cmy = cat(3, C, M, Y);
end
function displayColorPlanes(rgb)
R = rgb;
R(:,:,2) = 0;
R(:,:,3) = 0;
G = rgb;
G(:,:,1) = 0;
G(:,:,3) = 0;
B = rgb;
B(:,:,1) = 0;
B(:,:,2) = 0;
subplot(3, 3, 6), imshow(R), title('Red Plane');
subplot(3, 3, 7), imshow(G), title('Green Plane');
subplot(3, 3, 8), imshow(B), title('Blue Plane');
end
71
Output:
Output verification:
Result: Hence we have successfully observed the required result performing the
colour space conversion.
72
LAB-10
Aim: To perform Pseudo color image processing on input image and observe
the output accordingly.
Code1:
% Read the input image
inputImage = imread('/MATLAB Drive/DIP/images/city.jpeg');
subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(1, 2, 2);
imshow(pseudoColorImage);
title('Pseudo Color Image');
Output:
73
Code2 : with specific ranges
% Read the input image
inputImage = imread('/MATLAB Drive/DIP/images/feather.jpg');
subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(1, 2, 2);
imshow(uint8(pseudoColorImage)); % Convert to uint8 for display
title('Pseudo Color Image');
Output:
74
Code 3: with highlighting only reds, only blues, only greens
Algorithm:
Read the Input Image: Load the image file into memory using an appropriate function
(e.g., imread in MATLAB).
Convert to RGB Format: Ensure the image is in RGB format, as this algorithm works
with individual color channels.
Initialize Highlighted Images: Create copies of the original image for each color channel
you want to highlight (e.g., red, green, blue, magenta, cyan, yellow).
Define Intensity Ranges: Set lower and upper intensity thresholds for highlighting the
desired colors.
Iterate Through Pixels: Loop through each pixel of the image and perform the following
checks:
For Red: If the red channel intensity is within the specified range, set green and blue
channels to zero in the highlighted red image.
For Green: If the green channel intensity is within the specified range, set red and
blue channels to zero in the highlighted green image.
For Blue: If the blue channel intensity is within the specified range, set red and green
channels to zero in the highlighted blue image.
For Magenta: If both red and blue intensities are above the threshold, set the green
channel to zero.
For Cyan: If both green and blue intensities are above the threshold, set the red
channel to zero.
For Yellow: If both red and green intensities are above the threshold, set the blue
channel to zero.
Display Results: Use a suitable function (e.g., imshow in MATLAB) to display the
original image alongside the highlighted images for each color.
Adjust Parameters (if needed): Based on the output, fine-tune the intensity thresholds to
achieve the desired highlighting effect.
Code:
% Read the input image
inputImage = imread('/MATLAB Drive/DIP/images/city.jpeg');
75
% Iterate through the image
for i = 1:size(inputImage, 1)
for j = 1:size(inputImage, 2)
% Get the channel intensities
redIntensity = inputImage(i, j, 1);
greenIntensity = inputImage(i, j, 2);
blueIntensity = inputImage(i, j, 3);
% Highlight red
if redIntensity >= lowerThreshold && redIntensity <= upperThreshold
highlightedGreen(i, j, 1) = 0; % Zero out green channel
highlightedGreen(i, j, 3) = 0; % Zero out blue channel
else
highlightedGreen(i, j, :) = inputImage(i, j, :); % Keep original
end
% Highlight green
if greenIntensity >= lowerThreshold && greenIntensity <= upperThreshold
highlightedRed(i, j, 2) = 0; % Zero out red channel
highlightedRed(i, j, 3) = 0; % Zero out blue channel
else
highlightedRed(i, j, :) = inputImage(i, j, :); % Keep original
end
% Highlight blue
if blueIntensity >= lowerThreshold && blueIntensity <= upperThreshold
highlightedBlue(i, j, 1) = 0; % Zero out red channel
highlightedBlue(i, j, 2) = 0; % Zero out green channel
else
highlightedBlue(i, j, :) = inputImage(i, j, :); % Keep original
end
end
end
subplot(2, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(2, 2, 2);
imshow(highlightedRed);
title('Highlighted Red');
subplot(2, 2, 3);
imshow(highlightedGreen);
title('Highlighted Green');
subplot(2, 2, 4);
imshow(highlightedBlue);
title('Highlighted Blue');
76
Output:
% Highlight magenta
if redIntensity >= lowerThreshold && blueIntensity >= lowerThreshold
highlightedMagenta(i, j, 2) = 0; % Zero out green channel
else
highlightedMagenta(i, j, :) = inputImage(i, j, :); % Keep original
end
% Highlight cyan
77
if greenIntensity >= lowerThreshold && blueIntensity >= lowerThreshold
highlightedCyan(i, j, 1) = 0; % Zero out red channel
else
highlightedCyan(i, j, :) = inputImage(i, j, :); % Keep original
end
% Highlight yellow
if redIntensity >= lowerThreshold && greenIntensity >= lowerThreshold
highlightedYellow(i, j, 3) = 0; % Zero out blue channel
else
highlightedYellow(i, j, :) = inputImage(i, j, :); % Keep original
end
end
end
subplot(2, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(2, 2, 2);
imshow(highlightedMagenta);
title('Highlighted Magenta');
subplot(2, 2, 3);
imshow(highlightedCyan);
title('Highlighted Cyan');
subplot(2, 2, 4);
imshow(highlightedYellow);
title('Highlighted Yellow');
Output:
78
Observation:
We can observe that the effectiveness of highlighting relies on the chosen
intensity thresholds, as low thresholds may capture noise while high thresholds
may miss subtle shades. It's crucial to maintain image quality, as excessive
manipulation can lead to loss of detail. Understanding color combinations (e.g.,
red + blue = magenta) enhances isolation efforts. Lighting conditions also affect
color representation, impacting the highlighting process. While color maps can
improve visibility, they may alter the original image. Computational efficiency
is essential, particularly for larger images, and optimizing the algorithm can
improve speed. Highlighting specific colors serves various applications,
including object detection and medical imaging, each requiring tailored
approaches.
Output verification:
79
LAB EXPERIMENT – 11
Digital Image Processing
Name: V. Surya Teja
REG number: 21BEC1484
Aim: To complete the different tasks on input image like quantization, Non DC
components elimination, and MSE calculation on the taken input images and
observe the output accordingly.
% Initialize variables
blockSize = 8;
quantMatrix = [16 11 10 16 24 40 51 61;
12 12 14 19 26 58 60 55;
14 13 16 24 40 57 69 56;
14 17 22 29 51 87 80 62;
18 22 37 56 68 109 103 77;
24 35 55 64 81 104 113 92;
49 64 78 87 103 121 120 101;
72 92 95 98 112 100 103 99]; % Example quantization matrix
80
% Perform DCT (Discrete Cosine Transform)
dctBlock = dct2(block);
subplot(1, 3, 2);
imshow(uint8(quantizedImg)); % Display quantized image (in uint8 format)
title('Quantized Image');
subplot(1, 3, 3);
imshow(uint8(reconstructedImg)); % Display reconstructed image (in uint8 format)
title('Reconstructed Image');
Output:
81
Decreased quantization values
quantMatrix = [4 3 3 4 6 10 13 15;
3 3 4 5 7 14 15 14;
4 3 4 6 10 14 17 14;
4 4 6 8 13 22 20 15;
5 6 9 14 17 27 26 19;
6 8 13 16 20 26 28 22;
12 16 20 22 26 30 30 25;
18 23 24 25 29 25 26 25];
Code:
% Read the input image
img = imread('/MATLAB Drive/DIP/images/feather.jpg'); % Replace with your image
file
img = rgb2gray(img); % Convert to grayscale if it's a color image
img = imresize(img, [256 256]); % Ensure the image is 256x256
% Initialize variables
blockSize = 8;
82
dcBlock(1, 1) = dctBlock(1, 1); % Keep only the DC component
subplot(1, 3, 2);
imshow(uint8(dcImg)); % Display image with only DC components
title('DC Components Image');
subplot(1, 3, 3);
imshow(uint8(reconstructedImg)); % Display reconstructed image
title('Reconstructed Image');
Output:
Code:
% Read the input image
img = imread('/MATLAB Drive/DIP/images/feather.jpg'); % Replace with your image
file
img = rgb2gray(img); % Convert to grayscale if it's a color image
img = imresize(img, [256 256]); % Ensure the image is 256x256
83
% Initialize variables
blockSize = 8;
% Calculate MSE
mse = mean((img_double(:) - reconstructedImg(:)).^2);
84
% Display the original and modified images
figure;
subplot(1, 3, 1);
imshow(img);
title('Original Image');
subplot(1, 3, 2);
imshow(uint8(modifiedImg)); % Display image with selected components
title(['Selected Components: ', num2str(numComponents)]);
subplot(1, 3, 3);
imshow(uint8(reconstructedImg)); % Display reconstructed image
title('Reconstructed Image');
fprintf('Mean Squared Error (MSE): %.2f\n', mse);
Output:
Number of components: 1
Number of components: 5
85
Number of components: 20
Output verification:
86
Inference:
Result:
Hence we have successfully completed the tasks and got the outputs
accordingly.
87
LAB-12
DIGITAL IMAGE PROCESSING
AIM: The aim of this project is to implement and analyze Huffman Coding and Arithmetic
Coding techniques for data compression in MATLAB. The goal is to compare their
performance in terms of compression ratio, efficiency, and computational complexity, and
determine which method offers better performance for different types of data.
Arithmetic Coding:
Algorithm: -
Read the image using `imread` and convert it to grayscale with `rgb2gray`. - Flatten the
grayscale image into a 1D array using `image(:)`. - Calculate pixel intensity probabilities using
`histcounts` and normalize them. - Compute cumulative probabilities for each pixel
intensity. - Remove zero-probability values for optimization by filtering out them. - Identify
unique pixel values (symbols) that appear in the image. - Initialize the interval range for
arithmetic coding (low = 0, high = 1). - Loop through each pixel in the image and update the
coding interval based on its probability. - For each pixel, find its corresponding symbol's
cumulative probability range. - Update the `low` and `high` values based on the cumulative
probabilities of the symbol. - Calculate the final encoded value as the midpoint between
`low` and `high`. - Display the final arithmetic coded value.
TASK1:
Code:
88
% Define a stronger 8x8 quantization matrix to increase blocky
effect
Q = [
32 22 20 32 48 80 102 122;
24 24 28 38 52 116 120 110;
28 26 32 48 80 114 138 112;
28 34 44 58 102 174 160 124;
36 44 74 112 136 218 206 154;
48 70 110 128 162 208 226 184;
98 128 156 174 206 242 240 202;
144 184 190 196 224 200 206 198
];
% Ensure the output image is in the correct uint8 format for display
output_image = uint8(output_image);
89
mse = mean((double(image) - double(output_image)).^2, 'all');
% Display MSE
disp(['Mean Squared Error (MSE): ', num2str(mse)]);
Huffman Coding:
Read the image and convert it to grayscale. - Compute the histogram of the
image to get pixel intensity counts. - Normalize the counts to calculate pixel
probabilities. - Remove zero probabilities for intensity levels not present in the
image. - Generate a Huffman dictionary based on the pixel probabilities. -
Flatten the image into a 1D array. - Encode the flattened image using the
Huffman dictionary. - Calculate the original size in bits and the compressed size
in bits. - Compute the compression ratio. - Decode the encoded image using
the Huffman dictionary. - Reshape the decoded vector back to the original
image size. - Display both the original and decoded images side by side. - Check
if the original and decoded images are identical.
Task2:
Code:
90
% Read or generate a sample 256x256 grayscale image
image = imread('/MATLAB Drive/DIP/Images/pic9.jpg'); % Replace with
your 256x256 image
if size(image, 3) == 3
image = rgb2gray(image); % Convert to grayscale if needed
end
91
% Display original and processed images with enhanced contrast for
visibility
figure;
subplot(1, 2, 1), imshow(image, []), title('Original Image');
subplot(1, 2, 2), imshow(uint8(output_image * 1.5)), title('Image
with Only DC Component');
% Calculate the Mean Squared Error (MSE) between the original and
processed images
MSE = mean((double(image) - output_image).^2, 'all');
disp(['Mean Squared Error (MSE): ', num2str(MSE)]);
Task3:
Code:
92
probabilities = counts / total_pixels; % Remove zero probabilities (intensity
levels that do not appear in the image)
probabilities = probabilities(probabilities > 0);
intensity_levels = intensity_levels(counts > 0); % Generate Huffman dictionary
based on probabilities
[dict, avg_len] = huffmandict(intensity_levels, probabilities); % Flatten the
image into a 1D array and encode it using the Huffman dictionary img_vector =
img(:); % Flatten image into a column vector
encoded_img = huffmanenco(img_vector, dict); % Display the compression
ratio original_size = numel(img_vector) * 8; % Original size in bits (8 bits per
pixel)
compressed_size = numel(encoded_img); % Compressed size in bits
compression_ratio = original_size / compressed_size; disp(['Original size (bits):
', num2str(original_size)]); disp(['Compressed size (bits): ',
num2str(compressed_size)]); disp(['Compression Ratio: ',
num2str(compression_ratio)]); % Decoding the Huffman encoded image
decoded_img_vector = huffmandeco(encoded_img, dict); % Reshape the
decoded vector back to the original image size decoded_img =
reshape(decoded_img_vector, size(img)); % Create a single figure to display
both images (original and decoded) side by side figure; % Display the original
image in the first subplot (1st position) subplot(1, 2, 1); % 1 row, 2 columns, 1st
subplot imshow(img); title('Original Image'); % Display the decoded image in
the second subplot (2nd position) subplot(1, 2, 2);
imshow(decoded_img, []);
title('Decoded Image (After Huffman Decoding)'); % Verify if the original and
decoded images are identical if
isequal(img, decoded_img) disp('The original and decoded images are
identical.');
else disp('The original and decoded images are not identical.');
end
93
Inference:
The code demonstrates Huffman coding for image compression and
decompression. It begins by reading and converting the image to grayscale,
then calculates the pixel intensity distribution to generate probabilities. Using
these probabilities, a Huffman codebook is created, which is then used to
encode the image, reducing its size. The compression ratio is computed to
show the effectiveness of the encoding process. Afterward, the encoded image
is decoded using the same codebook, and the original and decoded images are
compared to ensure they are identical. This method effectively reduces image
file size while preserving the original content, showcasing the efficiency of
Huffman coding in lossless image compression.
94
LAB-13
DIGITAL IMAGE PROCESSING
Name: Surya teja
Aim: To find the threshold image of the input image by setting a threshold
value and observing the histograms before and after effect.
Algorithm:
1. Load Image: Read the input image and convert it to grayscale if it’s RGB.
2. Set Threshold: Define a threshold value for classification (e.g., 10).
3. Select Segment: Extract a 40% region of the image (e.g., starting at 30
of height and width).
4. Apply Thresholding: Set pixel values above the threshold to 255 (white)
and below or equal to it to 0 (black) for the segment.
5. Reinsert Segment: Place the thresholded segment back into the original
image.
6. Plot Histograms:
• Plot histograms of the original and thresholded images.
• Plot histograms of the original and thresholded segment.
7. Display Images: Show side-by-side comparison of the original and
thresholded images.
Code:
% Step 4: Select a 40% segment of the image (you can choose the segment as needed)
[imageHeight, imageWidth] = size(inputImage);
segmentHeight = round(0.4 * imageHeight); % 40% of the image height
segmentWidth = round(0.4 * imageWidth); % 40% of the image width
95
% Define the top-left corner of the segment (choose an arbitrary starting
position)
segmentStartRow = round(0.3 * imageHeight); % Starting row for the segment
segmentStartCol = round(0.3 * imageWidth); % Starting column for the segment
% Step 6: Reinsert the thresholded segment back into the original image (for
visualization)
outputImage = inputImage; % Copy the original image
outputImage(segmentStartRow:segmentStartRow + segmentHeight - 1, ...
segmentStartCol:segmentStartCol + segmentWidth - 1) =
thresholdedSegment;
% Step 7: Plot histograms for the whole image (before and after thresholding)
figure;
subplot(2, 1, 1);
imhist(inputImage);
title('Histogram of Original Image');
xlabel('Pixel Intensity');
ylabel('Frequency');
subplot(2, 1, 2);
imhist(outputImage);
title('Histogram of Image After Thresholding');
xlabel('Pixel Intensity');
ylabel('Frequency');
%Step 8: Plot histograms for the segment (before and after thresholding)
figure;
subplot(2, 1, 1);
imhist(segment);
title('Histogram of Original Segment');
xlabel('Pixel Intensity');
ylabel('Frequency');
subplot(2, 1, 2);
imhist(thresholdedSegment);
title('Histogram of Thresholded Segment');
xlabel('Pixel Intensity');
ylabel('Frequency');
% Step 9: Show the images for comparison (Original image and Thresholded image)
figure;
subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(1, 2, 2);
imshow(outputImage);
title('Image After Thresholding');
96
Output:
97
Output Verification
98
Inference:
As the threshold value increases, fewer pixels in the image exceed the threshold and are set
to 1 (white), resulting in more black pixels (0) and a greater portion of the image being
classified as background. The thresholded image appears darker, with a histogram showing a
higher peak at 0 (black) and a lower peak at 255 (white). On the other hand, decreasing the
threshold allows more pixels to exceed the threshold and be set to 1 (white), which increases
the number of white pixels, making the image appear brighter with a larger foreground. The
histogram for this thresholded image shows a higher peak at 255 (white) and a lower peak
at 0 (black). Essentially, higher thresholds emphasize brighter regions of the image, while
lower thresholds highlight darker areas.
Result:
Hence we have successfully applied the threshold on the input image and got the output
accordingly.
99