Object Detection Using YOLO and OpenCV
This project demonstrates object detection using OpenCV and the YOLO model.
It uses a webcam to detect objects in real-time. Ensure you have all required files
downloaded before running the script.
Required Files:
- yolov3.weights (YOLO pre-trained weights)
- yolov3.cfg (YOLO model configuration)
- coco.names (List of object classes)
Python Code:
import cv2
import numpy as np
# Load YOLO
weights_path = "yolov3.weights"
config_path = "yolov3.cfg"
names_path = "coco.names"
net = cv2.dnn.readNet(weights_path, config_path)
with open(names_path, "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
# Initialize camera
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
height, width, channels = frame.shape
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
detections = net.forward(output_layers)
for detection in detections:
for obj in detection:
scores = obj[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x, center_y, w, h = (obj[0:4] * np.array([width, height, width,
height])).astype("int")
x = int(center_x - w / 2)
y = int(center_y - h / 2)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, f"{classes[class_id]}: {int(confidence * 100)}%", (x,
y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow("Object Detection", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
Notes:
- Ensure you have OpenCV installed: `pip install opencv-python numpy`
- Download required YOLO files from official sources.
- Press 'q' to exit the program.