Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

Python Programming MANUAL-NEW

The document is a laboratory manual for the Python Programming course at Muthayammal Engineering College, detailing the institution's vision, mission, and educational objectives. It includes a list of experiments for students to complete, such as computing GCD, finding square roots, and implementing sorting algorithms. Additionally, it outlines safety protocols and best practices for laboratory conduct.

Uploaded by

kosikan2810
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)
54 views

Python Programming MANUAL-NEW

The document is a laboratory manual for the Python Programming course at Muthayammal Engineering College, detailing the institution's vision, mission, and educational objectives. It includes a list of experiments for students to complete, such as computing GCD, finding square roots, and implementing sorting algorithms. Additionally, it outlines safety protocols and best practices for laboratory conduct.

Uploaded by

kosikan2810
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/ 31

MUTHAYAMMAL ENGINEERING COLLEGE

(An Autonomous Institution)

(Approved by AICTE, New Delhi, Accredited by

NAAC & Affiliated to Anna University)

Rasipuram-637408, Namakkal Dist., TamilNadu

23GES05 / PYTHON PROGRAMMING LABORATORY

LAB MANUAL

FOR

I YEAR / II SEM B.E. / B.Tech

Prepared By, Approved By,


Mrs J.Juliet Brownie Dr.G.Kavitha
AP / CSE Professor & Head / CSE
MEC MEC

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 1


Institution Vision and Mission

Vision: To be a Centre of Excellence in Engineering, Technology and Management on par with


International Standards.

Mission
 To prepare the students with high professional skills and ethical values
 To impart knowledge through best practices
 To instil a spirit of innovation through Training, Research and Development
 To undertake continuous assessment and remedial measures
 To achieve academic excellence through intellectual, emotional and social stimulation

Department Vision and Mission

Vision: To produce the Computer Science and Engineering graduates with the Innovative and
Entrepreneur skills to face the challenges ahead

Mission

 M1: To impart knowledge in the state of art technologies in Computer Science and
Engineering

 M2: To inculcate the analytical and logical skills in the field of Computer Science and
Engineering

 M3: To prepare the graduates with Ethical values to become successful Entrepreneurs

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 2


Program Educational Objectives (PEOs):
 PEO1:Graduates will be able to Practice as an IT Professional in Multinational Companies

 PEO2:Graduates will be able to Gain necessary skills and to pursue higher education for
career growth.

 PEO3:Graduates will be able to Exhibit the leadership skills and ethical values in the day
to day life.

Program Outcomes (POs):

PO1 : Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2 : Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO3 : Design / Development Solutions: Design solutions for complex, engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4 : Conduct Investigations of Complex Problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5 : Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6 : The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice
PO7: Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 3
of, and need for sustainable development
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and Team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply the se to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
PO12: Lifelong Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

Program Specific Outcomes (PSOs):

 PSO1: Graduates should be able to design and analyze the algorithms to develop an Intelligent
Systems

 PSO2: Graduates should be able to apply the acquired skills to provide efficient solutions for real
time problems

 PSO3: Graduates should be able to exhibit an understanding of System Architecture, Networking


and Information Security

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 4


Do’s and Dont’s in the Laboratory:

DO’S

 Know the location of the fire extinguisher and the first aid box and how to use them in
case of an emergency.

 Read and understand how to carry out an activity thoroughly before coming to the
laboratory.

 Use hand sanitizer and face mask before enter in the Laboratory

 Report fires or accidents to your lecturer/laboratory technician immediately.

 Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician
immediately.

DONT’S
 Do not eat or drink in the laboratory.

 Avoid stepping on electrical wires or any other computer cables.

 Do not open the system unit casing or monitor casing particularly when the power is
turned on. Some internal components hold electric voltages of up to 30000 volts, which can
be fatal.

 Do not insert metal objects such as clips, pins and needles into the computer casings. They
may cause fire.

 Do not remove anything from the computer laboratory without permission.

 Do not touch, connect or disconnect any plug or cable without your lecturer/laboratory
technician’s permission.

 Do not misbehave in the computer laboratory.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 5


LIST OF EXPERIMENTS

1. Compute the GCD of two numbers.


2. Find the square root of a number (Newton ‘s method)
3. Develop a python program for Exponentiation (power of a number)
4. Find the maximum of a list of numbers
5. Develop a python program to Selection sort, Insertion sort
6. Implement divide and conquer method using Merge sort
7. Find first n prime numbers using python
8. Implement matrix multiplication using 2-dimensional array
9. Programs that take command line arguments (word count)
10. Find the most frequent words in a text read from a file
11. Simulate elliptical orbits in Pygame
12. Simulate bouncing ball using Pygame
13. Object detection using Tensorflow
14. Object detection using Keras

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 6


23GES05 – PYTHON PROGRAMMING LAB
INDEX

STAFF
S.NO DATE EXPERIMENTS MARKS
SIGNATURE

1. Compute the GCD of two numbers.

2. Find the square root of a number (Newton ‘s method)

Develop a python program for Exponentiation


3.
(power of a number)

4. Find the maximum of a list of numbers

Develop a python program to Selection sort, Insertion


5.
sort
Implement divide and conquer method using Merge
6.
sort

7. Find first n prime numbers using python

Implement matrix multiplication using 2-


8.
dimensional array.
Programs that take command line arguments (word
9.
count)
Find the most frequent words in a text read from a
10.
file

11. Simulate elliptical orbits in Pygame

12. Simulate bouncing ball using Pygame

13. Object detection using Tensorflow

14. Object detection using Keras

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 7


Ex.No: 1
Compute the GCD of two numbers
DATE:

AIM:
To compute the GCD of two numbers Greatest Common Divisor.
ALGORITHM:
Step1:Start
Step 2: Read two numbers to find the GCD number(x,y)
Step3: def GCD function
Step4: Enter the first number
Step 5: Enter the second number
Step 6: print GCD is x,y
Step 7: Stop
PROGRAM
def gcd_fun (x, y):
if (y == 0): # it divide every number
return x # return x
else:
return gcd_fun (y, x % y)
x =int (input ("Enter the first number: ")) # take first no.
y =int (input ("Enter the second number: ")) # take second no.
num = gcd_fun(x, y) # call the gcd_fun() to find the result
print ("GCD of two number is: ")
print(num) # call num

OUTPUT:
Enter the first number: 54
Enter the second number: 24
GCD of two number is:6

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 8


Ex.No: 2
Find the Square root of a number (newton’s method)
DATE:

AIM:
To find the square root of a number (Newton’s method)
ALGORITHM:
Step1:Start
Step 2: Define the square root function n.
Step 3: Assign the syntax
Step 4: 0.5*(approx root + n/approx root)
Step 5: write the newton’s method square root values
Step 6: Enter the newton’s square root value
Step 7: Run the program
Step 8: Stop

PROGRAM
defnewtonSqrt (n, base):
approx_root = 0.5 * n
fori in range(base):
betterapprox = 0.5 * (approx_root + n/approx_root)
approx_root = betterapprox
returnbetterapprox
print ("the square root of 100:", newtonSqrt (100, 10))
print ("the square root of 256:", newtonSqrt (256, 10))
print ("the square root of 24:", newtonSqrt (24, 10))

OUTPUT:
the square root of 100: 10.0
the square root of 256: 16.0
the square root of 24: 4.898979485566356

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 9


Ex.No: 3 Develop a Python Program for Exponentiation
DATE: (power of a number)

AIM:
To develop a python programming for exponentiation (power of a number).
ALGORITHM:
Step1:Start
Step 2: Define the number and Exponent
Step 3: Assign the values
Step 4: Give the range of the exponent
Step 5: write the syntax
Step 6: Enter the format of the exponent power values
Step 7: Enter the positive integer
Step 8: Enter the Exponent values
Step 9: Run the program
Step 10: Stop

PROGRAM
number = int (input (" Please Enter any Positive Integer: "))
exponent = int (input (" Please Enter Exponent Value: "))
power = 1

fori in range (1, exponent + 1):


power = power * number

print ("The Result of {0} Power {1} = {2}". format (number, exponent, power))

OUTPUT:
Please Enter any Positive Integer: 3
Please Enter Exponent Value: 4
The Result of 3 Power 4 = 81

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 10


Ex.No:4
Find a maximum of a list of numbers
DATE:

AIM:
To find a maximum of a list of numbers using python programming.
ALGORITHM:
Step1:Start
Step 2: Enter the lists
Step 3: Using in built method here
Step 4: maxn=0
Step 5: list using loop
Step 6: Enter the Maximum values
Step 7: Run the program
Step 8: Stop

PROGRAM
list1= [10,24,7,54,34,76,21]

print ("Maximum number:",max(list1)) #using in-built method

maxn=0

fori in list1: #using loops

if(i>maxn):

maxn=i

print ("Maximum number:",max(list1))

OUTPUT:
Maximum number: 76
Maximum number: 76

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 11


Ex.No:5a
Develop a Python program to Selection Sort
DATE:

AIM:
To develop a python programming to Selection Sort.
ALGORITHM:
Step 1: Start the program
Step 2: Develop a program for Selection Sort
Step 3: list out the ranges
Step 4: For condition to check the conditions:
for j in range (i + 1, len(alist)):
Step 5: using the syntax
ifalist[j] <alist[smallest]:
Step 6: Select the list of numbers
Step 7: Sorted the entered numbers
Step 8: Execute the program
Step 9: Stop

PROGRAM
defselection_sort(alist):
fori in range (0, len(alist) - 1):
smallest = i
for j in range (i + 1, len(alist)):
ifalist[j] <alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input ('Enter the list of numbers: '). split ()
alist = [int(x) for x in alist]
selection_sort(alist)
print ('Sorted list: ', end='')
print(alist)

OUTPUT:
Enter the list of numbers: 6 2 4 3 5 1
Sorted list: [1, 2, 3, 4, 5, 6]

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 12


Ex.No: 5b
Develop a Python program to Insertion Sort
DATE:

AIM:
To develop a python programing to Insertion Sort.
ALGORITHM:
Step 1: Start
Step 2: Develop a program for Insertion Sort
Step 3: list out the ranges
Step 4: using While loop check the conditions:
while j >=0 and key <arr[j]:
Step 5: Sort the array
Step 6: Print the array
Step 7: Execute the program
Step 8: Stop

PROGRAM
definsertionSort(arr):
fori in range (1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greaterthan key,
#To one position ahead of their current position
j = i-1
while j >=0 and key <arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# main
arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
print ("The sorted array is:")
fori in range(len(arr)):
print (arr[i])

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 13


OUTPUT:
The sorted array is:
a
i
l
o
r
t
t
u

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 14


Ex.No: 6
Implement divide and conquer method using Merge Sort
DATE:

AIM:
To implement divide and conquer method using Merge Sort.
ALGORITHM:
Step 1: Start
Step 2: Def the required sorting array
Step 3: if merge sort as,
b=c=d=0
Step 4: using While loop for checking the condition:
while b <len(l) and c <len(r):

Step 5: Following the While conditions


Step 6: Execute the program
Step 7: Stop

PROGRAM

defmergeSort(arr):

iflen(arr) > 1:

a = len(arr)//2

l = arr [: a]

r = arr[a:]

# Sort the two halves

mergeSort(l)

mergeSort(r)

b=c=d=0

while b <len(l) and c <len(r):

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 15


if l[b] < r[c]:

arr[d] = l[b]

b += 1

else:

arr[d] = r[c]

c += 1

d += 1

while b <len(l):

arr[d] = l[b]

b += 1

d += 1

while c <len(r):

arr[d] = r[c]

c += 1

d += 1

defprintList(arr):

fori in range(len(arr)):

print(arr[i], end=" ")

print ()

# Driver program

if __name__ == '__main__':

arr = [0,1,3,5,7,9,2,4,6,8]
MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 16
mergeSort(arr)

print ("Sorted array is: ")

printList(arr)

OUTPUT:
Sorted array is:
0123456789

RESULT:
The above program is successfully executed.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 17


Ex.No: 7
Find Firstnprimenumbers using python
DATE:

AIM:
To find first n prime numbers using python.
ALGORITHM:
Step 1: start
Step 2: Assign the numbers
Step 3: Using if conditions
if(n%i==0):
Step 4: Appear the Break statement
Step 5: using else condition
Step 6: Print the range between the prime number
Step 7: Execute the program
Step 8: Stop

PROGRAM:
numr=int (input ("Enter range:"))
print ("Prime numbers:",end=' ')
for n in range (1, numr):
fori in range (2, n):
if(n%i==0):
break
else:
print (n,end=' ')

OUTPUT:

Enter range:50
Prime numbers: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 18


Ex.No: 8
Implement Matrix multiplication using 2-dimensionalarray
DATE:

AIM:
To Develop a Python program to insert an element into an Array
ALGORITHM:
Step 1: Start
Step 2: Multiplication using Two-dimensional matrix
Step 3: Assign the matrix 1 & matrix 2
Step 4: Using for loop condition to implementing 2-dimensional array
Step 5: using syntax
fori in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
Step 6: Print the value of multiplications
Step 7: Execute the program
Step 8: Stop
PROGRAM
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]
res = [[0 for x in range (3)] for y in range (3)]
# explicit for loops
fori in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
# resulted matrix
res[i][j] += matrix1[i][k] * matrix2[k][j]
print (res)

OUTPUT:
[[114, 160, 60], [74, 97, 73], [119, 157, 112]]

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 19


Ex.No: 9
Programsthattakecommand linearguments(wordcount)
DATE:

AIM:
To program that take command line arguments (word count) in python.
ALGORITHM:
Step 1: Start
Step 2: Assign the number of arguments
Step 3: Using argumentsstr(sys.argv)
Step 4: Getting word command line arguments
Step 5: Run the program
Step 6: Stop
PROGRAM
import sys
defword_count(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
returnlen(words)
exceptFileNotFoundError:
print("File not found.")
return -1
if __name__ == "__main__":
iflen(sys.argv) != 2:
print("Usage: python word_count.py <filename>")
sys.exit(1)
filename = sys.argv[1]
count = word_count(filename)
if count != -1:
print("Word count:", count)

OUTPUT:
A module you have imported isn't available at the moment. It will be available soon.

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 20


Ex.No: 10
Findthemost frequent wordsina textreadfroma file
DATE:

AIM:
To find the most frequent words in a text read from a file.
ALGORITHM:
Step 1: Start
Step 2: Frequent words in a text read from a file
Step 3: Give the statement
Step 4: if the program assign the repeated words in text file.
Step 5: Print most repeated words
Step 6: Execute the required program
Step 7: Start to be execute
Step 8: Find the most repeated words in a text file
Step 9: Stop

PROGRAM

# Python program to find the most repeated word


# in a text file
# A file named "gfg", will be opened with the
# reading mode.
file = open("gfg.txt","r")
frequent_word = ""
frequency = 0
words = []
# Traversing file line by line
for line in file:
# splits each line into
# words and removing spaces
# and punctuations from the input
line_word = line.lower().replace(',','').replace('.','').split(" ");
# Adding them to list words
for w in line_word:
words.append(w);
# Finding the max occurred word
fori in range (0, len(words)):
# Declaring count

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 21


count = 1;
# Count each word in the file
for j in range (i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
# If the count value is more
# than highest frequency then
if (count > frequency):
frequency = count;
frequent_word = words[i];
print ("Most repeated word: " + frequent_word)
print ("Frequency: " + str(frequency))
file.close();

OUTPUT:
Themost frequent wordsina textreadfroma file: Frequent

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 22


Ex.No: 11
SimulateellipticalorbitsinPygame
DATE:

AIM:
To simulate elliptical orbits in Pygame.

ALGORITHM:
Algorithm - Simulation of Elliptical orbit
Step 1: Start the program
Step 2: Set screen size and caption
Step 3: Create clock variable
Step 4: Set x and y radius of ellipse.
Step 5: Starting from degree 0 ending with 360 degrees in increments of 10 degrees calculate the (x1, y1)
coordinates to find a point in the elliptical orbit.
Step 6: Convert degree to radians (degree * 2 * math.pi / 360)
Step 7: Set background color, draw center circle, ellipse and another smaller circle on the ellipse
Step 8: Refresh the screen every 5 clock ticks
Step 9: Repeat steps 4 to 8 until user quits the program
Step 10: Stop the program

PROGRAM:

#Elliptical orbits
import pygame
import math
import sys
pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
xRadius = 250
yRadius = 100
for degree in range(0,360,10):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
screen.fill((0, 0, 0))

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 23


pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)

OUTPUT :

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 24


Ex.No: 12
SimulatebouncingballusingPygame
DATE:

AIM:
To simulate bouncing ball using Pygame.
ALGORITHM:
Step 1: Start
Step 2: Set Screen size and caption
Step 3: Create clock variable
Step 4: Starting from degree 0 ending with 360 degrees
Step 5: Set background color, draw center circle, bouncing ball circle at a center
Step 6: Execute the program
Step 7: Stop

PROGRAM
# Program
# Bouncing ball
import sys, pygame
pygame.init()
size = width, height = 700, 250
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
pygame.time.delay(2)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
if ballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 25


OUTPUT :

RESULT:
The above program is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 26


Ex.No: 13
Object detection using Tensorflow
DATE:

AIM:
Toobject detection using a Tensorflow Python program is to automate the process of identifying and
localizing objects within images or videos.
ALGORITHM:
Object detection using Tensorflow typically involves several steps:
Step1: Data Preparation: Gather and preprocess your dataset.
Step 2: Model Selection: Choose a suitable object detection model.
Step 3: Model Configuration: Configure the selected model according to your needs, such as adjusting
input size, choosing the number of classes to detect, and selecting other hyper parameters.
Step 4: Training: Train your object detection model on your dataset.
Step 5: Evaluation: Evaluate your trained model's performance using the validation set.
Step 6: Fine-tuning (Optional): If necessary, fine-tune your model to improve its performance on specific
types of objects or in specific conditions.
Step 7: Inference: Use your trained model to detect objects in new images or videos.
PROGRAM
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
returnimage_np
# Main function
def main():
cap = cv2.VideoCapture(0)
withdetection_graph.as_default():
withtf.Session(graph=detection_graph) as sess:
while True:
ret, image_np = cap.read()
MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 27
image_np = detect_objects(image_np, sess, detection_graph)
cv2.imshow('object detection', cv2.resize(image_np, (800, 600)))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if __name__ == '__main__':
main()

OUTPUT :

RESULT:
The above Object detection using Tensorflowprogram is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 28


Ex.No: 14
Object detection using Keras
DATE:

AIM:
Toobject detection using a Keras Python program is to automate the process of identifying and localizing
objects within images or videos.
ALGORITHM:
Object detection using Keras typically involves several steps:
Step 1: Build an object detection dataset using Selective Search
Step 2: Fine-tune a classification network (originally trained on ImageNet) for object detection
Step 3: Create an object detection inference script that utilizes Selective Search to propose regions
that could contain an object that we would like to detect
Step 4: Use our fine-tuned network to classify each region proposed via Selective Search
Step 5: Apply non-maxima suppression to suppress weak, overlapping bounding boxes
Step 6: Return the final object detection results
PROGRAM

# import the packages


import numpy as np
import cv2
# this is the model we'll be using for
# object detection
from tensorflow.keras.applications import Xception
# for preprocessing the input
from tensorflow.keras.applications.xception import preprocess_input
from tensorflow.keras.applications import imagenet_utils
from tensorflow.keras.preprocessing.image import img_to_array
from imutils.object_detection import non_max_suppression
# read the input image
img = cv2.imread('/content/img4.jpg')
# instantiate the selective search
# segmentation algorithm of opencv
search = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
# set the base image as the input image
search.setBaseImage(img)
search.switchToSelectiveSearchFast()
# you can also use this for more accuracy ->
# search.switchToSelectiveSearchQuality()
rects = search.process() # process the image
rois = []

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 29


boxes = []
(H, W) = img.shape[:2]
for (x, y, w, h) in rects:
# check if the ROI has atleast
# 20% the size of our image
if w / float(W) < 0.1 or h / float(H) < 0.1:
continue
# Extract the Roi from image
roi = img[y:y + h, x:x + w]
# Convert it to RGB format
roi = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
# Resize it to fit the input requirements of the model
roi = cv2.resize(roi, (299, 299))
# Further preprocessing
roi = img_to_array(roi)
roi = preprocess_input(roi)
# Append it to our rois list
rois.append(roi)
# now let's store the box co-ordinates
x1, y1, x2, y2 = x, y, x + w, y + h
boxes.append((x1, y1, x2, y2))
# ------------ Model--------------- #
model = Xception(weights='imagenet')
# Convert ROIS list to arrays for predictions
input_array = np.array(rois)
print("Input array shape is ;", input_array.shape)
#---------- Make Predictions -------#
preds = model.predict(input_array)
preds = imagenet_utils.decode_predictions(preds, top=1)
# Initiate the dictionary
objects = {}
for (i, pred) in enumerate(preds):
# extract the prediction tuple
# and store it's values
iD = pred[0][0]
label = pred[0][1]
prob = pred[0][2]
if prob>= 0.9:
# grab the bounding box associated
# with the prediction and
# convert the coordinates
box = boxes[i]
# create a tuble using box and probability
value = objects.get(label, [])
# append the value to the list for the label
value.append((box, prob))
# Add this tuple to the objects dictionary
# that we initiated
objects[label] = value
# Loop through the labels
# for each label apply the non_max_suppression

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 30


for label in objects.keys():
# clone the original image so that we can
# draw on it
img_copy = img.copy()
boxes = np.array([pred[0] for pred in objects[label]])
proba = np.array([pred[1] for pred in objects[label]])
boxes = non_max_suppression(boxes, proba)
# Now unpack the co-ordinates of the bounding box
(startX, startY, endX, endY) = boxes[0]
# Draw the bounding box
cv2.rectangle(img_copy, (startX, startY),
(endX, endY), (0, 255, 0), 2)
y = startY - 10 if startY - 10 > 10 else startY + 10
# Put the label on the image
cv2.putText(img_copy, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 0), 2)
# Show the image
cv2.imshow("Regional proposal object detection", img_copy)
cv2.waitKey(0)

OUTPUT :

RESULT:
The above Object detection using Kerasprogram is executed successfully.

MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 31

You might also like