0% found this document useful (0 votes)
46 views8 pages

Machine Learning Program 6 (SHANKAR)

The document discusses implementing object detection models using pre-trained models like YOLO. It covers offline detection on static images and online detection of objects in video streams. Steps include loading models, preprocessing data, making predictions and visualizing results.

Uploaded by

21EE076 NIDHIN
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)
46 views8 pages

Machine Learning Program 6 (SHANKAR)

The document discusses implementing object detection models using pre-trained models like YOLO. It covers offline detection on static images and online detection of objects in video streams. Steps include loading models, preprocessing data, making predictions and visualizing results.

Uploaded by

21EE076 NIDHIN
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/ 8

Ex.

No: 6 OBJECT DETECTION USING MACHINE LEARNING


DATE: ALGORITHM

AIM:

The Aim of the program is to perform object detection in both online and
offline mode and implement a simple object detection model using a pre-trained
model such as YOLO (You Look Only Once) in Python.

HARDWARE SPECIFICATION:

Processor : Apple M1
Installed RAM : 8.00 GB

SOFTWARE SPECIFICATION:

PYTHON IDLE( 3.12.1 64 BIT)

LIBRARIES:

OpenCV , NumPy , Requests

ALGORITHM:

The lab will cover the following steps and aspects of object detection:
1. Introduction to Object Detection:
• Brief explanation of object detection in the context of computer vision.
• Overview of popular object detection algorithms.
2. Data Loading:
• Import necessary libraries (e.g., OpenCV, NumPy).
• Download a pre-labeled dataset for object detection (e.g., COCO dataset).
3. Data Exploration:
• Understand the structure of the dataset, including labeled bounding boxes and
class labels.
4. Data Preprocessing:
• Load and preprocess images from the dataset.
• Normalize or standardize pixel values.

SUDARSAN R-21EE113
5. Model Implementation:
• Implement object detection using a pre-trained model (e.g., YOLO).
• Discuss the architecture of the chosen model and its components.

6. Model Inference:
• Apply the trained model to detect objects in new images.
• Visualize the bounding boxes and class labels.
7. Evaluation and Fine-Tuning:
• Evaluate the performance of the model on the test set.
• Discuss strategies for fine-tuning the model or training on a custom dataset.

SUDARSAN R-21EE113
PROGRAM:
OFFLINE OBJECT DETECTION:

import cv2
import requests
import numpy as np
from io import BytesIO
from PIL import Image
import matplotlib.pyplot as plt
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

# Load the pre-trained Haar Cascade Classifier for face detection


face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')

# Function to load image from URL with retries


def load_image_from_url(url, retries=3):
session = requests.Session()
retry_strategy = Retry(total=retries, backoff_factor=1)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)

try:
response = session.get(url)
response.raise_for_status()
img = Image.open(BytesIO(response.content))
img = np.array(img)
return img
except requests.exceptions.RequestException as e:
print(f"Error loading image from URL: {e}")
return None

# URL of the input image


image_url = "https://assets.editorial.aetnd.com/uploads/2014/08/adolf-hitler-
gettyimages-92424893.jpg"

SUDARSAN R-21EE113
# Load the image from URL
image = load_image_from_url(image_url)

if image is not None:


# Display the original image using Matplotlib
plt.imshow(image)
plt.axis('off') # Hide axis
plt.show()

# Convert the image to grayscale


gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Detect faces in the image


faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1,
minNeighbors=5)

# Check if any faces were detected


if len(faces) == 0:
print("No faces detected in the image.")
else:
# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Display the output image using Matplotlib


plt.imshow(image)
plt.axis('off') # Hide axis
plt.show( )

ONLINE OBJECT DETETION:

import cv2
from random import randint
dnn = cv2.dnn.readNet('yolov4-tiny.weights', 'yolov4-tiny.cfg')
model = cv2.dnn_DetectionModel(dnn)

SUDARSAN R-21EE113
model.setInputParams(size=(416, 416), scale=1/255, swapRB=True)
with open('classes.txt') as f:
classes = f.read().strip().splitlines()
capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
color_map = {}

while True:
# frame capture
_, frame = capture.read()
frame = cv2.flip(frame,1)

# object detection
class_ids, confidences, boxes = model.detect(frame)
for id, confidence, box in zip(class_ids, confidences, boxes):
x, y, w, h = box
obj_class = classes[id]
if obj_class not in color_map:
color = (randint(0, 255), randint(0, 255), randint(0, 255))
color_map[obj_class] = color
else:
color = color_map[obj_class]
cv2.putText(frame, f'{obj_class.title()} {format(confidence, ".2f")}', (x, y-10),
cv2.FONT_HERSHEY_DUPLEX, 1, color, 2)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.imshow('Video Capture', frame)
key = cv2.waitKey(1) # freezes frame for 1ms
match(key):
case 27: # esc key to exit
capture.release()
cv2.destroyAllWindows()
case 13: # enter key to reset colors
color_map = {}

SUDARSAN R-21EE113
OUTPUT:

OFFLINE OBJECT DETECTION:

SUDARSAN R-21EE113
ONLINE OBJECT DETECTION:

SUDARSAN R-21EE113
INFERENCE:

Offline Object Detection:


Detecting faces in a static image retrieved from a URL using the Haar Cascade
Classifier for face detection.

Online Object Detection:


Detecting objects in a live video stream from a webcam using the YOLOv4-tiny
model. The detected objects are labeled with their class names and confidence scores,
and bounding boxes are drawn around them.

However, the provided output section is empty, possibly due to the absence of
executed code or missing output statements.

RUBRICS:

Outcome
Exemplary Proficient Apprentice Novice
Parameter Score
(4) (3) (2) (1)
(1 - 4)
Identifying clear goals for
the experiment
Choosing the appropriate
experimental test bed
(Hardware, Software,
Emulation, Simulation, or
hybrid) to achieve the
identified objectives of the
experiment
Designing and conducting
the experiment

Ability to analyze and


interpret the data

RESULT:

In this program demonstrates the implementation of object detection using both


offline and online approaches, showcasing the versatility and applicability of pre-
trained models in computer vision tasks. The output includes visualizations of offline
and online object detection results. However, the provided output section is empty,
possibly due to the absence of executed code or missing output statements.

SUDARSAN R-21EE113

You might also like