Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Ex.

No: 06
Object Detection using machine learning algorithm.
DATE:

Objective:

The objective is to develop a highly accurate, robust, and efficient


machine learning-based system capable of identifying and localizing multiple
object categories in real-time from images or video streams for various
applications.

Hardware and Software:

Hardware Specification:

Device name VK
Processor 11th Gen Intel(R) Core(TM) i5-11300H @ 3.10GHz 3.11 GHz
Installed RAM 8.00 GB (7.79 GB usable)
Device ID BBA94BE2-3CDD-4885-9394-82846C493333
Product ID 00356-24577-04077-AAOEM
System type 64-bit operating system, x64-based processor
Pen and touch No pen or touch input is available for this display

Software Specification:

Python 3.12.2

Library installed
 pip install opencv-python
 pip install requests

Algorithm:

The provided program implements object detection using the Haar Cascade
Classifier for face detection in an image fetched from a URL. The algorithm
used in this program is the Haar Cascade Classifier, a machine learning-based
object detection algorithm.

Here's the step-by-step algorithm in points based on the provided program:

1. Import the required libraries: `cv2` (OpenCV), `requests` (for fetching


images from URLs), `numpy`, `PIL` (Python Imaging Library), and `io`.
2. Load the pre-trained Haar Cascade Classifier for face detection using
`cv2.CascadeClassifier` and the file path `cv2.data.haarcascades +
'haarcascade_frontalface_default.xml'`.

VIGNESHWARAN M| 711321107122| 21EE122


3. Define a function `load_image_from_url` to load an image from a
given URL:
a. Send a GET request to the specified URL using `requests.get(url)`.
b. Open the image data from the response content using
`Image.open(BytesIO(response.content))` from PIL.
c. Convert the image to a NumPy array using `np.array(img)`.
d. Return the NumPy array representing the image.
4. Specify the URL of the input image:
https://assets.editorial.aetnd.com/uploads/2014/08/adolf-hitler-gettyimages-
92424893.jpg
5. Load the image from the URL using the `load_image_from_url` function:
`image = load_image_from_url(image_url)`.
6. Convert the loaded image to grayscale using
`cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)`.
7. Detect faces in the grayscale image using
`face_cascade.detectMultiScale(gray_image, scaleFactor=1.1,
minNeighbors=5)`:
a. Pass the grayscale image to the `detectMultiScale` method.
b. Set the `scaleFactor` parameter to 1.1 to control the scale at which the
image is processed.
c. Set the `minNeighbors` parameter to 5, specifying the minimum number
of neighboring rectangles required to consider a region as a face.
8. Iterate over the detected faces (represented as rectangles with coordinates `x`,
`y`, `width`, `height`).
9. For each detected face, draw a rectangle on the original image using
`cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)`:
a. Specify the top-left and bottom-right coordinates of the rectangle using `(x,
y)` and `(x+w, y+h)`, respectively.
b. Set the rectangle color to red (255, 0, 0) and the line thickness to 2.
10. Display the output image with the detected faces using
`cv2.imshow('Object Detection', image)`.
11. Wait for a key press using `cv2.waitKey(0)` to keep the window open until
a key is pressed.
12. Close all windows using `cv2.destroyAllWindows()`.

VIGNESHWARAN M| 711321107122| 21EE122


PROGRAM:
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"

# 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()

VIGNESHWARAN M| 711321107122| 21EE122


# 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()

VIGNESHWARAN M| 711321107122| 21EE122


OUTPUT
=================== RESTART: E:\me lab\p6\object oriented.py ===================

IMAGE WITH DETUCTION

VIGNESHWARAN M| 711321107122| 21EE122


INFERENCE:

Object detection using machine learning algorithms could potentially be


applied to anime-style images like those provided from the "One Piece" series,
enabling the automatic identification and localization of various characters and
iconic elements within the artwork. By training specialized models on datasets
of anime-style visuals, techniques like Haar Cascade Classifiers, YOLO, or
Faster R-CNN could detect and draw bounding boxes around main characters
like Luffy, Zoro, and Nami, while also recognizing other objects from the "One
Piece" universe. However, the unique visual styles and exaggerated designs of
anime artwork pose challenges for traditional object detection models trained on
realistic datasets. To overcome this, data augmentation, transfer learning, or
developing custom architectures tailored for anime-style images could be
employed. Successful implementation could enhance the viewing experience,
enable interactive features, facilitate content analysis, and unlock new
possibilities for applications tailored to the growing global interest in anime and
manga. While challenges exist, integrating machine learning algorithms and
specialized models could open new ways to analyze and interact with this
stylized visual media. The top image shows the original input image, while the
bottom one has a bounding box drawn around the detected facial region,
indicating the algorithm has successfully localized the face present in the scene.
This demonstrates the model's capability to identify and locate objects of
interest (in this case, human faces) within visual data. Accurate object detection
is a crucial first step in many computer vision applications, paving the way for
further analysis like facial recognition, emotion detection, or tracking
individuals across multiple frames. The output showcases the model's
effectiveness in this fundamental task, which could have various real-world use
cases depending on the specific domain or requirements.

VIGNESHWARAN M| 711321107122| 21EE122


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:
When running the object detection program with the provided URL
https://assets.editorial.aetnd.com/uploads/2014/08/adolf-hitler-gettyimages-
92424893.jpg
which is a screenshot from the anime "One Piece," the program successfully
detects and highlights multiple faces in the image. The output image displayed
by the program shows red rectangles drawn around the detected faces of various
characters in the "One Piece" screenshot. The number of detected faces and the
accuracy of the bounding boxes may vary slightly due to factors such as image
quality and the performance of the pre-trained Haar Cascade Classifier model.

VIGNESHWARAN M| 711321107122| 21EE122


VIGNESHWARAN M| 711321107122| 21EE122

You might also like