Data Science Jupyter Notebooks
11K subscribers
269 photos
31 videos
9 files
726 links
Explore the world of Data Science through Jupyter Notebooks—insights, tutorials, and tools to boost your data journey. Code, analyze, and visualize smarter with every post.
Download Telegram
#YOLOv8 #ComputerVision #ObjectDetection #Python #AI

Audience Analysis with YOLOv8: Counting People & Estimating Gender Ratios

This lesson demonstrates how to use the YOLOv8 model to perform a computer vision task: analyzing an image of a crowd to count the total number of people and estimate the ratio of men to women.

---

Step 1: Setup and Installation

First, we need to install the necessary libraries. ultralytics for the YOLOv8 model, opencv-python for image manipulation, and cvlib for a simple, pre-trained gender classification model.

#Setup #Installation

# Open your terminal or command prompt and run:
pip install ultralytics opencv-python cvlib tensorflow


---

Step 2: Loading Models and Image

We will load two models: the official YOLOv8 model pre-trained for object detection, and we'll use cvlib for gender detection. We also need to load the image we want to analyze. Make sure you have an image named crowd.jpg in the same directory.

#DataLoading #Model

import cv2
from ultralytics import YOLO
import cvlib as cv
import numpy as np

# Load the YOLOv8 model (pre-trained on COCO dataset)
model = YOLO('yolov8n.pt')

# Load the image
image_path = 'crowd.jpg' # Make sure this image exists
img = cv2.imread(image_path)

# Check if the image was loaded correctly
if img is None:
print(f"Error: Could not load image from {image_path}")
else:
print("Image and YOLOv8 model loaded successfully.")


---

Step 3: Person Detection with YOLOv8

Now, we'll run the YOLOv8 model on our image to detect all objects and then filter those results to keep only the ones identified as a 'person'.

#PersonDetection #Inference

# Run inference on the image
results = model(img)

# A list to store the bounding boxes of detected people
person_boxes = []

# Process the results
for result in results:
boxes = result.boxes
for box in boxes:
# Get class id and check if it's a person (class 0 in COCO)
if model.names[int(box.cls)] == 'person':
# Get bounding box coordinates
x1, y1, x2, y2 = map(int, box.xyxy[0])
person_boxes.append((x1, y1, x2, y2))

# Print the total number of people found
total_people = len(person_boxes)
print(f"Total people detected: {total_people}")


---

Step 4: Gender Classification

For each detected person, we will crop their bounding box from the image. Then, we'll use cvlib to detect a face within that crop and predict the gender. This is a multi-step pipeline.

#GenderClassification #CV
#YOLOv8 #ComputerVision #HomeSecurity #ObjectTracking #AI #Python

Lesson: Tracking Suspicious Individuals Near a Home at Night with YOLOv8

This tutorial demonstrates how to build an advanced security system using YOLOv8's object tracking capabilities. The system will detect people in a night-time video feed, track their movements, and trigger an alert if a person loiters for too long within a predefined "alert zone" (e.g., a driveway or porch).

---

#Step 1: Project Setup and Dependencies

We will use ultralytics for YOLOv8 and its built-in tracker, opencv-python for video processing, and numpy for defining our security zone.

pip install ultralytics opencv-python numpy

Create a Python script (e.g., security_tracker.py) and import the necessary libraries. We'll also use defaultdict to easily manage timers for each tracked person.

import cv2
import numpy as np
from ultralytics import YOLO
from collections import defaultdict
import time

# Hashtags: #Setup #Python #OpenCV #YOLOv8


---

#Step 2: Model Loading and Zone Configuration

We will load a standard YOLOv8 model capable of detecting 'person'. The key is to define a polygon representing the area we want to monitor. We will also set a time threshold to define "loitering". You will need a video file of your target area, for example, night_security_footage.mp4.

# Load the YOLOv8 model
model = YOLO('yolov8n.pt')

# Path to your night-time video file
VIDEO_PATH = 'night_security_footage.mp4'

# Define the polygon for the alert zone.
# IMPORTANT: You MUST adjust these [x, y] coordinates to fit your video's perspective.
# This example defines a rectangular area for a driveway.
ALERT_ZONE_POLYGON = np.array([
[100, 500], [800, 500], [850, 250], [50, 250]
], np.int32)

# Time in seconds a person can be in the zone before an alert is triggered
LOITERING_THRESHOLD_SECONDS = 5.0

# Dictionaries to store tracking data
# Stores the time when a tracked object first enters the zone
loitering_timers = {}
# Stores the IDs of individuals who have triggered an alert
alert_triggered_ids = set()

# Hashtags: #Configuration #AIModel #SecurityZone


---

#Step 3: Main Loop for Tracking and Zone Monitoring

This is the core of the system. We will read the video frame by frame and use YOLOv8's track() function. This function not only detects objects but also assigns a unique ID to each one, allowing us to follow them across frames.

cap = cv2.VideoCapture(VIDEO_PATH)

while cap.isOpened():
success, frame = cap.read()
if not success:
break

# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True)

# Get the bounding boxes and track IDs
boxes = results[0].boxes.xywh.cpu()
track_ids = results[0].boxes.id.int().cpu().tolist()

# Visualize the results on the frame
annotated_frame = results[0].plot()

# Draw the alert zone polygon on the frame
cv2.polylines(annotated_frame, [ALERT_ZONE_POLYGON], isClosed=True, color=(0, 255, 255), thickness=2)

# Hashtags: #RealTime #ObjectTracking #VideoProcessing

(Note: The code below should be placed inside the while loop of Step 3)

---

#Step 4: Implementing Loitering Logic and Alerts

Inside the main loop, we'll iterate through each tracked person. We check if their position is inside our alert zone. If it is, we start or update a timer. If the timer exceeds our threshold, we trigger an alert for that person's ID.