AICV Lab Manual
AICV Lab Manual
LAB MANUAL
Artificial Intelligence
and Computer Vision
Lab 21AM505
Academic Year
2023-2024
ARTIFICIAL INTELLIGENCE AND COMPUTER VISION LAB
(Effective from the academic year 2023 -2024)
SEMESTER – V
Course Code 21AM505 CIE Marks 50
Number of Contact Hours/Week 0:0:2 SEE Marks 50
Total Number of Contact Hours 26 Exam Hours 03
Credits – 1
PART-A
1. Implement and Demonstrate Depth First Search Algorithm on Water Jug Problem
2. Implement and Demonstrate Best First Search Algorithm on any AI problem
3. Implement AO* Search algorithm.
4. Solve 8-Queens Problem with suitable assumptions
5. Implementation of TSP using heuristic approach
6. Implementation of the problem-solving strategies: either using Forward Chaining or Backward
Chaining
7. Implement K- means algorithm.
8. Implement K- nearest neighbour algorithm
9. Implement SVM
PART-B
1. Write a program in python to demonstrate working with images and videos using OpenCV.
2. Write a program in python to demonstrate Bitwise Operations on Binary Images using OpenCV.
3. Write a program in python to Draw different geometric shapes and to write text on images using
OpenCV.
5. Implement different Thresholding techniques, Edge detection and Contour detection on images using
openCV.
6. Demonstrate Haar feature-based cascade classifiers for Face and Eye Detection on images.
7. Develop a classification model using YOLO object detection algorithm using OpenCV.
Program:
def water_jug_dfs(jug1_capacity, jug2_capacity, target_capacity):
def dfs(jug1, jug2, path):
if jug1 == target_capacity or jug2 == target_capacity:
print("Solution found:", path)
return
# Fill jug1
if jug1 < jug1_capacity:
new_jug1 = jug1_capacity
new_jug2 = jug2
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path + f"Fill Jug1\n")
# Fill jug2
if jug2 < jug2_capacity:
new_jug1 = jug1
new_jug2 = jug2_capacity
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path + f"Fill Jug2\n")
# Empty jug1
if jug1 > 0:
new_jug1 = 0
new_jug2 = jug2
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path + f"Empty Jug1\n")
# Empty jug2
if jug2 > 0:
new_jug1 = jug1
new_jug2 = 0
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path + f"Empty Jug2\n")
visited = set()
dfs(0, 0, "")
# Example usage
jug1_capacity = 4
jug2_capacity = 3
target_capacity = 2
Output:
Program:
for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()
source = 0
target = 9
best_first_search(source, target, v)
Output:
0 1 3 2 8 9
3. Implement AO* Search algorithm.
Program:
class Graph:
def __init__(self, graph, heuristicNodeList, startNode):
#instantiate graph object with graph topology, heuristic values,
start node
self.graph = graph
self.H=heuristicNodeList
self.start=startNode
self.parent={}
self.status={}
self.solutionGraph={}
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE
START NODE:",self.start)
print("------------------------------------------------------------
")
print(self.solutionGraph)
print("------------------------------------------------------------
")
print("------------------------------------------------------------
-----------------------------")
if self.getStatus(v) >= 0: # if status node v >= 0, compute
Minimum Cost nodes of v
minimumCost, childNodeList =
self.computeMinimumCostChildNodes(v)
print(minimumCost, childNodeList)
self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v,len(childNodeList))
solved=True # check the Minimum Cost nodes of v are
solved
for childNode in childNodeList:
self.parent[childNode]=v
if self.getStatus(childNode)!=-1:
solved=solved & False
if solved==True: # if the Minimum Cost nodes of v are
solved, set the current node status as solved(-1)
self.setStatus(v,-1)
self.solutionGraph[v]=childNodeList # update the
solution graph with the solved nodes which may be a part of
solution
if v!=self.start: # check the current node is the start
node for backtracking the current node value
self.aoStar(self.parent[v], True) # backtracking
the current node value with backtracking status set to true
if backTracking==False: # check the current call is not
for backtracking
for childNode in childNodeList: # for each Minimum
Cost child node
self.setStatus(childNode,0) # set the status of
child node to 0(needs exploration)
self.aoStar(childNode, False) # Minimum Cost
child node is further explored with backtracking status as false
Output:
PROCESSING NODE : I
--------------------------------------------------------------------
---------------------
0 []
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F':
1, 'G': 8, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': []}
PROCESSING NODE : G
--------------------------------------------------------------------
---------------------
1 ['I']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F':
1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I']}
PROCESSING NODE : B
--------------------------------------------------------------------
---------------------
2 ['G']
HEURISTIC VALUES : {'A': 12, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F':
1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : A
--------------------------------------------------------------------
---------------------
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1,
'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : C
--------------------------------------------------------------------
---------------------
2 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1,
'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : A
--------------------------------------------------------------------
---------------------
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1,
'G': 1, 'H': 7, 'I': 0, 'J': 1}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G']}
PROCESSING NODE : J
--------------------------------------------------------------------
---------------------
0 []
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1,
'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': []}
PROCESSING NODE : C
--------------------------------------------------------------------
---------------------
1 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 1, 'D': 12, 'E': 2, 'F': 1,
'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C':
['J']}
PROCESSING NODE : A
--------------------------------------------------------------------
---------------------
5 ['B', 'C']
FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A
------------------------------------------------------------
{'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J'], 'A': ['B',
'C']}
4. Solve 8-Queens Problem with suitable assumptions
Program:
# Taking number of queens as input from user
print ("Enter the number of queens")
N = int(input())
# here we create a chessboard
# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
Output:
Program:
import math
# Define a function to calculate the Euclidean distance between
two points
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] -
point2[1])**2)
while unvisited:
current_point = tour[-1]
nearest_point = min(unvisited, key=lambda x:
distance(points[current_point], points[x]))
tour.append(nearest_point)
unvisited.remove(nearest_point)
return tour
# Example usage
if __name__ == "__main__":
# Define the points as (x, y) coordinates
points = [(0, 0), (1, 2), (2, 3), (3, 4),(4,2)]
Output:
class KnowledgeBase:
def __init__(self):
self.facts = set()
self.rules = []
def apply_forward_chaining(self):
new_facts_derived = True
while new_facts_derived:
new_facts_derived = False
for rule in self.rules:
if all(antecedent in self.facts for antecedent in
rule.antecedents) and rule.consequent not in self.facts:
self.facts.add(rule.consequent)
new_facts_derived = True
if __name__ == "__main__":
kb = KnowledgeBase()
Output:
Derieved Facts: {'A', 'C', 'D', 'E', 'G'}
Backward Chaining Program:
Output:
The Goal'C' cannot be Reached
7. Implement K- means algorithm.
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Generate some sample data for clustering
np.random.seed(0)
X = np.random.rand(100, 2)
Output:
Accuracy: 85.00%
9. Implement SVM
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
Output:
Accuracy: 90.00%
PART B
def process_video(video_path):
#open a video capture object
Cap=cv2.VideoCapture(video_path)
while cap.isOpened():
ret,frame=cap.read()
frame=cv2.resize(frame,(960,540))
#Display the video frame
cv2.imshow(“Vi the video capturedeo”,frame)
#Press ‘q’ to exit the video playback
if cv2.waitKey(250) & 0xFF==ord(‘q’):
Break
#Release the video capture object and close all the
windows
cap.release()
cv2.destroyAllwindows()
#Choose whether to process an image or video
if choice.lower()==’I’:
#Load an image
image=cv2.imread(‘image.jpg’)
process_image(image)
elif choice.lower()==’v’:
#Load a video
video_path=’video.mp4’
process_video(video_path)
else:
print(“invalid choice. Please enter ‘I’ or ‘V’)
Output:
2. Write a program in python to demonstrate Bitwise Operations on
Binary Images using OpenCV.
Program:
import cv2
import numpy as np
Output:
3. Write a program in python to Draw different geometric shapes
and to write text on images using OpenCV.
import numpy
as np import
cv2
# Using cv2.putText()
method font =
cv2.FONT_HERSHEY_SIMPLEX
org = (50, 400)
fontScale = 2
color = (0, 0, 255)
thickness = 3
Img = cv2.putText(Img, 'OpenCV', org, font,fontScale, color,
thickness,cv2.LINE_AA, False)
Img = cv2.putText(Img, 'OpenCV', org, font,fontScale, color,
thickness,cv2.LINE_AA, True)
# Displaying the image
cv2.imshow('Geometric_shapes', Img)
cv2.waitKey(0)
cv2.destroyAllWindows(
)
Output:
img = cv.imread(morph.jpg)
# Creating kernel
kernel =np.ones((5, 5), np.uint8)
cv2.waitKey(0)
cv2.destroyAllWindo
ws()
5. Implement different Thresholding techniques, Edge detection and
Contour detection on images using openCV.
import cv2
image = cv2.imread('tiger.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
contours,_=cv2.findContours(edged,cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
# draw the contours on a copy of the original image
cv2.drawContours(image_copy, contours, -1, (0, 255, 0), 2)
print(len(contours), "objects were found in this image.")
Output:
7. Develop a classification model using YOLO object detection
algorithm using OpenCV.
Program:
import cv2
import numpy as
np # Load Yolo
print("LOADING YOLO")
net = cv2.dnn.readNet("yolov3.weights",
"yolov3.cfg") #save all the names in file o
the list classes classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in
f.readlines()] #get layers of the network
layer_names = net.getLayerNames()
#Determine the output layer names from the YOLO model
output_layers = [layer_names[i - 1] for i in
net.getUnconnectedOutLayers()] print("YOLO LOADED")
# Capture frame-by-frame
img = cv2.imread("test_img.jpg")
#img = cv2.resize(img, None, fx=0.4,
fy=0.4) height, width, channels =
img.shape
# USing blob function of opencv to preprocess image
blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416,
416),swapRB=True, crop=False)
#Detecting
objects
net.setInput(bl
ob)
outs = net.forward(output_layers)
# Showing informations on the
screen class_ids = []
confidences =
[] boxes = []
for out in outs:
for detection in out:
scores =
detection[5:]
class_id =
np.argmax(scores)
confidence =
scores[class_id] if
confidence > 0.5:
# Object detected
center_x = int(detection[0] *
width) center_y =
int(detection[1] * height) w =
int(detection[2] * width)
h = int(detection[3] *
height) # Rectangle
coordinates
x = int(center_x - w
/ 2) y = int(center_y
- h / 2)
boxes.append([x, y,
w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
#We use NMS function in opencv to perform Non-maximum
Suppression #we give it score threshold and nms
threshold as arguments. indexes =
cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
colors = np.random.uniform(0, 255,
size=(len(classes), 3)) for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y -
5),cv2.FONT_HERSHEY_SIMPLEX,1/2, color, 2)
cv2.imshow("Image",img) cv2.waitKey(0)
Output:
8. Write a program in python to demonstrate Handwritten Digit
Recognition on MNIST dataset.
Program:
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
# Display the first few test images and their predicted labels
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(test_images[i], cmap=plt.cm.binary)
predicted_label = predictions[i].argmax()
true_label = test_labels[i].argmax()
color = 'blue' if predicted_label == true_label else 'red'
plt.xlabel(f'Predicted: {predicted_label} True: {true_label}',
color=color)
plt.show()
Output: