Spaces:
Sleeping
Sleeping
import cv2 | |
import gradio as gr | |
from ultralytics import YOLO | |
# ── Config ───────────────────────────────────────────── | |
MODEL_PATH = "yolov8n.pt" | |
CONF_THRES = 0.30 | |
LINE_RATIO = 0.50 | |
# ─────────────────────────────────────────────────────── | |
model = YOLO(MODEL_PATH) | |
memory, in_count, out_count = {}, 0, 0 | |
def count_people(frame_rgb): | |
global memory, in_count, out_count | |
if frame_rgb is None: | |
return None, "" | |
frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR) | |
h, w = frame_bgr.shape[:2] | |
line_y = int(h * LINE_RATIO) | |
results = model.track(frame_bgr, | |
classes=[0], conf=CONF_THRES, | |
persist=True, verbose=False) | |
annotated = frame_bgr.copy() | |
cv2.line(annotated, (0, line_y), (w, line_y), (0, 255, 255), 2) | |
if results: | |
for box in results[0].boxes: | |
x1, y1, x2, y2 = map(int, box.xyxy[0]) | |
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 | |
tid = int(box.id[0]) if box.id is not None else -1 | |
prev_cy = memory.get(tid, cy) | |
if prev_cy < line_y <= cy: | |
in_count += 1 # entró | |
elif prev_cy > line_y >= cy: | |
out_count += 1 # salió | |
memory[tid] = cy | |
cv2.rectangle(annotated, (x1, y1), (x2, y2), (0, 255, 0), 1) | |
cv2.circle(annotated, (cx, cy), 3, (0, 0, 255), -1) | |
cv2.putText(annotated, str(tid), (x1, y1 - 5), | |
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1) | |
total = in_count - out_count | |
label = f"In: {in_count} | Out: {out_count} | Ocupación: {total}" | |
annotated_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB) | |
return annotated_rgb, label | |
def reset_counts(): | |
global memory, in_count, out_count | |
memory, in_count, out_count = {}, 0, 0 | |
return None, "" | |
with gr.Blocks(title="Contador de personas (entrada única)") as demo: | |
gr.Markdown("# Contador de personas (entrada única)") | |
with gr.Row(): | |
cam = gr.Image(sources=["webcam"], streaming=True, label="frame") | |
out_img = gr.Image(label="Video") | |
out_lbl = gr.Text(label="Contador") | |
btn_clear = gr.Button("Limpiar") | |
cam.stream(count_people, inputs=[cam], outputs=[out_img, out_lbl]) | |
btn_clear.click(reset_counts, outputs=[out_img, out_lbl]) | |
# límite de cola (para que no se llene si baja el FPS) | |
demo.queue(max_size=60) | |
demo.launch() | |