This MATLAB code applies the Roberts edge detection filter to an input image. It first reads in the image and converts it to grayscale. It then initializes an output matrix to store the filtered image. Next, it defines the Roberts filter masks and loops through the image, calculating the gradient approximations in the x and y directions using the masks. It calculates the magnitude of the gradient vector and stores it in the output matrix. Finally, it displays the original and filtered images, with the filtered image highlighting edges detected by the Roberts filter.
Generative AI for Social Good at Open Data Science East 2024
Image Processing Tasks
1. Task 01
a. Download RGB image and read a RGB image.
The code used for this as follows.
rgbImage = imread("image.png");
imshow(rgbImage)
b. Create a separate image for each colour planes (Red, Green and Blue) of the image.
The code used for this as follows.
imSize = 200;
RGB = reshape(ones(imSize,1)*reshape(jet(imSize),1,imSize*3),[imSize,imSize,3]);
imshow(RGB)
title('Original RGB Image')
figure
subplot(1,3,1)
imshow(R)
title('Red Channel')
subplot(1,3,2)
imshow(G)
title('Green Channel')
subplot(1,3,3)
imshow(B)
title('Blue Channel')
allBlack = zeros(size(RGB,1,2),class(RGB));
justR = cat(3,R,allBlack,allBlack);
justG = cat(3,allBlack,G,allBlack);
2. justB = cat(3,allBlack,allBlack,B);
c. Display each colour plane image separately and display the original image.
figure
montage({justR,justG,justB},'Size',[1 3], ...
"BackgroundColor",'w',"BorderSize",10);
title('Color Representation of the Red, Green, and Blue Color Channels');
3. Task 02
2.1 - Read an image and display its property in MATLAB.
The code used as follows.
rgbImage = imread("image.png");
imshow(rgbImage)
4.
5. 2.2 - Find the histogram of the Grayscale image.
grayImage = rgb2gray(rgbImage);
imshow(grayImage)
6. Apply histogram equalization for the Gray scaled image of figure 02.
figure
subplot(1,3,1)
imshow(I)
subplot(1,3,2:3)
imhist(I)
7. 2.5 Display the findings 2.1 to 2.4 in one frame in MATLAB. Label x and y axis’s
if true
figure;
subplot(2,2,1),imshow(first_image);
subplot(2,2,2),imshow(second_image);
subplot(2,2,3),imshow(third_image);
subplot(2,2,4),imshow(fourth_image);
end
8. 2.6 Critically review the results found before and after applying the histogram equalization.
Histograms are graphs that display the distribution of your continuous data. They are fantastic
exploratory tools because they reveal properties about your sample data in ways that summary
statistics cannot. For instance, while the mean and standard deviation can numerically summarize
your data, histograms bring your sample data to life.
In this blog post, I’ll show you how histograms reveal the shape of the distribution, its central
tendency, and the spread of values in your sample data. You’ll also learn how to identify outliers,
how histograms relate to probability distribution functions, and why you might need to use
hypothesis tests with them.
Histograms, Central Tendency, and Variability
Use histograms when you have continuous measurements and want to understand the distribution
of values and look for outliers. These graphs take your continuous measurements and place them
into ranges of values known as bins. Each bin has a bar that represents the count or percentage of
observations that fall within that bin. Histograms are similar to stem and leaf plots.
Task 03
3.1 - Enlarge an image to its double size.
Code is given below.
magnificationFactor = 1.25;
J = imresize(I,magnificationFactor);
imshowpair(I,J,method="montage")
K = imresize(I,[100 150]);
10. Image double size
3.2 - Rotate an image in a clockwise and anticlockwise direction.
The code is shown below
Clockwise:
J = imrotate(I,-90,'bilinear','crop');
figure
imshow(J)
title('Rotated Image')
14. s3=uint8(sp2)
subplot(2,2,4)
imshow(s3);
title 'c=3'
3.4.3 Power low transformation
Code :
clc; clear all;
c=1;
Gamma=input('Enter the Gamma values = '); % Must be vector, Ex:[3 4 5]
x=imread('remote.jpg');
x1=double(x);
y=c*(x1.^Gamma(1)); % s=c*(r^ γ)
y1=c*(x1.^Gamma(2));
y2=c*(x1.^Gamma(3));
subplot(141),imshow(x), title('Aerial image')
subplot(142),imshow((y),[]), title('Corrected image(Gamma=3)')
subplot(143),imshow((y1),[]), title('Corrected image(Gamma=4)')
subplot(144),imshow((y2),[]), title('Corrected image(Gamma=5)')
15. 3.4.4 Piecewise Linear Transformation (Contrast Stretching)
CODE:
clear all;
close all;
clc;
%% Reading an image
16. a=imread('cameraman.tif');
a=double(a);
s=size(a);
%% Defingin points and calculating equation parameters
p1=[0,0];
p2=[150,20];
p3=[200,200];
p4=[255,255];
m1=(p1(1,2)-p2(1,2))/(p1(1,1)-p2(1,1));
m2=(p2(1,2)-p3(1,2))/(p2(1,1)-p3(1,1));
m3=(p3(1,2)-p4(1,2))/(p3(1,1)-p4(1,1));
c1=p1(1,2)-m1*p1(1,1);
c2=p2(1,2)-m2*p2(1,1);
c3=p3(1,2)-m3*p3(1,1);
%% Transformation function
t=[];
for x=0:255
if(x<=p2(1,1))
t=[t (m1*x+c1)];
end
if(x>p2(1,1) && x<=p3(1,1))
t=[t (m2*x+c2)];
end
if(x>p3(1,1) && x<=p4(1,1))
t=[t (m3*x+c3)];
end
end
%% Getting output image
for n=1:s(1,1)
for m=1:s(1,2)
ot(n,m)=t(a(n,m)+1);
end
end
plot(t)
grid on;
xlabel('Intensity in input image');
ylabel('Intensity in output image')
title('Piece-wise linear transformation : Contrast stretching function')
figure()
subplot(1,2,1)
imshow(a/255)
title('Original image')
subplot(1,2,2)
imshow(ot./255)
title('Contrast stretching')
Task 04
17. Write a MATLAB function called "Noise Edge Filter" that accepts a string (image file name) and
displays images as shown in figure 3 (original image, image using Gaussian filter, Laplacian
image and image using Laplacian filter).
J = imnoise(I,'gaussian',0,0.025);
imshow(J(600:1000,1:600));
title('Portion of the Image with Added Gaussian Noise');
A = imread('peppers.png');
sigma = 0.4;
alpha = 0.5;
B = locallapfilt(A, sigma, alpha);
% MATLAB code for
% Edge detection using Laplacian Filter.
k=imread("logo.png");
% Convert rgb image to grayscale.
k1=rgb2gray(k);
% Convert into double format.
k1=double(k1);
% Define the Laplacian filter.
Laplacian=[0 1 0; 1 -4 1; 0 1 0];
% Convolve the image using Laplacian Filter
k2=conv2(k1, Laplacian, 'same');
% Display the image.
imtool(k1, []);
imtool(abs(k2,[]);
18. Task 5
5.1 Apply FFT to grayscale image and find the frequency spectrum of the image
img = imread("6502icbtbe---dip-assignment-5.jpg");
imgFFT = fft2(double(img));
img2 = ifft2(imgFFT);
imshow(img)
19. figure
imshow(img2)
5.2 Plot a frequency spectrum in MATLAB
rng('default')
fs = 100; % sample frequency (Hz)
t = 0:1/fs:10-1/fs; % 10 second span time vector
x = (1.3)*sin(2*pi*15*t) ... % 15 Hz component
20. + (1.7)*sin(2*pi*40*(t-2)) ... % 40 Hz component
+ 2.5*randn(size(t)); % Gaussian noise;
y = fft(x);
n = length(x); % number of samples
f = (0:n-1)*(fs/n); % frequency range
power = abs(y).^2/n; % power of the DFT
plot(f,power)
xlabel('Frequency')
ylabel('Power')
y0 = fftshift(y); % shift y values
f0 = (-n/2:n/2-1)*(fs/n); % 0-centered frequency range
power0 = abs(y0).^2/n; % 0-centered power
plot(f0,power0)
xlabel('Frequency')
ylabel('Power')
whaleFile = 'bluewhale.au';
[x,fs] = audioread(whaleFile);
plot(x)
xlabel('Sample Number')
ylabel('Amplitude')
moan = x(2.45e4:3.10e4);
t = 10*(0:1/fs:(length(moan)-1)/fs);
plot(t,moan)
xlabel('Time (seconds)')
ylabel('Amplitude')
xlim([0 t(end)])
m = length(moan); % original sample length
n = pow2(nextpow2(m)); % transform length
y = fft(moan,n); % DFT of signal
f = (0:n-1)*(fs/n)/10;
power = abs(y).^2/n;
plot(f(1:floor(n/2)),power(1:floor(n/2)))
xlabel('Frequency')
ylabel('Power')
21. 5.3, 5.4 - Design a low pass digital filter in frequency domain.
Code
fs = 2e3;
t = 0:1/fs:0.3-1/fs;
l = [0 130.81 146.83 164.81 174.61 196.00 220 246.94];
m = [0 261.63 293.66 329.63 349.23 392.00 440 493.88];
23. 5.5
Code:
% MATLAB Code | Ideal Low Pass Filter
% Reading input image : input_image
input_image = imread('[name of input image file].[file format]');
% Saving the size of the input_image in pixels-
% M : no of rows (height of the image)
% N : no of columns (width of the image)
[M, N] = size(input_image);
% Getting Fourier Transform of the input_image
% using MATLAB library function fft2 (2D fast fourier transform)
FT_img = fft2(double(input_image));
% Assign Cut-off Frequency
24. D0 = 30; % one can change this value accordingly
% Designing filter
u = 0:(M-1);
idx = find(u>M/2);
u(idx) = u(idx)-M;
v = 0:(N-1);
idy = find(v>N/2);
v(idy) = v(idy)-N;
% MATLAB library function meshgrid(v, u) returns
% 2D grid which contains the coordinates of vectors
% v and u. Matrix V with each row is a copy
% of v, and matrix U with each column is a copy of u
[V, U] = meshgrid(v, u);
% Calculating Euclidean Distance
D = sqrt(U.^2+V.^2);
% Comparing with the cut-off frequency and
% determining the filtering mask
H = double(D <= D0);
% Convolution between the Fourier Transformed
% image and the mask
G = H.*FT_img;
% Getting the resultant image by Inverse Fourier Transform
25. % of the convoluted image using MATLAB library function
% ifft2 (2D inverse fast fourier transform)
output_image = real(ifft2(double(G)));
% Displaying Input Image and Output Image
subplot(2, 1, 1), imshow(input_image),
subplot(2, 1, 2), imshow(output_image, [ ]);
5.6 Display before and after applying the low pass frequency domain low pass filter to the
image.
26.
27. 5.7 Critically review the results found before and after applying the frequency domain low pass
filter to the image
Image Smoothing (Low-pass Frequency Domain Filters) A low-pass filter that attenuates
(suppresses) high frequencies while passing the low frequencies which results in creating a blurred
(smoothed) image. It leaves the low frequencies of the Fourier transform relatively unchanged and
ignores the high frequency noise components. Three main low-pass filters are:
28. i. Ideal low-pass filter (ILPF)
An ideal low pass filter deals with the removal of all high frequency values of the Fourier transform
that are at a distance greater than a specified distance from the origin of the transformed image.
The filter transfer function for the Ideal low-pass filter is given by:
Task 6
6.1 Apply roberts edge detector for an image
Code:
% MATLAB Code | Robert Operator from Scratch
% Read Input Image
input_image = imread('[name of input image file].[file format]');
% Displaying Input Image
input_image = uint8(input_image);
figure, imshow(input_image); title('Input Image');
% Convert the truecolor RGB image to the grayscale image
input_image = rgb2gray(input_image);
% Convert the image to double
input_image = double(input_image);
% Pre-allocate the filtered_image matrix with zeros
filtered_image = zeros(size(input_image));
% Robert Operator Mask
Mx = [1 0; 0 -1];
My = [0 1; -1 0];
29. % Edge Detection Process
% When i = 1 and j = 1, then filtered_image pixel
% position will be filtered_image(1, 1)
% The mask is of 2x2, so we need to traverse
% to filtered_image(size(input_image, 1) - 1
%, size(input_image, 2) - 1)
for i = 1:size(input_image, 1) - 1
for j = 1:size(input_image, 2) - 1
% Gradient approximations
Gx = sum(sum(Mx.*input_image(i:i+1, j:j+1)));
Gy = sum(sum(My.*input_image(i:i+1, j:j+1)));
% Calculate magnitude of vector
filtered_image(i, j) = sqrt(Gx.^2 + Gy.^2);
end
end
% Displaying Filtered Image
filtered_image = uint8(filtered_image);
figure, imshow(filtered_image); title('Filtered Image');
% Define a threshold value
thresholdValue = 100; % varies between [0 255]
output_image = max(filtered_image, thresholdValue);
output_image(output_image == round(thresholdValue)) = 0;
30. % Displaying Output Image
output_image = im2bw(output_image);
figure, imshow(output_image); title('Edge Detected Image');
6.2 Apply Perwitt edge detector for a selected image
% MATLAB Code | Prewitt Operator from Scratch
% Read Input Image
input_image = imread('[name of input image file].[file format]');
% Displaying Input Image
input_image = uint8(input_image);
figure, imshow(input_image); title('Input Image');
% Convert the truecolor RGB image to the grayscale image
input_image = rgb2gray(input_image);
% Convert the image to double
31. input_image = double(input_image);
% Pre-allocate the filtered_image matrix with zeros
filtered_image = zeros(size(input_image));
% Prewitt Operator Mask
Mx = [-1 0 1; -1 0 1; -1 0 1];
My = [-1 -1 -1; 0 0 0; 1 1 1];
% Edge Detection Process
% When i = 1 and j = 1, then filtered_image pixel
% position will be filtered_image(2, 2)
% The mask is of 3x3, so we need to traverse
% to filtered_image(size(input_image, 1) - 2
%, size(input_image, 2) - 2)
% Thus we are not considering the borders.
for i = 1:size(input_image, 1) - 2
for j = 1:size(input_image, 2) - 2
% Gradient approximations
Gx = sum(sum(Mx.*input_image(i:i+2, j:j+2)));
Gy = sum(sum(My.*input_image(i:i+2, j:j+2)));
% Calculate magnitude of vector
filtered_image(i+1, j+1) = sqrt(Gx.^2 + Gy.^2);
end
end
33. % Read Input Image
input_image = imread('[name of input image file].[file format]');
% Displaying Input Image
input_image = uint8(input_image);
figure, imshow(input_image); title('Input Image');
% Convert the truecolor RGB image to the grayscale image
input_image = rgb2gray(input_image);
% Convert the image to double
input_image = double(input_image);
% Pre-allocate the filtered_image matrix with zeros
filtered_image = zeros(size(input_image));
% Sobel Operator Mask
Mx = [-1 0 1; -2 0 2; -1 0 1];
My = [-1 -2 -1; 0 0 0; 1 2 1];
% Edge Detection Process
% When i = 1 and j = 1, then filtered_image pixel
% position will be filtered_image(2, 2)
% The mask is of 3x3, so we need to traverse
% to filtered_image(size(input_image, 1) - 2
%, size(input_image, 2) - 2)
% Thus we are not considering the borders.
34. for i = 1:size(input_image, 1) - 2
for j = 1:size(input_image, 2) - 2
% Gradient approximations
Gx = sum(sum(Mx.*input_image(i:i+2, j:j+2)));
Gy = sum(sum(My.*input_image(i:i+2, j:j+2)));
% Calculate magnitude of vector
filtered_image(i+1, j+1) = sqrt(Gx.^2 + Gy.^2);
end
end
% Displaying Filtered Image
filtered_image = uint8(filtered_image);
figure, imshow(filtered_image); title('Filtered Image');
% Define a threshold value
thresholdValue = 100; % varies between [0 255]
output_image = max(filtered_image, thresholdValue);
output_image(output_image == round(thresholdValue)) = 0;
% Displaying Output Image
output_image = im2bw(output_image);
figure, imshow(output_image); title('Edge Detected Image');
35. Task 7
7.1 Use the MATLAB function to add salt and pepper noise.
J = imnoise(I,'salt & pepper',0.02);
figure
imshow(J)
7.2 Implementing 3 x 3 median filter for the image given
36. I = imread(image);
[x,y] = size(I);
for i = 2:x-1
for j = 2:y-1
sum = 0;
for ii = i-1:i+1
for jj = j-1:j+1
sum = sum + I(ii,jj);
end
end
I2(i,j) = ceil(sum/9);
end
end
imshow(I2);
7.3 Apply the above-mentioned filter to the Gray image and display all the output in one
window.
I = imread(“playcube.jpg”);
[x,y] = size(I);
for i = 2:x-1
for j = 2:y-1
sum = 0;
for ii = i-1:i+1
for jj = j-1:j+1
sum = sum + I(ii,jj);
end
end
I2(i,j) = ceil(sum/9);
end
end
imshow(I2);
37. Task 8
As one of the information technologies, Image processing is the process of modifying or
interpreting existing pictures, such as photographs. (Hearn & Baker, 1997). It originates from
newspaper industry in 1920s, which is applied in “Bartlane cable picture transmission system”. It
contains image segmentation, image enhancement, image recognition and so on. Three layers of
image processing technology are:
1. Low-level processing: inputs and outputs are images
2. Mid -level processing: inputs are images and outputs are attributes
3. High -level processing: “making sense” , performing cognitive functions
Nowadays, image processing technology shows more and more power in many fields such as
medical, industrial and commercial areas. In recent years, image processing technology is widely
used in medical science to help understand and gather information from biomedical images of
nature of human biological systems. Transformation from 2D to 3D images, automated feature
finding and mage comparison is the magnificent outcomes of the image processing technology.
Moreover, image processing is also applied in textile industry to detect yarn parameters, the
roughness of textile surface and the defect of textile, which is proved to be very effective. To be
most important, many improved theories, algorithms and models of image processing technology
are proposed and inspired based on actual application research such as “Omron's new ZFX-C
Smart Vision Sensor”. It proves to that application research of image processing technology
contributes not only to help understand and gather information from the images but also to self-
develop really in theories, algorithms and models.
38. So far, taking on the inspection of welding, there is not any application research and knowledge
of image processing technology. As one of the main methods in modern steel production, welding
plays an important role in the economy. Welding has been widely applied in many fields of
aviation, petroleum, chemicals, electricity, railways and so on.
The craft of welding can be improved from the aspects of welding tools, welding technique and
welding inspection. So far, welding inspection has been a very complex issue because a variety of
defects will be produced in the welding process. Welded structural parts which usually stand a
high temperature, high pressure, corrosion and other extreme environments lead to performance
deterioration, affect the safe operation and even endanger the industrial production. Therefore, it
originates my research interest for it is very important to effectively detect internal welding defects
of the steeled-structure. The general construction work is connected by components such as steel
and steel plate structure. Constituting the entire structure by components, it ensures safe and
reliable, clear power transmission, simple installation and save steel. So, the connections among
different components are divided into welding connection, rivet connection and bolted connection.
References
Rafael C. Gonzalez, Richard E. Woods, “Digital Image Processing”, Pearson Prentice Hall,
Third Edition, ISBN 0-13-168728-x 978-0-13-168728-8.
Sasan John jiu, “Frequency Domain Filter In Digital Image Processing In Remote Sensing: An
Overview”, International journal of innovative r research & development, volume2, issue 6 july,
2013, ISSN:2278- 0211
Omeed kamal khorsheed, “Produce low-pass and high- pass image filter in java”, International
journal of Advances inengineering &Technology, July, 2014, ISSN:22311963
Snehal O.Mundhada, V.K.Shandilya, “Spatial and Transformation Domain Techniques for
Enhancement”, International Journal of engineering Science and Innovative technology,
Volume1, Issue2, November2012 ISSN: 2319-5967.
Aziz makandar, Bhagirathi Halali, “Image Enhancement Techniques using Highpass and
Lowpass Filters”, International journal of computer application (0975-88875), Volume109
No.14, January2015.
Amit shukla, Dr.R.K.Singh, “Performance analysis of frequency domain filters for noise
reduction”, e-Joumal of Science & technology, (5), 9, 2014
Garima Goyal, Ajay Kumar Bansal , Manish Singhal, “Review Paper on Various Filtering
Techniques and Future Scope to Apply These on TEM Images” International Journal of
Scientific and Research Publications, Volume 3, Issue 1, January 2013, ISSN 2250-3153
Samayita Bhattacharya, Kalyani mali, “Comparative Studyof Different Filters on Images in
Frequency Domain ”, International Journal of Advance Research in computer science and
software Engineering, Volume4, issue8, August 2014, issue: 2277128x.s
39. B.D.Venkatramana Reddy & Dr.T.Jayachandra Prasad, “Frequency Domain Filtering of Colour
Images using Quaternion Fourier transforms”, IJCST, Vol.1, Issue2, December 2010,ISSN0976-
8491.
Jakia Afruz , Va’Juanna Wilson, “Frequency Domain Pseudo-color to Enhance Ultrasound
Images”, Canadian center of science and Education, Volume3, No.4, November 2014.