Yolo 8 crowd dete4ctions

120 Views Asked by At

I have this code to detect crowds with yolo v8 in a video but when im trying to execute it it says have an error on the start of the for cycle and i tried to sub the expression "xyxy" by pred but doesnt work too

I tried sub the expression "xyxy" for "pred" but doesnt work at same and on conda says that the error its at that line, im new to python and idont know how to solve it

import cv2
import numpy as np
from ultralytics import YOLO

# Load YOLO model
modelo = YOLO('yolov8n.pt')

# Load class names from "coco.names"
with open("coco.names", "r") as my_file:
    class_list = my_file.read().strip().split("\n")

# Minimum distance for crowd detection
min_distance = 50  # You can adjust this value

# Function to calculate distance between two points
def calculate_distance(point1, point2):
    return np.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)

# Open the video
cap = cv2.VideoCapture("videoteste.mp4")

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

    # Detect objects using YOLO
    results = modelo(frame)

    # Initialize a list to store middle points
    middle_points = []
    for detection in results.xyxy[0]: 
        class_id = int(detection[5])  # Extract the class ID
        if class_id < len(class_list):
            class_name = class_list[class_id]
        if class_name == 'person':
            x, y, w, h = detection[0:4]  # Bounding box coordinates
            middle_x = x + w / 2
            middle_y = y + h / 2
            middle_points.append((middle_x, middle_y))

    # Check for crowd
    for i in range(len(middle_points)):
        for j in range(i + 1, len(middle_points)):
            dist = calculate_distance(middle_points[i], middle_points[j])
            if dist <= min_distance:
                print("CROWD ALERT: Minimum distance violated")

    # Display the frame with detections
    modelo.show()

# Release the video capture
cap.release()
cv2.destroyAllWindows()
0

There are 0 best solutions below