0% found this document useful (0 votes)
23 views42 pages

Karnatak Arts, Science and Commerce College Bidar: Digital Image Processing Laboratory Manual - SCP 4.1

This program demonstrates edge detection on an image using Sobel operators. It reads in a color image and converts it to grayscale. Horizontal and vertical Sobel filters are defined. A double for loop calculates the gradient magnitude at each pixel by convolving the grayscale image with the Sobel filters, taking the square root of the sum of squares. The results are normalized and displayed alongside the original color and grayscale images.
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)
23 views42 pages

Karnatak Arts, Science and Commerce College Bidar: Digital Image Processing Laboratory Manual - SCP 4.1

This program demonstrates edge detection on an image using Sobel operators. It reads in a color image and converts it to grayscale. Horizontal and vertical Sobel filters are defined. A double for loop calculates the gradient magnitude at each pixel by convolving the grayscale image with the Sobel filters, taking the square root of the sum of squares. The results are normalized and displayed alongside the original color and grayscale images.
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/ 42

M.Sc. Computer Science SCT 4.

1: DIP Programs

KRE Society’s
Karnatak Arts, Science and Commerce
College Bidar
Department of PG Studies and Research in ComputerScience
M.Sc. IV Semester

DIGITAL IMAGE PROCESSING


LABORATORY MANUAL – SCP 4.1

Prepared by: Mr.Pavan Kumar Compiled By: Mohd Abdul Basheer


Assistant Professor M.Sc. Computer Science IV SEM
Department of M.sc Computer Karnatak Arts, Science and
Science Commerce College Bidar
KARNATAK ARTS, SCIENCE AND
COMMERCE COLLEGE BIDAR

DIGITAL IMAGE PROCESSING LABORATORY


[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2022-2023)

1|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs

DIGITAL IMAGE PROCESSING


LABORATORY
[As per Choice Based Credit System (CBCS)
scheme](Effective from the academic year 2022 -
2023) SEMESTER – IV
Subject Code SCP:4.1 IA Marks 20
Number of Lecture 04 + 04P Exam Marks 80
Hours/Week
Total Number of Lecture 56 Exam Hours 03
Hours
CREDITS – Theory-04, Practical-02

Course objectives: This course will enable students to

1. To study the image fundamentals and mathematical transforms necessary for


image processing.
2. To study the image enhancement techniques.
3. To study image restoration procedures.
4. To study the image compression procedures.

Course outcome: This course will enable students to

1. Review the fundamental concepts of a digital image processing system.


2. Analyze images in the frequency domain using various transforms.
3. Evaluate the techniques for image enhancement and image restoration.
4. Categorize various compression techniques.
5. Interpret Image compression standards.
6. Interpret image segmentation and representation techniques.

2|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs

PROGRAMS INDEX: -
1. Program for opening and closing of the image.
2. Program to fill the region of interest for the image.
3. Program for edge detection algorithm.
4. Program of sharpen image using gradient mask.
5. Program for Display of an Image, Negative of an Image(Binary & Gray
Scale)
6. Program for Implementation of Relationships between Pixels
7. Program for Implementation of Transformations of an Image
8. Program for Contrast stretching of a low contrast image, Histogram, and
Histogram Equalization
9. Program for Display of bit planes of an Image
10.Program for Display of FFT(1-D & 2-D) of an image
11.Program for Computation of Mean, Standard Deviation, Correlation
coefficient of the given Image.
12.Program for Implementation of Image Smoothening Filters (Mean and
Median filtering of an Image.
13.Program for Implementation of image sharpening filters and Edge
Detection using Gradient Filters.
14.Program for Image Compression by DCT, DPCM, HUFFMAN coding.
15. Program for Implementation of image restoring techniques.
16.Program for Implementation of Image Intensity slicing technique for
image enhancement.
17.Program for Canny edge detection Algorithm.
18.Program to obtain histogram equalization concept.
19.Program To Implement smoothing or averaging filter in spatial domain.
20.Program for morphological operation: erosion and dilation.
21.Program for DCT/IDCT computation.
22.Program to compute the edges in the image using Roberts, Sobel, Canny,
Log, Prewitt edge detection methods.
23. Program to perform watershed transformation on an image.
24. Program for the dilation and erosion process with a character image
example.
25. Program to separate the RGB plane from the color image.
26.Program to demonstrate run length encoding and decoding.
27.Program to read a document image and perform morphological whole
filling operation.
28.Program to demonstrate geometric transformations like scale, rotate,
affine.

3|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs

1. Program for opening and closing of the image.


Matlab code:-
clc
close all

input image = imread('Images/morph2.bmp');


se = ones(3);

subplot (2, 3, 2);


imshow(input image);
title('Original Image');

output image = custom opening(input_image,se);

subplot(2, 3, 4);
imshow (output_image);
title('Opened Image');

output_image=custom_closing (input_image,se);
subplot(2, 3, 6);
imshow(output_image);
title('Closed Image');

function output_image = custom_opening(input_image, se)


eroded_image = custom_erosion(input_image, se);
output_image = custom_dilation(eroded_image, se);
end

function output_image = custom_closing(input_image, se)


dilated_image = custom_dilation(input_image, se);
output_image = custom_erosion(dilated_image, se);
end

function output_image = custom_erosion(input_image, se)


[M, N] = size(input_image);
[se_m, se_n] = size(se);
pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);
padded_image = padarray(input_image, [pad_m, pad_n], 0, 'both');
output_image = zeros(size(input_image));
for i = 1:M
for j = 1:N
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = min(region(:));
end
end
end

function output_image = custom_dilation(input_image, se)


[M, N] = size(input_image);

4|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs

[se_m, se_n] = size(se);


pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);
padded_image = padarray(input_image, [pad_m, pad_n], 0, 'both');
output_image = zeros(size(input_image));
for i = 1:M
for j = 1:N
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = max(region(:));
end
end
end

Output:-

5|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs
2. Program to fill the region of interest for the image.

Matlab code:-
clc
close all
image = imread('region.png');
image=rgb2gray(image);

seedPoint = [200, 100];


fillColor = 255;
outputImage = floodFill(image, seedPoint, fillColor);

subplot(1, 2, 1);
imshow(image);
title('Original Image');

subplot(1, 2, 2);
imshow(outputImage);
title('Image with Filled Region');

function outputImage = floodFill(image, seedPoint, fillColor)


outputImage = image;
[rows, cols] = size(image);

seedX = seedPoint(1);
seedY = seedPoint(2);
seedValue = image(seedY, seedX);

if seedValue == fillColor || seedX < 1 || seedX > cols || seedY < 1 || seedY > rows
return;
end

neighbors = [0, -1; 0, 1; -1, 0; 1, 0];

stack = [seedX, seedY];

while ~isempty(stack)
currentPoint = stack(end, :);
stack(end, :) = [];

currentX = currentPoint(1);
currentY = currentPoint(2);

if currentX >= 1 && currentX <= cols && currentY >= 1 && currentY <= rows &&
outputImage(currentY, currentX) == seedValue
outputImage(currentY, currentX) = fillColor;

for i = 1:size(neighbors, 1)
neighborX = currentX + neighbors(i, 1);
neighborY = currentY + neighbors(i, 2);
stack = [stack; neighborX, neighborY];
end
end
end
end

6|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs

Output:-

7|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs
3. Program for edge detection algorithm.

Matlab code:-
clc
close all
originalImage = imread('mixedfruit.bmp');
grayImage = rgb2gray(originalImage);

sobelHorizontal = [-1, 0, 1; -2, 0, 2; -1, 0, 1];


sobelVertical = [-1, -2, -1; 0, 0, 0; 1, 2, 1];

[rows, cols] = size(grayImage);

gradientMagnitude = zeros(rows, cols);

for i = 2:rows-1
for j = 2:cols-1
gx = sum(sum(double(grayImage(i-1:i+1, j-1:j+1)) .* sobelHorizontal));
gy = sum(sum(double(grayImage(i-1:i+1, j-1:j+1)) .* sobelVertical));

gradientMagnitude(i, j) = sqrt(gx^2 + gy^2);


end
end

gradientMagnitude = uint8(255 * (gradientMagnitude / max(max(gradientMagnitude))));

subplot(3, 1, 1);
imshow(originalImage);
title('Original Image');

subplot(3, 1, 2);
imshow(grayImage);
title('Original Grayscale Image');

subplot(3, 1, 3);
imshow(gradientMagnitude);
title('Edge Detected Image');

Output:-

8|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs
4. Program for sharpen image using gradient mask.

Matlab code:-
//for color image
clc
close all

originalImage = imread('Images/apple3.bmp');
originalImage = im2double(originalImage);

laplacianKernel = [0, -1, 0;-1, 4, -1; 0, -1, 0];

[rows, cols, ~] = size(originalImage);


sharpenedImage = zeros(rows, cols, 3);

for channel = 1:3


for i = 2:rows-1
for j = 2:cols-1
convolution = sum(sum(originalImage(i-1:i+1, j-1:j+1, channel) .* laplacianKernel));
sharpenedImage(i, j, channel) = originalImage(i, j, channel) + convolution;
end
end
end

sharpenedImage = max(0, min(sharpenedImage, 1));

subplot(1, 2, 1);
imshow(originalImage);
title('Original Image');

subplot(1, 2, 2);
imshow(sharpenedImage);
title('Sharpened Image');

Output:-

9|Pa ge
M.Sc. Computer Science SCT 4.1: DIP Programs
//converting gray scale image
clc
close all

input_image = imread('Images/key.jpg');

originalImage = im2double(input_image);

gray_image=rgb2gray(originalImage);

laplacianKernel = [0, -1, 0;-1, 4, -1; 0, -1, 0];

sharpenedImage=conv2(gray_image,laplacianKernel,'same');

sharpenedImage = gray_image-sharpenedImage;

subplot(3, 1, 1);
imshow(input_image);
title('Original Image');

subplot(3, 1, 2);
imshow(gray_image);
title('Gray Scale Image');

subplot(3, 1, 3);
imshow(sharpenedImage);
title('Sharpened Image using Gradient Mask');

10 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
5. Program for display of an image, negative of an image (Binary & Gray Scale).

Matlab code:-

clc
close all

input_image=imread('lotus.jpg');
subplot(1, 2, 1);
imshow(input_image);
title('Original Image');

negative_image=255-input_image;
subplot(1, 2, 2);
imshow(negative_image);
title('Negative of Original Image');

Output:-

11 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
6. Program for implementation of Transformation of an image.

Matlab code:-
clc
close all

original_image=imread('myna.jpg');
input_image=rgb2gray(original_image);
subplot(2, 3, 2);
imshow(input_image);
title('Original Image');

%Image Naegative Transform


negative_image=255-input_image;
subplot(2, 3, 4);
imshow(negative_image);
title('Negative Image');

%Logarithmic Transform
L=255;
c=L/log10(1+L);
log_transform=c*log10(1+double(input_image));
subplot(2, 3, 5);
imshow(uint8(log_transform));
title('Log Transformation');

%Power Law Transform


gamma=1.1
power_law_transform=double(input_image).^gamma;
subplot(2, 3, 6);
imshow(uint8(power_law_transform));
title('Power law Transformation');
xlabel(sprintf('gamma = %g',gamma));

Output:-

12 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
7. Program for contrast stretching of a low contrast image, Histogram, and histogram
Equalization.
Matlab code:-
clc
close all
clear all
inputImage = imread('Images/eye1.jpg');
if size(inputImage, 3) == 3
inputImage = rgb2gray(inputImage);
end
grayImage = im2double(inputImage);

% Apply contrast stretching to enhance the image contrast


minIntensity = min(grayImage(:));
maxIntensity = max(grayImage(:));
contrastStretchedImage = (grayImage - minIntensity) / (maxIntensity - minIntensity);

% Compute the histogram of the original and contrast-stretched images


originalHistogram = computeHistogram(grayImage);
contrastStretchedHistogram = computeHistogram(contrastStretchedImage);

% Perform histogram equalization to enhance the image contrast


histEqualizedImage = histogramEqualization(grayImage);

% Compute the histogram of the equalized image


equalizedHistogram = computeHistogram(histEqualizedImage);

subplot(3, 2, 1);
imshow(grayImage);
title('Original Image');
subplot(3, 2, 2);
bar(originalHistogram);
title('Histogram (Original Image)');

subplot(3, 2, 3);
imshow(contrastStretchedImage);
title('Contrast Stretched Image');
subplot(3, 2, 4);
bar(contrastStretchedHistogram);
title('Histogram (Contrast Stretched Image)');

subplot(3, 2, 5);
imshow(histEqualizedImage);
title('Histogram Equalized Image');
subplot(3, 2, 6);
bar(equalizedHistogram);
title('Histogram (Histogram Equalized Image)');

function histogram = computeHistogram(image)


histogram = zeros(256, 1);
[rows, cols] = size(image);
for i = 1:rows
for j = 1:cols
intensity = round(image(i, j) * 255) + 1;

13 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

histogram(intensity) = histogram(intensity) + 1;
end
end
end

function equalizedImage = histogramEqualization(image)


histogram = computeHistogram(image);

% Compute the cumulative distribution function (CDF)


cdf = cumsum(histogram) / sum(histogram);

% Perform histogram equalization


[rows, cols] = size(image);
equalizedImage = zeros(rows, cols);

for i = 1:rows
for j = 1:cols
intensity = round(image(i, j) * 255) + 1;
equalizedImage(i, j) = cdf(intensity);
end
end
end

Output:-

14 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
8. Program for display of bit planes of an image.

Matlab code:-
clc
close all

input_image=imread('penguin.jpg');

[row,col]=size(input_image);

%extract 7th bit plane


for i=1:row
for j=1:col
bit_7(i,j)=bitand(input_image(i,j),128);
end
end
%extract 6th bit plane
for i=1:row
for j=1:col
bit_6(i,j)=bitand(input_image(i,j),64);
end
end
%extract 5th bit plane
for i=1:row
for j=1:col
bit_5(i,j)=bitand(input_image(i,j),32);
end
end
%extract 4th bit plane
for i=1:row
for j=1:col
bit_4(i,j)=bitand(input_image(i,j),16);
end
end
%extract 3th bit plane
for i=1:row
for j=1:col
bit_3(i,j)=bitand(input_image(i,j),8);
end
end
%extract 2th bit plane
for i=1:row
for j=1:col
bit_2(i,j)=bitand(input_image(i,j),4);
end
end
%extract 1th bit plane
for i=1:row
for j=1:col
bit_1(i,j)=bitand(input_image(i,j),2);
end
end
%extract 0th bit plane
for i=1:row
for j=1:col

15 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

bit_0(i,j)=bitand(input_image(i,j),1);
end
end

subplot(4, 3, 1),imshow(input_image),title('Original Image');


subplot(4, 3, 5),imshow(bit_7),title('7th bit palne');
subplot(4, 3, 6),imshow(bit_6),title('6th bit palne');
subplot(4, 3, 7),imshow(bit_5),title('5th bit palne');
subplot(4, 3, 8),imshow(bit_4),title('4th bit palne');
subplot(4, 3, 9),imshow(bit_3),title('3th bit palne');
subplot(4, 3, 10),imshow(bit_2),title('2th bit palne');
subplot(4, 3, 11),imshow(bit_1),title('1th bit palne');
subplot(4, 3, 12),imshow(bit_0),title('0th bit palne');

Output :-

16 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
9. Program for display of FFT (1D & 2D) of an image.
Matlab code :-

clc
close all
input_image = imread('lenna.jpg');
image = im2double(input_image);

[fft1D, fft2D] = myFFT(image);

subplot(2, 2, 1);
imshow(image);
title('Original Image');

subplot(2, 2, 2);
imshow(abs(fft1D));
title('1D FFT');

subplot(2, 2, 3);
imshow(log(1 + abs(fft2D)), []);
title('2D FFT Magnitude');

subplot(2, 2, 4);
imshow(angle(fft2D), []);
title('2D FFT Phase');

function [fft1D, fft2D] = myFFT(image)

fft1D = zeros(size(image));
for row = 1:size(image, 1)
fft1D(row, :) = myFFT1D(image(row, :));
end

fft2D = zeros(size(image));
for col = 1:size(fft1D, 2)
fft2D(:, col) = myFFT1D(fft1D(:, col).');
end
end

function fft1D = myFFT1D(signal)


N = length(signal);
fft1D = zeros(1, N);

17 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
for k = 1:N
for n = 1:N
angle = -2*pi*(k-1)*(n-1)/N;
fft1D(k) = fft1D(k) + signal(n) * exp(1i * angle);
end
end
end

Output:-

18 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
10. Program for computation of mean, standard deviation, Correlation coefficient of the given
image.
Matlab code:-
clc
close all
image = imread('dove1.jpg');
image = im2double(image);

% Compute mean and standard deviation


meanValue = customMean(image);
stdValue = customStd(image);

% Generate a second image with some modifications (for correlation)


modifiedImage = image + 0.1 * randn(size(image));

% Compute the correlation coefficient between the original and modified images
correlationValue = customCorrelation(image, modifiedImage);

subplot(1,1,1);
imshow(image);
title('Original Image');
xlabel(sprintf('Mean : %s\nStandard Deviation: %s\nCorrelation Coefficient: %s',num2str(meanValue),
num2str(stdValue),num2str(correlationValue)));

function imageMean = customMean(image)


[rows, cols] = size(image);
totalPixels = rows * cols;
imageMean = sum(image(:)) / totalPixels;
end

function imageStd = customStd(image)


imageMean = customMean(image);
[rows, cols] = size(image);
totalPixels = rows * cols;
squaredDifferences = (image(:) - imageMean).^2;
imageStd = sqrt(sum(squaredDifferences) / totalPixels);
end

function correlationCoefficient = customCorrelation(image1, image2)


image1Mean = customMean(image1);
image2Mean = customMean(image2);
[rows, cols] = size(image1);
totalPixels = rows * cols;

numerator = sum((image1(:) - image1Mean) .* (image2(:) - image2Mean));


denominator = sqrt(sum((image1(:) - image1Mean).^2) * sum((image2(:) - image2Mean).^2));

correlationCoefficient = numerator / denominator;


end

19 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

Output:-

20 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

11. Program for implementation of Image Smoothening Filters (Mean and Median Filtering) of
an Image.
Matlab code:-
clc
close all
inputImage = imread('rose.jpg');
inputImage = im2double(inputImage);

% Set the kernel size for the filters (e.g., 3x3 or 5x5)
kernelSize = 5;

meanFiltered = meanFilter(inputImage, kernelSize);


medianFiltered = medianFilter(inputImage, kernelSize);

subplot(1, 3, 1);
imshow(inputImage);
title('Original Image');

subplot(1, 3, 2);
imshow(meanFiltered);
title('Mean Filtered Image');

subplot(1, 3, 3);
imshow(medianFiltered);
title('Median Filtered Image');

function outputImage = meanFilter(inputImage, kernelSize)


[rows, cols] = size(inputImage);
outputImage = zeros(rows, cols);

padSize = floor(kernelSize / 2);


paddedImage = padarray(inputImage, [padSize, padSize], 'replicate');

for y = 1:rows
for x = 1:cols
neighbors = paddedImage(y:y + kernelSize - 1, x:x + kernelSize - 1);
outputImage(y, x) = mean(neighbors(:));
end
end
end

function outputImage = medianFilter(inputImage, kernelSize)


[rows, cols] = size(inputImage);
outputImage = zeros(rows, cols);

padSize = floor(kernelSize / 2);


paddedImage = padarray(inputImage, [padSize, padSize], 'replicate');

for y = 1:rows
for x = 1:cols
neighbors = paddedImage(y:y + kernelSize - 1, x:x + kernelSize - 1);
outputImage(y, x) = median(neighbors(:));
end
21 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

end
end

Output:-

22 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
12. Program for implementation of Image Sharpening filters and Edge Detection using Gradient
Filters.

Matlab code :-
clc
close all
inputImage = imread('Images/babyelephant.jpg');
inputImage = im2double(inputImage);

% Apply image sharpening


sharpened = laplacianSharpen(inputImage);

% Apply edge detection


[edgeMagnitude, edgeDirection] = sobelEdgeDetect(inputImage);

subplot(1, 3, 1);
imshow(inputImage),title('Original Image');

subplot(1, 3, 2);
imshow(sharpened),title('Sharpened Image');

subplot(1, 3, 3);
imshow(edgeMagnitude, []);
title('Edge Detected Image');

function outputImage = conv2D(inputImage, kernel)


[rows, cols] = size(inputImage);
[kRows, kCols] = size(kernel);
padSize = floor(max(size(kernel)) / 2);
outputImage = zeros(rows, cols);

paddedImage = padarray(inputImage, [padSize, padSize], 'replicate');


for y = 1:rows
for x = 1:cols
neighbors = paddedImage(y:y + kRows - 1, x:x + kCols - 1);
outputImage(y, x) = sum(neighbors(:) .* kernel(:));
end
end
end

function outputImage = laplacianSharpen(inputImage)


laplacianKernel = [0, 1, 0; 1, -4, 1; 0, 1, 0];
outputImage = inputImage - conv2D(inputImage, laplacianKernel);
end

function [magnitude, direction] = sobelEdgeDetect(inputImage)


sobelX = [-1, 0, 1; -2, 0, 2; -1, 0, 1];
sobelY = [-1, -2, -1; 0, 0, 0; 1, 2, 1];

gradientX = conv2D(inputImage, sobelX);


gradientY = conv2D(inputImage, sobelY);

magnitude = sqrt(gradientX.^2 + gradientY.^2);

end

23 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

Output:-

24 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
13. Program for image compression by DCT, DPCM, HUFFMAN coding.
Matlab code :-
clc
close all
inputImage = imread('cameraman.jpg');
inputImage = im2double(inputImage);

blocksize = 16;
quantizationFactor = 0.2;
% Compress the image
compressedImage = compressImageByDCT(inputImage, blocksize, quantizationFactor);

subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');
subplot(1, 2, 2);
imshow(compressedImage);
title('Compressed Image');

compressionRatio = numel(compressedImage) / numel(inputImage);


xlabel(sprintf('Compression Ratio: %s', num2str(compressionRatio)));

function compressedImage = compressImageByDCT(inputImage, blocksize, quantizationFactor)


[rows, cols] = size(inputImage);
numBlocksX = floor(cols / blocksize);
numBlocksY = floor(rows / blocksize);

inputImagePadded = padarray(inputImage, [numBlocksY * blocksize - rows, numBlocksX * blocksize


- cols], 'replicate', 'post');

compressedImage = zeros(numBlocksY * blocksize, numBlocksX * blocksize);

for i = 1:numBlocksY
for j = 1:numBlocksX
block = inputImagePadded((i - 1) * blocksize + 1:i * blocksize, (j - 1) * blocksize + 1:j * blocksize);
dctBlock = dct2(block);
quantizedBlock = round(dctBlock / quantizationFactor);
compressedImage((i - 1) * blocksize + 1:i * blocksize, (j - 1) * blocksize + 1:j * blocksize) =
quantizedBlock;
end
end
end

Output :-

25 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

14. Program for implementation of image restoration techniques.


Matlab code :-
clc
close all

input_image = imread('apple3.bmp');
degraded_image = im2double(input_image);

kernel_size = 5;
kernel = fspecial('gaussian', kernel_size, 1);

noise_variance = 0.02;
noisy_degraded_image = degraded_image + sqrt(noise_variance) * randn(size(degraded_image));

restored_image = myWienerFilter(noisy_degraded_image, kernel, noise_variance);

subplot(1, 3, 1); imshow(degraded_image); title('Degraded Image');


subplot(1, 3, 2); imshow(noisy_degraded_image); title('Noisy Degraded Image');
subplot(1, 3, 3); imshow(restored_image); title('Restored Image');

function restored_image = myWienerFilter(input_image, kernel, noise_variance)

F_input = fft2(input_image);
F_kernel = fft2(kernel, size(input_image, 1), size(input_image, 2));

H = conj(F_kernel) ./ (abs(F_kernel).^2 + noise_variance);

F_restored = F_input .* H;

restored_image = abs(ifft2(F_restored));

end

Output:-

26 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

15. Program for implementation of image Intensity slicing technique for image enhancement.
Matlab code :-
clc
close all

input_image = imread('puppy.jpg');

if size(input_image, 3) == 3
input_image = rgb2gray(input_image);
end

lower_threshold = 120;
upper_threshold = 200;
new_intensity = 255;

enhanced_image = intensitySlicing(input_image, lower_threshold, upper_threshold, new_intensity);

subplot(1, 2, 1); imshow(input_image); title('Original Image');


subplot(1, 2, 2); imshow(enhanced_image); title('Enhanced Image');

function enhanced_image = intensitySlicing(input_image, lower_threshold, upper_threshold,


new_intensity)

[height, width] = size(input_image);

enhanced_image = zeros(height, width);

for y = 1:height
for x = 1:width
intensity = input_image(y, x);
if intensity >= lower_threshold && intensity <= upper_threshold
enhanced_image(y, x) = new_intensity;
else
enhanced_image(y, x) = intensity;
end
end
end
enhanced_image = cast(enhanced_image, class(input_image));
end

Output:-

27 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
16. Program for Canny Edge Detection Algorithm.
Matlab code :-
clc
close all
clear all

inputImage = imread('Images/crow.jpg');

if size(inputImage, 3) == 3
inputImage = rgb2gray(inputImage);
end

cannyEdges = edge(inputImage, 'Canny');

subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');

subplot(1, 2, 2);
imshow(cannyEdges);
title('Canny Edges');

Output:-

28 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
17. Program to obtain histogram equalization concept.
Matlab code :-
clc
close all

input_image = imread('Images/cameraman.jpg');
if size(input_image, 3) == 3
input_image = rgb2gray(input_image);
end

subplot(2, 2, 1); imshow(input_image); title('Original Image');


subplot(2, 2, 3); imhist(input_image); axis tight;title('Bfr Histogram Equilization');

[rows, cols] = size(input_image);


total_no_pixel=rows*cols;

% Calculate the histogram of the input image


histogram = zeros(1, 256);
for i = 1:rows
for j = 1:cols
histogram(input_image(i,j)+1) = histogram(input_image(i,j)+1) + 1;
end
end
%calculating probalility
for i = 1 : 256
histogram(i) = histogram(i) / total_no_pixel;
end

temp=histogram(1);
for i = 2:256
temp=temp+histogram(i);
histogram(i)=temp;
end

%mapping
for i = 1:rows
for j = 1:cols
input_image(i,j) = round(histogram(input_image(i,j)+1) *255);
end
end

subplot(2, 2, 2); imshow(input_image); title('Equalized Image');


subplot(2, 2, 4); imhist(input_image); axis tight;title('Afr Histogram Equilization');

29 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
Output:-

30 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
18. Program to implement smoothing or averaging filter in spatial domain.

Matlab code:-
clc
close all
clear all
originalImage = imread('Images/hibiscus.tif');
if size(originalImage, 3) == 3
originalImage = rgb2gray(originalImage);
end
grayImage = im2double(originalImage);
filterSize = 5; % Change this value for different filter sizes

% Compute the padding size based on the filter size


paddingSize = floor(filterSize / 2);
[rows, cols] = size(grayImage);
smoothedImage = zeros(rows, cols);

% Apply the averaging filter using convolution


for row = 1:rows
for col = 1:cols
neighborhood = grayImage(max(row - paddingSize, 1):min(row + paddingSize, rows), ...
max(col - paddingSize, 1):min(col + paddingSize, cols));

% Compute the average of the neighborhood and assign it to the smoothed image
smoothedValue = mean(neighborhood(:));
smoothedImage(row, col) = smoothedValue;
end
end

subplot(1, 2, 1);
imshow(grayImage);
title('Original Image');

subplot(1, 2, 2);
imshow(smoothedImage);
title('Smoothed Image');

Output:-

31 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

19. Program for morphological operation: erosion and dilation.

Matlab code:-
clc
close all
image = imread('morph2.bmp');
se = ones(3);
dilated_image = custom_dilation(image, se);
eroded_image = custom_erosion(image, se);

subplot(2, 3, 2);
imshow(image);
title('Original Image');

subplot(2, 3, 4);
imshow(dilated_image);
title('Dilated Image');

subplot(2, 3, 6);
imshow(eroded_image);
title('Eroded Image');

function output_image = custom_dilation(input_image, se)


[M, N] = size(input_image);
[se_m, se_n] = size(se);
pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);

padded_image = padarray(input_image, [pad_m, pad_n], 0, 'both');


output_image = zeros(size(input_image));

for i = 1:M
for j = 1:N
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = max(region(:));
end
end
end

function output_image = custom_erosion(input_image, se)


[M, N] = size(input_image);
[se_m, se_n] = size(se);
pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);

padded_image = padarray(input_image, [pad_m, pad_n], 1, 'both');


output_image = zeros(size(input_image));

for i = 1:M
for j = 1:N
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = min(region(:));
end
end
32 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs

end
Output:-

33 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
20. Program for DCT/IDCT computation.

Matlab code:-
clc
close all
% Read the input image
inputImage = imread('lenna.jpg');

% Convert the grayscale image to double precision


grayImage = im2double(inputImage);

% Compute the 2D DCT of the image


dctImage = dct2(grayImage);

compressionFactor = 0.05;
numCoefficientsToKeep = round(compressionFactor * numel(dctImage));
sortedCoefficients = sort(abs(dctImage(:)), 'descend');
threshold = sortedCoefficients(numCoefficientsToKeep);
dctImage(abs(dctImage) < threshold) = 0;

% Reconstruct the image using the IDCT


reconstructedImage = idct2(dctImage);

subplot(1, 3, 1);
imshow(grayImage);
title('Original Image');

subplot(1, 3, 2);
imshow(dctImage);
title('DCT of Image');

subplot(1, 3, 3);
imshow(reconstructedImage);
title('IDCT of Image');

Output:-

34 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
21. Program to compute the edges in the images using Roberts, Sobel, Canny, Log, Perwitt edge
detection methods.
Matlab code:-
clc
close all
inputImage = imread('Images/crow.jpg');
if size(inputImage, 3) == 3
inputImage = rgb2gray(inputImage);
end

cannyEdges = edge(inputImage, 'Canny');


sobelEdges = edge(inputImage, 'sobel');
robertEdges = edge(inputImage, 'roberts');
perwittEdges = edge(inputImage, 'prewitt');
logEdges = edge(inputImage, 'log');

subplot(3, 2, 1);
imshow(inputImage),title('Original Image');

subplot(3, 2, 2);
imshow(robertEdges),title('Roberts Edges');

subplot(3, 2, 3);
imshow(sobelEdges),title('Sobel Edges');

subplot(3, 2, 4);
imshow(cannyEdges),title('Canny Edges');

subplot(3, 2, 5);
imshow(perwittEdges),title('Perwitt Edges');

subplot(3, 2, 6);
imshow(logEdges),title('Log Edges');

Output:-

35 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
22. Program to perform watershed transformation on an image.

Matlab code:-
clc
close all
clear all
inputImage = imread('Images/water_coins.jpg');
grayImage = rgb2gray(inputImage);

thresholdValue = graythresh(grayImage);
binaryMask = imbinarize(grayImage, thresholdValue);

% Compute the distance transform of the binary mask


distanceTransform = bwdist(~binaryMask);

% Find the regional minima to use as markers for the watershed transformation
regionalMinima = imregionalmin(distanceTransform);

% Perform watershed transformation using the regional minima as markers


labels = watershed(imcomplement(distanceTransform));

overlayImage = inputImage;
overlayImage(labels == 0) = 0;

subplot(2, 2, 1);
imshow(inputImage);
title('Original Image');

subplot(2, 2, 3);
imshow(binaryMask);
title('Binary Mask');

subplot(2, 2, 4);
imshow(overlayImage);
title('Watershed Regions');
colormap(gca, jet); % Apply color map for visualization
colorbar;

Output:-

36 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
23. Program for the dilation and erosion process with a character image example.

Matlab code:-
clc
close all

character_image = imread('morph1.bmp');

se = ones(3);

dilated_image = custom_dilation(character_image, se);

eroded_image = custom_erosion(character_image, se);

% Display the results


subplot(2, 3, 2);
imshow(character_image);
title('Original Character Image');

subplot(2, 3, 4);
imshow(dilated_image);
title('Dilated Image');

subplot(2, 3, 6);
imshow(eroded_image);
title('Eroded Image');

function output_image = custom_dilation(input_image, se)


[M, N] = size(input_image);
[se_m, se_n] = size(se);
pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);

padded_image = padarray(input_image, [pad_m, pad_n], 0, 'both');


output_image = zeros(size(input_image));

for i = 1:M
for j = 1:N
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = max(region(:));
end
end
end

function output_image = custom_erosion(input_image, se)


[M, N] = size(input_image);
[se_m, se_n] = size(se);
pad_m = floor(se_m / 2);
pad_n = floor(se_n / 2);

padded_image = padarray(input_image, [pad_m, pad_n], 1, 'both');


output_image = zeros(size(input_image));

for i = 1:M
for j = 1:N

37 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
region = padded_image(i:i+2*pad_m, j:j+2*pad_n);
output_image(i, j) = min(region(:));
end
end
end

Output:-

38 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
24. Program to separate the RGB plane from the color image.
clear all
close all

input_image=imread('mixedfruit.bmp');

red_color =input_image;da
green_color =input_image;
blue_color =input_image;

red_color(:,:,2)=0;
red_color(:,:,3)=0;

green_color(:,:,1)=0;
green_color(:,:,3)=0;

blue_color(:,:,1)=0;
blue_color(:,:,2)=0;

subplot(2, 3, 2);
imshow(input_image);
title('Original RGB Image');
subplot(2, 3, 4);
imshow(red_color);
title('Red Color Plane');
subplot(2, 3, 5);
imshow(green_color);
title('Green Color Plane');
subplot(2, 3, 6);
imshow(blue_color);
title('Blue Color Plane');

Output:-

39 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
25. Program to demonstrate run length encoding and decoding.

Matlab code:-
clc
input_numbers = [10, 10, 2, 2, 2, 30, 4, 4, 4, 4];
encoded_numbers = runLengthEncodeNumbers(input_numbers);
decoded_numbers = runLengthDecodeNumbers(encoded_numbers);

disp(['Original: ' num2str(input_numbers)]);


disp(['Encoded: ' num2str(encoded_numbers)]);
disp(['Decoded: ' num2str(decoded_numbers)]);

function encoded = runLengthEncodeNumbers(input_nums)


encoded = [];
count = 1;
for i = 1:length(input_nums)-1
if input_nums(i) == input_nums(i+1)
count = count + 1;
else
encoded = [encoded, count, input_nums(i),];
count = 1;
end
end
encoded = [encoded, count, input_nums(end),];
end

function decoded = runLengthDecodeNumbers(encoded_nums)


decoded = [];
for i = 1:2:length(encoded_nums)-1
count = encoded_nums(i);
symbol = encoded_nums(i+1);
decoded = [decoded repmat(symbol, 1, count)];
end
end

Output :-
Original : 10 10 2 2 2 30 4 4 4 4
Encoded : 2 10 3 2 1 30 4 4
Decoded : 10 10 2 2 2 30 4 4 4 4

40 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
26. Program to read a document image and perform morphological hole filling operation.

Matlab code:-

clc
close all
clear all
inputImage = imread('keyimg1.PNG');

grayImage = rgb2gray(inputImage);

binaryImage = imbinarize(grayImage, 'adaptive');

% Perform morphological hole filling


filledImage = imfill(binaryImage, 'holes');

subplot(1, 2, 1);
imshow(inputImage);
title('Original Image');

subplot(1, 2, 2);
imshow(filledImage);
title('Filled Image');

Output:-

41 | P a g e
M.Sc. Computer Science SCT 4.1: DIP Programs
27. Program to demonstrate geometric transformations like scaling, rotate, affine.
Matlab code :-
clc
close all
inputImage = imread('Images/cameraman.jpg');

subplot(2, 3, 2);
imshow(inputImage);
title('Original Image');
% Scaling (Resize the image)
scaleFactor = 1.5; % You can adjust this value for different scaling factors
scaledImage = imresize(inputImage, scaleFactor);
subplot(2, 3, 4);
imshow(scaledImage);
title('Scaled Image');

% Rotation
angle = 120; % You can adjust this value for different rotation angles (in degrees)
rotatedImage = imrotate(inputImage, angle, 'bilinear', 'crop');
subplot(2, 3, 5);
imshow(rotatedImage);
title('Rotated Image');
xlabel(sprintf('Rotated with %g deg angle',angle));

% Affine Transformation
% Define the affine transformation matrix
affineMatrix = [cosd(angle) sind(angle) 0;
-sind(angle) cosd(angle) 0;
0 0 1];
tform = affine2d(affineMatrix);
affineImage = imwarp(inputImage, tform);
subplot(2, 3, 6);
imshow(affineImage);
title('Affine Transformed Image');

Output:-

42 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy