assume i only have python installed and no knowledge of machine learning make me an…
- User
assume i only have python installed and no knowledge of machine learning make me an intermediate Real-Time Object Detection System project
- Assistant
assume i only have python installed and no knowledge of machine learning make me an intermediate Real-Time Object Detection System project
Welcome! In this project, we'll build a Real-Time Object Detection System using Python. Even if you have no prior knowledge of machine learning, we'll utilize pre-trained models and libraries to get you up and running. This project will help you understand how object detection works and give you hands-on experience with real-time applications.
We will create a Python application that uses your computer's webcam to detect and highlight objects in real-time. We'll use the following tools:
We need to install a few libraries before we start:
Open your command prompt or terminal and run the following commands:
pip install opencv-python
pip install numpy
pip install imutils
Note: If you encounter any permission issues, try adding --user at the end of each command.
Object detection involves locating instances of objects (like people, cars, or animals) within images or videos. In this project, we'll use a pre-trained model called MobileNet SSD (Single Shot Detector), which is efficient and suitable for real-time applications.
.caffemodel): Contains the pre-trained weights of the neural network..prototxt): Defines the model architecture.We'll download these files and use them in our application.
Create a new directory for your project:
mkdir real_time_object_detection
cd real_time_object_detection
Download the necessary files from the following links:
Place both files into your project directory.
Create a Python list to hold the class labels that the model can detect:
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"]
import numpy as np
import cv2
# Load the serialized model from disk
net = cv2.dnn.readNetFromCaffe('MobileNetSSD_deploy.prototxt', 'MobileNetSSD_deploy.caffemodel')
# Start the video stream
cap = cv2.VideoCapture(0) # 0 for the default webcam
while True:
# Capture frame-by-frame
ret, frame = cap.read()
if not ret:
break
# Resize the frame to have a maximum width of 600 pixels
frame_resized = cv2.resize(frame, (600, int(frame.shape[0] * 600 / frame.shape[1])))
# Get the dimensions of the frame
(h, w) = frame_resized.shape[:2]
# Preprocess the frame to create a blob
blob = cv2.dnn.blobFromImage(cv2.resize(frame_resized, (300, 300)),
0.007843, (300, 300), 127.5)
# Set the blob as input to the network
net.setInput(blob)
# Forward pass to get the detections
detections = net.forward()
# Loop over the detections
for i in np.arange(0, detections.shape[2]):
# Extract the confidence
confidence = detections[0, 0, i, 2]
# Filter out weak detections
if confidence > 0.2:
# Extract the index of the class label
idx = int(detections[0, 0, i, 1])
# Get the bounding box coordinates
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype('int')
# Draw the prediction on the frame
label = f"{CLASSES[idx]}: {confidence * 100:.2f}%"
cv2.rectangle(frame_resized, (startX, startY), (endX, endY),
(0, 255, 0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame_resized, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Real-Time Object Detection', frame_resized)
# Break the loop on 'q' key press
if cv2.waitKey(1) == ord('q'):
break
# Release the capture and close windows
cap.release()
cv2.destroyAllWindows()
python your_script_name.py
A window should open showing the video stream from your webcam.
Point your camera towards objects like a bottle, person, or chair.
The system should detect and highlight the objects in real-time.
Here's the complete script for reference:
import numpy as np
import cv2
# Class labels
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"]
# Load the model
net = cv2.dnn.readNetFromCaffe('MobileNetSSD_deploy.prototxt',
'MobileNetSSD_deploy.caffemodel')
# Initialize the video stream
cap = cv2.VideoCapture(0)
while True:
# Read frame
ret, frame = cap.read()
if not ret:
break
frame_resized = cv2.resize(frame, (600, int(frame.shape[0] * 600 / frame.shape[1])))
(h, w) = frame_resized.shape[:2]
# Prepare the frame for classification
blob = cv2.dnn.blobFromImage(cv2.resize(frame_resized, (300, 300)),
0.007843, (300, 300), 127.5)
# Set the blob as input and perform a forward pass
net.setInput(blob)
detections = net.forward()
# Process each detection
for i in np.arange(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.2:
idx = int(detections[0, 0, i, 1])
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype('int')
label = f"{CLASSES[idx]}: {confidence * 100:.2f}%"
cv2.rectangle(frame_resized, (startX, startY), (endX, endY),
(0, 255, 0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame_resized, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the frame
cv2.imshow('Real-Time Object Detection', frame_resized)
if cv2.waitKey(1) == ord('q'):
break
# Clean up
cap.release()
cv2.destroyAllWindows()
Congratulations! You've built a real-time object detection system using Python and pre-trained models. This project introduced you to:
To take this project further:
Feel free to ask questions or seek further explanations on any part of this project. Happy coding!
Not yet included in a published release.