Programming PDF
Programming PDF
LAB REPORT ON
COMPUTATIONAL TOOLS AND TECHNIQUES
Submitted By
Ayush Mishra 21111
V SEMESTER BTECH-CSE
SCHOOL OF COMPUTING
INDIAN INSTITUTE OF INFORMATION TECHNOLOGY
UNA
HIMACHAL PRADESH
INDEX
S.NO. Objective Page. Signature
No.
1 Installation of ns2
2 Write a code for addition, subtraction, multiplication,
and division in ns2.
3 To create various events at different time intervals in
ns2
4 Implementation of Star Topology in ns2
5 Implementation of Ring Topology in ns2.
6 Implementation of TCP protocol in ns2
7 Implementation of UDP protocol in ns2.
8 Implementation of Routing protocol in ns2
9 Installation of ns3.
10 Implementation of Dijkstra’s Algorithm in ns3.
11 Creation of nodes in ns3
12 To perform image alteration
Program to add Gaussian Noise in the image
Program to read images from the zip file
Program to apply Gaussian Blur on the single
image.
To apply operations on images using PIL
library
Objective: The aim of this experiment is to install ns2, a popular network simulation tool, along with
the NAM network animator.
i. Step 1:
Open the terminal or command window. Type the following commands one-by-one and press
Enter after each command:
sudo apt-get update
sudo apt-get install ns2
sudo apt-get install nam
sudo apt-get install tcl
ii. Step 2:
After installation, type the command "nam" in the terminal to launch the NAM network
animator window.
If the NAM window does not open, follow the steps below:
a. Go to https://ubuntu.pkgs.org/18.04/ubuntu-universe-amd64/nam_1.15-4_amd64.deb.html b.
Download the "nam_1.15-4_amd64.deb" file from the provided link. c. In the terminal, run the
command "sudo dpkg -i nam_1.15-4_amd64.deb".
iii. Step 3:
CSL-502 21111 1
set tracef [open wired2.tr w]
# Establish the links between the nodes with bandwidth and delay
CSL-502 21111 2
$ns at 1.0 "$ftp start"
iv. Step 4:
Run the script using the following command in the terminal:
ns ex2.tcl
CSL-502 21111 3
Experiment 2
Aim: Write a code for addition, subtraction, multiplication, and division in ns2.
Objective: The objective of this experiment is to perform basic arithmetic operations (addition,
subtraction, multiplication, and division) using ns2's scripting capabilities.
Operations Outputs
i. Addition
set a 2
set b 6
set add [expr $a + $b]
set msg “Addi on:”
puts “$msg $add”
ii. Subtraction
set a 2
set b 6
set add [expr $a - $b]
set msg “Subtrac on:”
puts “$msg $add”
iii. Multiply
Set a 2
set b 6
set add [expr $a - $b]
set msg “Mul ply:”
puts “$msg $add”
iv. Division
set a 2
CSL-502 21111 4
set b 6
set add [expr $a - $b]
set msg “Division:”
puts “$msg $add”
CSL-502 21111 5
Experiment 3
Objective: The objective of this experiment is to create and schedule various events at different time
intervals using ns2's scripting capabilities.
Code:
Puts ”line1”;
$ns run;
CSL-502 21111 6
Experiment 4
Objective: The objective of this experiment is to simulate a Star Topology using ns2, where all nodes
are connected to a central hub node.
Code:
CSL-502 21111 7
$ns duplex-link-op $n(0) $n(6) orient left
#Scheduling
$ns at 2.0 "finish"
$ns run
CSL-502 21111 8
Experiment 5
Code:
CSL-502 21111 9
$ns duplex-link-op $n(7) $n(0) orient right-up
#Scheduling
$ns at 2.0 "finish"
$ns run
CSL-502 21111 10
Experiment 6
Objective: The objective of this experiment is to simulate the implementation of the TCP
(Transmission Control Protocol) in ns2, which is a widely used transport protocol in computer
networks.
Code:
CSL-502 21111 11
$ns duplex-link $node_($server) $node_($router) 2Mb 50ms DropTail
$ns duplex-link $node_($router) $node_($client) 2Mb 50ms DropTail
$ns duplex-link-op $node_($server) $node_($router) orient right
$ns duplex-link-op $node_($router) $node_($client) orient right
#————Labelling—————-#
$ns at 0.0 "$node_($server) label Server"
$ns at 0.0 "$node_($router) label Router"
$ns at 0.0 "$node_($client) label Client"
$ns at 0.0 "$node_($server) color blue"
$ns at 0.0 "$node_($client) color blue"
$node_($server) shape hexagon
$node_($client) shape hexagon
#————Data Transfer between Nodes—————-#
# Defining a transport agent for sending
set tcp [new Agent/TCP]
# Attaching transport agent to sender node
$ns attach-agent $node_($server) $tcp
# Defining a transport agent for receiving
set sink [new Agent/TCPSink]
# Attaching transport agent to receiver node
$ns attach-agent $node_($client) $sink
#Connecting sending and receiving transport agents
$ns connect $tcp $sink
#Defining Application instance
set ftp [new Application/FTP]
# Attaching transport agent to application agent
$ftp attach-agent $tcp
# Setting flow color
$tcp set fid_ 4
# data packet generation starting time
$ns at 1.0 "$ftp start"
CSL-502 21111 12
# data packet generation ending time
$ns at 6.0 "$ftp stop"
#———finish procedure——–#
proc finish {} {
global ns nf nt
$ns flush-trace
close $nf
close $nt
puts "running nam…"
exec nam test2.nam &
exit 0
}
#Calling finish procedure
$ns at 10.0 "finish"
$ns run
CSL-502 21111 13
Experiment 7
Objective: The objective of this experiment is to simulate the implementation of the TCP
(Transmission Control Protocol) in ns2, which is a widely used transport protocol in computer
networks.
Code:
$ns rtproto DV
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exit 0
CSL-502 21111 14
}
$ns run
CSL-502 21111 15
Experiment 8
Objective: The objective of this experiment is to simulate the implementation of a routing protocol
in ns2. Routing protocols are essential in computer networks to determine the best path for data packets
to travel from the source to the destination.
Code:
$ns rtproto LS
CSL-502 21111 16
$ns trace-all $
CSL-502 21111 17
$ns duplex-link $node7 $node1 1.5Mb 10ms DropTail
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exit 0
CSL-502 21111 18
}
$ns run
Experiment 9
CSL-502 21111 19
Objective: The objective of this experiment is to guide the installation of ns3, a widely used network
simulation tool, on an Ubuntu system.
i. Step 1: Prerequisites
Open a terminal and run the following commands to update the package list and install essential
dependencies:
Go to the ns3 official website (https://www.nsnam.org/releases/) and download the latest version of
ns-allinone (e.g., ns-allinone-3.36.1.tar.bz2).
After downloading the ns-allinone package, navigate to the directory where it is located and extract its
contents to the home folder. You can use the GUI by right-clicking and selecting "Extract" to the home
folder, or use the following command:
cd ~/ns-allinone-3.36.1/
Now, run the build.py script with the necessary options to enable examples and tests:
The build process will take some time depending on your system's speed.
CSL-502 21111 20
The installation of ns3 is now complete.
Experiment 10
CSL-502 21111 21
Objective: The objective of this experiment is to implement Dijkstra's algorithm in ns3, a widely
used algorithm for finding the shortest path between nodes in a graph.
Code:
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])
def minDistance(self, dist, sptSet):
min = 1e7
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
CSL-502 21111 22
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = Graph(5)
g.graph = [[0, 2, 0, 5, 0],
[1, 0, 8, 0, 9],
[7, 6, 0, 5, 0],
[1, 0, 4, 0, 2],
[0, 3, 0, 9, 0],
[0, 0, 4, 14, 10],
[0, 8, 0, 0, 0],
[8, 11, 0, 0, 10],
[0, 0, 2, 0, 0]
]
g.dijkstra(0)
Experiment 11
CSL-502 21111 23
Objective: The objective of this experiment is to implement to create two node and send messages
between them in ns3
Code:
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h" // Include the applications module
using namespace ns3;
int main (int argc, char *argv[])
{
// Enable logging for ns3 components
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
// Create two nodes
NodeContainer nodes;
nodes.Create (2);
// Create a point-to-point link between the nodes
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
// Set Internet stack on the nodes
InternetStackHelper stack;
stack.Install (nodes);
// Assign IP addresses to the devices
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
CSL-502 21111 24
Ipv4InterfaceContainer interfaces = address.Assign (devices);
// Print the assigned IP addresses
std::cout << "Node 0 IP address: " << interfaces.GetAddress(0) << std::endl;
std::cout << "Node 1 IP address: " << interfaces.GetAddress(1) << std::endl;
// Create an echo server application on Node 1
UdpEchoServerHelper echoServer(9); // Port number 9
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
// Create an echo client application on Node 0
UdpEchoClientHelper echoClient(interfaces.GetAddress (1), 9); // Echo server IP and port number
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
// Run the simulation
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Lab Experiment No 12
CSL-502 21111 25
Aim: To perform image alteration
Objective:
Code:
import cv2
import numpy as np
img = cv2.imread(’filename’)
mean = 0
stddev = sqrt(var)
cv2.imwrite(’G-Noise’+str(fil)+’.jpg’, noisy_img)
CSL-502 21111 26
Screenshot:
import zipfile
imgzip = zipfile.ZipFile("100-Test.zip")
inflist = imgzip.infolist()
for f in inflist:
ifile = imgzip.open(f)
img = Image.open(ifile)
print(img)
im=Image.open(’1.jpg’)
im=im.filter(ImageFilter.GaussianBlur(30))
CSL-502 21111 27
im.show()
Screenshot:
import os
size=(224,224)
for f in os.listdir(’.’):
if f.endswith(’.jpg’):
im1=Image.open(f)
fn,f1=os.path.splitext(f)
print(fn)
im1.thumbnail(size)
im1=im1.rotate(45)
im1=im1.convert(mode=’L’)
CSL-502 21111 28
im1=im1.filter(ImageFilter.GaussianBlur(4))
im1.save(’ping/{}.png’.format(fn))
Screenshot:
CSL-502 21111 29
Lab Experiment No. 13
Objectives:
Create scatter plots for Iris and Tips datasets to visualize data patterns.
Plot a bar chart on the Tips dataset to represent categorical data.
Develop a program to perform Singular Value Decomposition (SVD) on the Iris dataset.
Visualize Iris dataset with species differentiation and Tips dataset with correlations.
Demonstrate the utility of SVD for dimensionality reduction or data analysis.
Code:
import pandas as pd
data = pd.read_csv("Iris.csv")
plt.scatter(data['Species'], data['SepalLengthCm'])
plt.title("Scatter Plot")
plt.xlabel('Species')
plt.ylabel('SepalLengthCm')
plt.show()
CSL-502 21111 30
2. Plot a scatter plot on Tips Dataset.
import pandas as pd
data = sns.load_dataset("tips")
plt.title("Scatter Plot")
plt.xlabel('Day')
plt.ylabel('Tip')
plt.colorbar()
plt.show()
CSL-502 21111 31
3. Plot a Bar plot on Tips Dataset.
import pandas as pd
data = sns.load_dataset("tips")
plt.bar(data['day'], data['tip'])
plt.title("Bar Chart")
plt.xlabel('Day')
plt.ylabel('Tip')
plt.show()
CSL-502 21111 32
4. Write a program to perform singular value decomposition on iris dataset
import numpy as np
import pandas as pd
iris = datasets.load_iris()
X = iris.data
U, S, VT = np.linalg.svd(X)
print(X)
k=2
print(X_reduced)
Screenshot:
CSL-502 21111 33
Original Matrix Reduced matrix
CSL-502 21111 34
Lab Experiment No. 14
Objective:
Create programs to calculate the average distances between images using Phash and Whash
techniques.
Visualize the distribution of these distances with separate histograms.
Enhance the histograms by fitting Gaussian distribution curves.
Analyze the conformity of distances to a Gaussian distribution.
Implement Singular Value Decomposition (SVD) on the Iris dataset for dimensionality
reduction.
Use suitable libraries for SVD computations and interpret the results.
These experiments aim to gain insights from image data and explore data analysis techniques.
Code:
import numpy as np
import imagehash
import cv2
import glob
import os
l=[]
i=0;
CSL-502 21111 35
for img1 in glob.glob("/content/drive/MyDrive/test/*.jpg"):
img1 = cv2.imread(img1)
img1 = Image.fromarray(img1)
l.append(phash(img1))
l2=[]
img1 = cv2.imread(img1)
img1 = Image.fromarray(img1)
l2.append(phash(img1))
count=0
avg=[]
for i in range(len(l)):
for j in range(len(l2)):
d=(l[i]-l2[j])/64
avg.append(d)
Screenshot:
l=[]
i=0;
CSL-502 21111 36
img1 = cv2.imread(img1)
img1 = Image.fromarray(img1)
l.append(whash(img1))
l2=[]
img1 = cv2.imread(img1)
img1 = Image.fromarray(img1)
l2.append(whash(img1))
count=0
avg=[]
for i in range(len(l)):
for j in range(len(l2)):
d=(l[i]-l2[j])/64
avg.append(d)
Screenshot:
plt.xlabel('Average Distance')
plt.ylabel('Frequency')
CSL-502 21111 37
plt.title('Histogram of Average Distances')
plt.show()
Screenshot:
plt.figure(figsize=(8, 6))
mu = np.mean(avg)
sigma = np.std(avg)
print("Avrage of:",mu)
CSL-502 21111 38
pdf = pdf * (len(avg) / 31.5)
Screenshot:
CSL-502 21111 39
Lab Experiment No. 15
Aim: Python Programming and Exploring Image Processing Techniques and Principal Component
Analysis (PCA) for Data Visualization.
Objective:
Code:
l= [5,7,15,17,12.5,9,16,18]
sum=0
for i in range(len(l)):
sum=sum+l[i]
print(sum/len(l))
Output Screenshot:
import cv2
img = cv2.imread('/content/OIP.jpeg')
CSL-502 21111 40
# Convert BGR to RGB
plt.imshow(img_rgb)
plt.axis('off')
plt.show()
Output Screenshot:
import numpy as np
arr=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr.ndim)
print(arr.shape)
Output Screenshot:
import cv2
import numpy as np
CSL-502 21111 41
from PIL import Image
img = cv2.imread('/content/OIP.jpeg')
!mkdir noisy_image
for fil in [0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.15, 0.2, 0.25]:
mean = 0
stddev = sqrt(var)
cv2.imwrite(f'noisy_images/G-Noise{str(fil)}.jpg', noisy_img)
display(IPImage(f'noisy_images/G-Noise0.25.jpg'))
Output Screenshot:
CSL-502 21111 42
5. Program to read images from the zip file
import zipfile
imgzip = zipfile.ZipFile("100-Test.zip")
inflist = imgzip.infolist()
for f in inflist:
ifile = imgzip.open(f)
img = Image.open(ifile)
print(img)
im=im.filter(ImageFilter.GaussianBlur(10))
im.show()
CSL-502 21111 44
Lab Experiment No. 16
Objectives:
Introduce Principal Component Analysis (PCA) as a technique for data visualization and
dimensionality reduction.
Demonstrate the implementation of PCA using the sklearn library in Python.
Familiarize students with the load_wine dataset for practical application of PCA.
Provide hands-on experience in transforming and visualizing data using PCA.
Code:
wdata = load_wine()
X, y = wdata['data'], wdata['target']
print(X.shape)
print(y.shape)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
CSL-502 21111 45
plt. tle('Original Data')
plt.show()
# Perform PCA
pca = PCA()
Xt = pca.fit_transform(X)
plt.show()
plt.gca().add_ar st(legend1)
plt.show()
Screenshot:
CSL-502 21111 46
CSL-502 21111 47
CSL-502 21111 48
Lab Experiment No. 17
Objective:
Introduce students to the concept of image hashing and its applications in image recognition
and similarity analysis.
Familiarize students with various image hashing algorithms like phash and whash for
generating unique image identifiers.
Provide hands-on experience in implementing image hashing techniques using the Python
libraries PIL, imagehash, and cv2.
Instruct students on how to read and process multiple images from a specified directory.
Code:
!pip install imagehash # Add this line to install the module
import numpy as np
import imagehash
import cv2
import glob
import os
l=[]
img1 = cv2.imread(img1)
img1 = Image.fromarray(img1)
l.append(phash(img1))
CSL-502 21111 49
print(phash(img1))
count=0
for i in range(len(l)):
for j in range(len(l)):
if i!=j:
d=l[i]-l[j]
if d<10:
count=count+1
print("Duplicate Images:",count)
Screenshot:
CSL-502 21111 50
Lab Experiment No. 18
Objectives:
Code:
CSL-502 21111 51
% Replace the Red channel in the copy with the filtered Red channel
temp(:,:,1) = filtered_red;
% Display the original and filtered images side by side
figure;
subplot(1, 2, 1); % Create a 1x2 grid of subplots and select the first one
imshow(i);
title('Original Image');
subplot(1, 2, 2); % Select the second subplot
imshow(temp);
title('Filtered Image (Sharpened Red Channel)');
Screenshot:
CSL-502 21111 52
% Convert the image Program to double precision for deconvolution
Idouble = im2double(temp);
% Apply the PSF Program to the image Program to simulate stronger blur
blurred = imfilter(Idouble, PSF, 'conv', 'circular');
% Perform deconvolution using Wiener deconvolution with a stronger noise-Program
to-signal ratio
SNR = 0.01; % Adjust this value Program to control the deconvolution strength
deblurred = deconvwnr(blurred, PSF, SNR);
% Display the original and deblurred images side by side
figure;
% Original Image (Left)
subplot(1, 2, 1);
imshow(temp);
title('Original Image');
% Deblurred Image (Right)
subplot(1, 2, 2);
imshow(deblurred);
title('Blurred Image');
Screenshot:
CSL-502 21111 53
18.3 Program to implement first derivative image
k=imread("4.jpeg");
k=rgb2gray(k);
k1=double(k);
forward_msk=[1 -1 0];
kx=conv2(k1, forward_msk, 'same');
ky=conv2(k1, forward_msk', 'same');
ked=sqrt(kx.^2 + ky.^2);
%display the images.
imProgram tool(k,[]);
%display the edge detection along x-axis.
imProgram tool(kx,[]);
imProgram tool(abs(kx), []);
%display the edge detection along y-axis.
imProgram tool(ky,[]);
imProgram tool(abs(ky),[]);
%display the full edge detection.
imProgram tool(ked,[]);
CSL-502 21111 54
imProgram tool(abs(ked),[]);
Screenshot:
CSL-502 21111 55
% Adjust the threshold Program to binarize the image
threshold = 80; % You may need Program to adjust this threshold
binary_image = k2 > threshold;
% Create a new figure for displaying the images
figure;
% Display the original image
subplot(2, 2, 1);
imshow(k, []);
title('Original Image');
% Display the Laplacian-filtered image
subplot(2, 2, 2);
imshow(k2, []);
title('Laplacian Filtered Image');
% Display the binarized edges
subplot(2, 2, 3);
imshow(binary_image, []);
title('Binarized Edges');
% Apply morphological operations Program to improve segmentation
se = strel('disk', 1); % You can adjust the disk size
binary_image = imclose(binary_image, se);
binary_image = imfill(binary_image, 'holes');
% Display the processed binary image
subplot(2, 2, 4);
imshow(binary_image, []);
title('Processed Binary Image');
Screenshot:
CSL-502 21111 56
18.5 Program to implement image segmentation.
CSL-502 21111 57
segmented_image = zeros(m, n, p);
separation_width = 2; % Adjust this value Program to control the separation width
for i = 1:num_clusters
segment_mask = (idx == i);
separated_segment_mask = imdilate(segment_mask, strel('square',
separation_width)) & ~segment_mask;
segmented_image(:, :, 1) = segmented_image(:, :, 1) + separated_segment_mask *
255; % Set the separation color Program to white (255)
segmented_image(:, :, 2) = segmented_image(:, :, 2) + separated_segment_mask *
255;
segmented_image(:, :, 3) = segmented_image(:, :, 3) + separated_segment_mask *
255;
end
% Convert back Program to uint8 for display
segmented_image = uint8(segmented_image);
% Display the original and segmented images
figure;
subplot(1,2,1);
imshow(uint8(X));
title('Original Image');
subplot(1,2,2);
imshow(segmented_image);
title('Segmented Image with Separation');
Screenshot:
CSL-502 21111 58
CSL-502 21111 59
Experiment No -19
Aim: Perform Different Task in SCILAB on Image Segmentation.
Objectives:
Code:
subplot(121);
imshow(I);
subplot(122);
plot2d3(levels, qtd);
Screenshot -
CSL-502 21111 60
19.2 Plot the images with their respective histograms using subplot.
I1= imread('cameraman.tif');
I2 = imread('house.tif');
I3 = rgb2gray(imread('lena_color_256.tif'));
subplot(321);
imshow(I1);
subplot(322);
plot2d3(level1,qtd1);
subplot(323);
imshow(I2);
subplot(324);
plot2d3(level2,qtd2);
subplot(325);
imshow(I3);
subplot(326);
plot2d3(level3,qtd3);
Screenshot -
CSL-502 21111 61
Figure-19.2- Images with their respective histograms using subplot.
Iequal = imhistequal(I);
subplot(221);
imshow(I);
subplot(222);
plot2d3(level, qtd);
subplot(223);
CSL-502 21111 62
imshow(Iequal);
subplot(224);
plot2d3(levele, qtde);
Output:
I2 = imread('walkbridge.tif');
mask = [1,1,1;1,-8,1;1,1,1];
I1r = double(I1);
CSL-502 21111 63
I2rc = conv2(I2r, mask);
I2r = double(I2);
subplot(221);
imshow(I1);
subplot(222);
imshow(I2);
subplot(223);
imshow(I1rc);
subplot(224);
imshow(I2rc);
CSL-502 21111 64
19.5 Perform a task to Filtering for Line Detection.
I1 = imread('jetplane.tif');
I2 = imread('walkbridge.tif');
I1r = double(I1);
I2r = double(I2);
I1rc = conv2(mask_hor,I1r);
I2rc = conv2(mask_hor,I2r);
I1rc_hor = conv2(mask_hor,I1r);
I2rc_hor = conv2(mask_hor,I2r);
I1rc_45 = conv2(mask_45,I1r);
12rc_45 = conv2(mask_45,I2r);
I1rc_ver = conv2(mask_ver,I1r);
I2rc_ver = conv2(mask_ver,I2r);
I1rc_45neg = conv2(mask_45neg,I1r);
I2rc_45neg = conv2(mask_45neg,I2r);
subplot(521);
imshow(I1);
subplot(522);
imshow(I2);
CSL-502 21111 65
subplot(523);
imshow(I1rc_hor);
subplot(524);
imshow(I2rc_hor);
subplot(525);
imshow(I1rc_45);
subplot(526);
imshow(I2rc_45);
subplot(527);
imshow(I1rc_ver);
subplot(528);
imshow(I2rc_ver);
subplot(529);
imshow(I1rc_45neg);
subplot(5,2,10);
imshow(I2rc_45neg);
Output:
CSL-502 21111 66
Figure-19.5- Filtering for Line Detection of an image.
CSL-502 21111 67
Experiment No -20
Aim: Perform a Task of Feature Extraction on Image Data using VGG19 Model.
Objective:
Code:
import os
model = VGG19()
# summary
print(model.summary())
CSL-502 21111 68
Downloading data from https://storage.googleapis.com/tensorflow/keras-
applications/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels.h5
574710816/574710816 [==============================] - 7s 0us/step
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 224, 224, 3)] 0
CSL-502 21111 69
block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808
import scipy.fftpack
import numpy
import imagehash
features = {}
imageHash=[[]]
directory = '/content/image/'
image_path = directory+image
CSL-502 21111 70
# convert pixel to numpy array
img = img_to_array(img)
img = preprocess_input(img)
# extract features
# print(feature)
# print(type(feature))
hash_size=8
med = numpy.median(dctlowfreq)
print(diff)
# store feature
features[image_path] = feature
CSL-502 21111 71