0% found this document useful (0 votes)
22 views75 pages

Programming PDF

The document is a lab report detailing various experiments conducted using computational tools and techniques, specifically focusing on network simulation with ns2 and ns3, as well as image processing. It includes objectives, code snippets, and procedures for tasks such as implementing topologies, protocols, and image analysis. The report is submitted by a BTech-CSE student and is structured with an index and multiple experiments outlined in a systematic manner.

Uploaded by

ayan.yescity
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)
22 views75 pages

Programming PDF

The document is a lab report detailing various experiments conducted using computational tools and techniques, specifically focusing on network simulation with ns2 and ns3, as well as image processing. It includes objectives, code snippets, and procedures for tasks such as implementing topologies, protocols, and image analysis. The report is submitted by a BTech-CSE student and is structured with an index and multiple experiments outlined in a systematic manner.

Uploaded by

ayan.yescity
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/ 75

AY 2023-24

LAB REPORT ON
COMPUTATIONAL TOOLS AND TECHNIQUES

Submitted By
Ayush Mishra 21111
V SEMESTER BTECH-CSE

Submitting to Dr. Shivdutt Sharma

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

13 To perform various operations on Iris Dataset


 Plot a scatter plot on Iris Dataset.
 Plot a scatter plot on Tips Dataset
 Plot a Bar plot on Tips Dataset
 Write a program to perform singular value
decomposition on iris dataset

14 Write program for image analysis and distance


visualisation
 Implementing the Program to calculate
Average of distance of images (Phash)
 Implementing the Program to calculate
Average of distance of images (Whash)
 Plot the Histogram of Average Distance
 Plot the Histogram with Gaussian Distribution

15 Python Programming and Exploring Image


Processing Techniques and Principal Component
Analysis (PCA) for Data Visualization.
 Program to compute the average of numbers in
the list.
 Program to read an image from the file and
output it
 Program to create a two-dimensional array.
 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

16 Program to implement Principal Component Analysis


for Visualization
17 To implement Hash Code and Image Hash Library
18 Using MATLAB perform various image filtering
 Program to implement Image Filtering
 Program to implement image blur operation.
 Program to implement first derivative image.
 Program to implement second derivative of
image.
 Program to implement image segmentation
19 Perform Different Task in SCILAB on Image
Segmentation
 Show the histogram of one of image.
 Plot the images with their respective
histograms using subplot.
 Perform equalization on cameraman. If image.
 Perform a task to Filtering for Edge Detection.
 Perform a task to Filtering for Line Detection.
20 Perform a Task of Feature Extraction on Image Data
using VGG19 Model.
Experiment 1
Aim: Installation of ns2

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:

Save the following NS2 script in a file named "ex2.tcl":

# Set the simulator

set ns [new Simulator]

# Opening the network animation

set namf [open wired2.nam w]

$ns namtrace-all $namf

# Open the file for tracing

CSL-502 21111 1
set tracef [open wired2.tr w]

$ns trace-all $tracef

# Creation of wired nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

# Establish the links between the nodes with bandwidth and delay

$ns duplex-link $n0 $n1 2MB 1ms DropTail

$ns duplex-link $n1 $n2 2.5MB 1ms RED

$ns duplex-link $n2 $n3 2MB 1.5ms DropTail

$ns duplex-link $n3 $n1 12MB 10ms DropTail

# Creating the Tcp source and sink agents

set tcp [new Agent/TCP]

set sink [new Agent/TCPSink]

# Attach the agents to the corresponding nodes

$ns attach-agent $n0 $tcp

$ns attach-agent $n2 $sin

# Create the FTP Traffic

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns connect $tcp $sink

# Start the traffic

CSL-502 21111 2
$ns at 1.0 "$ftp start"

# End the simulation

$ns at 3.0 "finish"

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

Aim: To create various events at different time intervals in ns2

Objective: The objective of this experiment is to create and schedule various events at different time
intervals using ns2's scripting capabilities.

Code:

Set ns [new Simulator];

Puts ”line1”;

$ns at 1.0 {puts “Event 1: Now= [$ns now]”};

$ns at 5.0 {puts “Event 1: Now= [$ns now]”};

$ns at 3.0 {puts “Event 1: Now= [$ns now]”};

Puts “Line 2”;

Puts “Notice line 1 &2 precedes all events!!”

$ns run;

Puts “notice that event 3 precedes event 2!!”

CSL-502 21111 6
Experiment 4

Aim: Implementation of Star Topology in ns2

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:

set ns [new Simulator]


set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam
exit 0
}
#creating Nodes
for {set i 0} {$i<7} {incr i} {
set n($i) [$ns node]
}
#Creating Links
for {set i 1} {$i<7} {incr i} {
$ns duplex-link $n(0) $n($i) 512Kb 10ms SFQ
}
#Orienting The nodes
$ns duplex-link-op $n(0) $n(1) orient left-up
$ns duplex-link-op $n(0) $n(2) orient right-up
$ns duplex-link-op $n(0) $n(3) orient right
$ns duplex-link-op $n(0) $n(4) orient right-down
$ns duplex-link-op $n(0) $n(5) orient left-down

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

Aim: Implementation of Ring Topology in ns2.

Code:

set ns [new Simulator]


set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam
exit 0
}
#creating Nodes
for {set i 0} {$i<8} {incr i} {
set n($i) [$ns node]
}
#Creating Links
for {set i 0} {$i<8} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%8]) 512Kb 10ms SFQ
}
#Orienting The nodes
$ns duplex-link-op $n(0) $n(1) orient right
$ns duplex-link-op $n(1) $n(2) orient right-down
$ns duplex-link-op $n(2) $n(3) orient down
$ns duplex-link-op $n(3) $n(4) orient left-down
$ns duplex-link-op $n(4) $n(5) orient left
$ns duplex-link-op $n(5) $n(6) orient left-up
$ns duplex-link-op $n(6) $n(7) orient up

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

Aim: Implementation of TCP protocol in ns2

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:

#——-Event scheduler object creation——–#


set ns [new Simulator]
#———-creating trace objects—————-#
set nt [open test2.tr w]
$ns trace-all $nt
#———-creating nam objects—————-#
set nf [open test2.nam w]
$ns namtrace-all $nf
#———-Setting color ID—————-#
$ns color 1 darkmagenta
$ns color 2 yellow
$ns color 3 blue
$ns color 4 green
$ns color 5 black
#———- Creating Network—————-#
set totalNodes 3
for {set i 0} {$i < $totalNodes} {incr i} {
set node_($i) [$ns node]
}
set server 0
set router 1
set client 2
#———- Creating Duplex Link—————-#

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

Aim: Implementation of UDP protocol in ns2.

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:

set ns [new Simulator]

$ns color 1 blue

$ns color 2 red

$ns rtproto DV

set nf [open out.nam w]

$ns namtrace-all $nf

proc finish {} {

global ns nf

$ns flush-trace

close $nf

exec nam out.nam

exit 0

for {set i 0} {$i<5} {incr i} {

set n($i) [$ns node]

CSL-502 21111 14
}

for {set i 1} {$i<5} {incr i} {

$ns duplex-link $n(0) $n($i) 512Kb 10ms SFQ

$ns duplex-link-op $n(0) $n(1) orient left-up

$ns duplex-link-op $n(0) $n(2) orient right-up

$ns duplex-link-op $n(0) $n(3) orient right

$ns duplex-link-op $n(0) $n(4) orient right-down

set udp0 [new Agent/UDP]

$udp0 set class_ 2

$ns attach-agent $n(2) $udp0

set null0 [new Agent/Null]

$ns attach-agent $n(5) $null0

$ns connect $udp0 $null0

$ns at 2.0 "finish"

$ns run

CSL-502 21111 15
Experiment 8

Aim: Implementation of Routing protocol in ns2.

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:

set ns [new Simulator]

$ns rtproto LS

set node1 [$ns node]

set node2 [$ns node]

set node3 [$ns node]

set node4 [$ns node]

set node5 [$ns node]

set node6 [$ns node]

set node7 [$ns node]

set [open out.tr w]

CSL-502 21111 16
$ns trace-all $

set nf [open out.nam w]

$ns namtrace-all $nf

$node1 label "node 1"

$node2 label "node 2"

$node3 label "node 3"

$node4 label "node 4"

$node5 label "node 5"

$node6 label "node 6"

$node7 label "node 7"

$node1 label-color blue

$node2 label-color red

$node3 label-color red

$node4 label-color blue

$node5 label-color blue

$node6 label-color blue

$node7 label-color blue

$ns duplex-link $node1 $node2 1.5Mb 10ms DropTail

$ns duplex-link $node2 $node3 1.5Mb 10ms DropTail

$ns duplex-link $node3 $node4 1.5Mb 10ms DropTail

$ns duplex-link $node4 $node5 1.5Mb 10ms DropTail

$ns duplex-link $node5 $node6 1.5Mb 10ms DropTail

$ns duplex-link $node6 $node7 1.5Mb 10ms DropTail

CSL-502 21111 17
$ns duplex-link $node7 $node1 1.5Mb 10ms DropTail

$ns duplex-link-op $node1 $node2 orient le -down

$ns duplex-link-op $node2 $node3 orient le -down

$ns duplex-link-op $node3 $node4 orient right-down

$ns duplex-link-op $node4 $node5 orient right

$ns duplex-link-op $node5 $node6 orient right-up

$ns duplex-link-op $node6 $node7 orient le -up

$ns duplex-link-op $node7 $node1 orient le -up

set tcp2 [new Agent/TCP]

$ns a ach-agent $node1 $tcp2

set sink2 [new Agent/TCPSink]

$ns a ach-agent $node4 $sink2

$ns connect $tcp2 $sink2

set traffic_ p2 [new Applica on/FTP]

$traffic_ p2 a ach-agent $tcp2

$traffic_ p2 set type_ FTP

$ns at 1.0 "$traffic_ p2 start"

proc finish {} {

global ns nf

$ns flush-trace

close $nf

exec nam out.nam &

exit 0

CSL-502 21111 18
}

$ns at 5.0 "finish"

$ns run

Experiment 9

Aim: Installation of ns3.

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:

 sudo apt update


 sudo apt install g++ python3 python3-dev pkg-config sqlite3 cmake python3-setuptools git
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools gir1.2-goocanvas-2.0 python3-gi
python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython3 openmpi-bin openmpi-common
openmpi-doc libopenmpi-dev autoconf cvs bzr unrar gsl-bin libgsl-dev libgslcblas0 wireshark
tcpdump sqlite sqlite3 libsqlite3-dev libxml2 libxml2-dev libc6-dev libc6-dev-i386 libclang-
dev llvm-dev automake python3-pip libxml2 libxml2-dev libboost-all-dev
ii. Step 2: Download ns-allinone

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).

iii. Step 3: Extract ns-allinone

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:

tar jxvf ns-allinone-3.36.1.tar.bz2 -C ~/

iv. Step 4: Build ns3

Open a terminal and navigate to the extracted ns-allinone directory:

cd ~/ns-allinone-3.36.1/

Now, run the build.py script with the necessary options to enable examples and tests:

./build.py --enable-examples --enable-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

Aim: Implementation of Dijkstra’s Algorithm in ns3.

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

Aim: Creation of nodes in ns3

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:

 Create a program to add customizable Gaussian noise to images.


 Develop a tool to extract and process images from zip archives.
 Apply Gaussian blur to single images with user-defined parameters.
 Ensure compatibility with common image formats and handle errors.
 Allow users to fine-tune noise and blur settings.
 Conduct experiments and report on the impact of image processing operations.

Code:

1. Program to add Gaussian Noise in the image

import cv2

import numpy as np

from PIL import Image, ImageFilter

from numpy import sqrt

img = cv2.imread(’filename’)

for fil in [0.01,0.02,0.03,0.04,0.05,0.1,0.15,0.2,0.25]:

mean = 0

var=fil # var means variance

stddev = sqrt(var)

noise = np.zeros(img.shape, np.uint8)

cv2.randn(noise, mean, stddev)

noisy_img = cv2.add(img, noise)

cv2.imwrite(’G-Noise’+str(fil)+’.jpg’, noisy_img)

CSL-502 21111 26
Screenshot:

2. Program to read images from the zip file

import zipfile

from PIL import Image

imgzip = zipfile.ZipFile("100-Test.zip")

inflist = imgzip.infolist()

for f in inflist:

ifile = imgzip.open(f)

img = Image.open(ifile)

print(img)

3. Program to apply Gaussian Blur on the single image

from PIL import Image, ImageFilter

im=Image.open(’1.jpg’)

im=im.filter(ImageFilter.GaussianBlur(30))

CSL-502 21111 27
im.show()

Screenshot:

4. To apply operations on images using PIL library

from PIL import Image, ImageFilter

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

Aim: To perform various operations on Iris Dataset

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:

1. Plot a scatter plot on Iris Dataset.

import pandas as pd

import matplotlib.pyplot as plt

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

import matplotlib.pyplot as plt

import seaborn as sns

data = sns.load_dataset("tips")

plt.scatter(data['day'], data['tip'], c=data['size'],s=data['total_bill'])

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

import matplotlib.pyplot as plt

import seaborn as sns

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

from sklearn import datasets

from sklearn.decomposition import TruncatedSVD

iris = datasets.load_iris()

X = iris.data

U, S, VT = np.linalg.svd(X)

print("Original Matrix (X):")

print(X)

k=2

X_reduced = U[:, :k] @ np.diag(S)[:k, :k] @ VT[:k, :]

print(f"\nReduced Matrix (k={k}):")

print(X_reduced)

Screenshot:

CSL-502 21111 33
Original Matrix Reduced matrix

CSL-502 21111 34
Lab Experiment No. 14

Aim: Write program for image analysis and distance visualization.

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:

1. Implementing the Program to calculate Average of distance of images(Phash)

import numpy as np

from PIL import Image

!pip install imagehash

import imagehash

from imagehash import phash,whash

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=[]

for img1 in glob.glob("/content/drive/MyDrive/test/*.jpg"):

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)

print("Average of distance of images:", sum(avg)/len(avg))

Screenshot:

2. Implementing the Progran to calculate Average of distance of images(Whash)

l=[]

i=0;

for img1 in glob.glob("/content/drive/MyDrive/test/*.jpg"):

CSL-502 21111 36
img1 = cv2.imread(img1)

img1 = Image.fromarray(img1)

l.append(whash(img1))

l2=[]

for img1 in glob.glob("/content/drive/MyDrive/test/*.jpg"):

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)

print("Average of distance of images:", sum(avg)/len(avg))

Screenshot:

3. Plot the Histogram of Average Distance

import matplotlib.pyplot as plt

plt.hist(avg, bins=20, color='blue', alpha=0.7)

plt.xlabel('Average Distance')

plt.ylabel('Frequency')

CSL-502 21111 37
plt.title('Histogram of Average Distances')

plt.show()

Screenshot:

4. Plot the Histogram with Gaussian Distribution

plt.figure(figsize=(8, 6))

plt.hist(avg, bins=40, range=(0, 1.0), alpha=0.5, color='blue', label='Average Hash Differences')

mu = np.mean(avg)

sigma = np.std(avg)

print("Avrage of:",mu)

x = np.linspace(0, 1.0, 100)

pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))

CSL-502 21111 38
pdf = pdf * (len(avg) / 31.5)

# Plot the Gaussian curve

plt.plot(x, pdf, 'r', linewidth=2, label='Gaussian Curve')

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:

 Introduce us to essential Python programming concepts.


 Focus on list operations, file handling, image processing, and array manipulation.
 How to compute averages and perform basic operations on image files.
 Familiarize us with working with images and applying filters.
 Provide practical experience in handling zip archives.

Code:

1. Program to compute the average of numbers in the list.

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:

2. Program to read an image from the file and output it

import cv2

from matplotlib import pyplot as plt

# Read the image

img = cv2.imread('/content/OIP.jpeg')
CSL-502 21111 40
# Convert BGR to RGB

img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Display the image

plt.imshow(img_rgb)

plt.axis('off')

plt.show()

Output Screenshot:

3. Program to create a two-dimensional array

import numpy as np

arr=np.array([[1,2,3],[4,5,6],[7,8,9]])

print(arr.ndim)

print(arr.shape)

Output Screenshot:

4. Program to add Gaussian Noise in the image

import cv2

import numpy as np

CSL-502 21111 41
from PIL import Image

from numpy import sqrt

from IPython.display import display, Image as IPImage

# Read the image

img = cv2.imread('/content/OIP.jpeg')

# Create a folder to store the noisy images

!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

var = fil # var means variance

stddev = sqrt(var)

noise = np.zeros(img.shape, np.uint8)

cv2.randn(noise, mean, stddev)

noisy_img = cv2.add(img, noise)

# Save the noisy image

cv2.imwrite(f'noisy_images/G-Noise{str(fil)}.jpg', noisy_img)

# Display only the final noisy image

display(IPImage(f'noisy_images/G-Noise0.25.jpg'))

Output Screenshot:

Original Noise Image

CSL-502 21111 42
5. Program to read images from the zip file

import zipfile

from PIL import Image

imgzip = zipfile.ZipFile("100-Test.zip")

inflist = imgzip.infolist()

for f in inflist:

ifile = imgzip.open(f)

img = Image.open(ifile)

print(img)

6. Program to apply Gaussian Blur on the single image

from PIL import Image, ImageFilter


CSL-502 21111 43
im=Image.open(’1.jpg’)

im=im.filter(ImageFilter.GaussianBlur(10))

im.show()

CSL-502 21111 44
Lab Experiment No. 16

Aim: Program to implement Principal Component Analysis for Visualization

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:

# Import necessary libraries

from sklearn.datasets import load_wine

import matplotlib.pyplot as plt

from sklearn.decomposi on import PCA

# Load the wine dataset

wdata = load_wine()

X, y = wdata['data'], wdata['target']

# Print the shape of X and y to verify the dimensions

print(X.shape)

print(y.shape)

# Visualize the original data

plt.sca er(X[:, 1], X[:, 2], c=y)

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)

# Visualize the transformed data

plt.sca er(Xt[:, 0], Xt[:, 1], c=y)

plt.xlabel('Principal Component 1')

plt.ylabel('Principal Component 2')

plt. tle('PCA Transformed Data')

plt.show()

sca er = plt.sca er(Xt[:, 0], Xt[:, 1], c=y)

legend1 = plt.legend(*sca er.legend_elements(), tle="Classes")

plt.gca().add_ar st(legend1)

# Add legend for target names

handles = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='C0', markersize=10,


label=wdata['target_names'][i]) for i in range(len(wdata['target_names']))]

plt.legend(handles=handles, tle="Target Names")

plt.xlabel('Principal Component 1')

plt.ylabel('Principal Component 2')

plt. tle('PCA Transformed Data with Legend')

plt.show()

Screenshot:

CSL-502 21111 46
CSL-502 21111 47
CSL-502 21111 48
Lab Experiment No. 17

Aim: To implement Hash Code and Image Hash Library

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

from PIL import Image

import imagehash

from imagehash import phash, whash

import cv2

import glob

import os

l=[]

for img1 in glob.glob("/content/ping/*.jpg"):

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

Aim: Using MATLAB perform various image filtering

Objectives:

 Recognize various image filters and their specific applications.


 Familiarize with essential MATLAB functions for image processing.
 Apply basic filters like averaging and Gaussian in MATLAB for enhancement and noise
reduction.
 Create custom filter kernels for specific image processing tasks.
 Master image derivatives and edge detection techniques using Sobel and Prewitt operators in
MATLAB.
 Understand image compression concepts and automate the compression of image files.
 Learn image segmentation methods for tasks such as object recognition and medical image
analysis, optimizing parameters for desired results.

Code:

18.1 Program to implement Image Filtering

% Read the image


i = imread('im1.jpeg');
% Split the image inProgram to its Red, Green, and Blue channels
Red = i(:,:,1);
Green = i(:,:,2);
Blue = i(:,:,3);
% Define a filter kernel for sharpening
filter_kernel = [0, -1, 0; -1, 5, -1; 0, -1, 0];
% Apply the filter Program to the Red channel
filtered_red = imfilter(Red, filter_kernel, 'conv', 'replicate');
% Create a copy of the original image
temp = i;

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:

18.2 Program to implement image blur operation

% Read the image


temp = imread('im1.jpeg');
% Create a point spread function (PSF) for motion blur with stronger blur
PSF = fspecial('motion', 80, 15);

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:

18.4 Program to implement second derivative of image

% Read the input image


k = imread("5.jpeg");
k = rgb2gray(k);
% Convert the image Program to double precision
k1 = double(k);
% Define the Laplacian kernel for the second derivative
laplacian_kernel = [0 -1 0; -1 4 -1; 0 -1 0];
% Apply the Laplacian filter Program to the image
k2 = conv2(k1, laplacian_kernel, 'same');
% Compute the absolute value of the Laplacian response
k2 = abs(k2);

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.

% Load the image


X = imread('3.jpeg');
% Convert the image Program to double for processing
X = double(X);
% Reshape the image inProgram to a 2D array (height*width) x 3 (RGB channels)
[m, n, p] = size(X);
X_reshaped = reshape(X, m * n, p);
% Define the number of clusters (segments)
num_clusters = 2;
% Perform K-means clustering
[idx, centroids] = kmeans(X_reshaped, num_clusters);
% Reshape the index array back Program to the original image size
idx = reshape(idx, m, n);
% Create segmented image with separation

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:

19.1 Show the histogram of one of image.


I = imread('C:\Users\IIITU\Pictures\Histograms\cameraman.tif');

[qtd, levels] = imhist(I);

subplot(121);

imshow(I);

subplot(122);

plot2d3(levels, qtd);

Screenshot -

Figure-19.1- Histogram of an image in SCILAB.

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'));

[qtd1, level1] = imhist(I1);

[qtd2, level2] = imhist(I2);

[qtd3, level3] = imhist(I3);

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.

19.3 Perform equalization on cameraman. If image.


I = imread('cameraman.tif');

Iequal = imhistequal(I);

[qtd, level] = imhist(I);

[qtde, levele] = imhist(Iequal);

subplot(221);

imshow(I);

subplot(222);

plot2d3(level, qtd);

subplot(223);

CSL-502 21111 62
imshow(Iequal);

subplot(224);

plot2d3(levele, qtde);

Output:

Figure-19.3- Equalization on an image.

19.4 Perform a task to Filtering for Edge Detection.


I1 = imread('jetplane.tif');

I2 = imread('walkbridge.tif');

mask = [1,1,1;1,-8,1;1,1,1];

I1r = double(I1);

I1rc = conv2(I1r, mask);

CSL-502 21111 63
I2rc = conv2(I2r, mask);

Undefined variable: I2r

I2r = double(I2);

I2rc = conv2(I2r, mask);

subplot(221);

imshow(I1);

subplot(222);

imshow(I2);

subplot(223);

imshow(I1rc);

subplot(224);

imshow(I2rc);

Figure-19.4- Filtering for Edge Detection of an image.

CSL-502 21111 64
19.5 Perform a task to Filtering for Line Detection.
I1 = imread('jetplane.tif');

I2 = imread('walkbridge.tif');

mask_hor = [-1 -1 -1; 2 2 2; -1 -1 -1];

mask_45 = [2 -1 -1; -1 2 -1; -1 -1 2];

mask_ver = [-1 2 -1; -1 2 -1; -1 2 -1];

mask_45neg = [-1 -1 2; -1 2 -1; 2 -1 -1];

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

from tensorflow.keras.applications.vgg19 import VGG19, preprocess_input

from tensorflow.keras.preprocessing.image import load_img, img_to_array

from tensorflow.keras.models import Model

# load the model

model = VGG19()

# restructure the model

model = Model(inputs=model.inputs, outputs=model.layers[-2].output)

# 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

block1_conv1 (Conv2D) (None, 224, 224, 64) 1792

block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

block1_pool (MaxPooling2D) (None, 112, 112, 64) 0

block2_conv1 (Conv2D) (None, 112, 112, 128) 73856

block2_conv2 (Conv2D) (None, 112, 112, 128) 147584

block2_pool (MaxPooling2D) (None, 56, 56, 128) 0

block3_conv1 (Conv2D) (None, 56, 56, 256) 295168

block3_conv2 (Conv2D) (None, 56, 56, 256) 590080

block3_conv3 (Conv2D) (None, 56, 56, 256) 590080

block3_conv4 (Conv2D) (None, 56, 56, 256) 590080

block3_pool (MaxPooling2D) (None, 28, 28, 256) 0

block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160

block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808

block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808

block4_conv4 (Conv2D) (None, 28, 28, 512) 2359808

block4_pool (MaxPooling2D) (None, 14, 14, 512) 0

CSL-502 21111 69
block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808

block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808

block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808

block5_conv4 (Conv2D) (None, 14, 14, 512) 2359808

block5_pool (MaxPooling2D) (None, 7, 7, 512) 0

flatten (Flatten) (None, 25088) 0

fc1 (Dense) (None, 4096) 102764544

Figure 19.1: VGG19 Model Summary

import scipy.fftpack

import numpy

from PIL import Image

import imagehash

from imagehash import phash,whash

features = {}

imageHash=[[]]

directory = '/content/image/'

for image in os.listdir(directory):

image_path = directory+image

# load the image

img = load_img(image_path, target_size=(224, 224))

CSL-502 21111 70
# convert pixel to numpy array

img = img_to_array(img)

# reshape the image for the model

img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2]))

# preprocess the image

img = preprocess_input(img)

# extract features

feature = model.predict(img, verbose=0)

# print(feature)

# print(type(feature))

hash_size=8

dct = scipy.fftpack.dct(scipy.fftpack.dct(feature, axis=0), axis=1)

dctlowfreq = dct[:hash_size, :hash_size]

med = numpy.median(dctlowfreq)

diff = dctlowfreq > med

print(diff)

# store feature

features[image_path] = feature

Figure 19.2: Fast Fourier Transformation on each image row.

CSL-502 21111 71

You might also like