cesar commited on
Commit
e651f8c
·
verified ·
1 Parent(s): ac8349b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -79
app.py CHANGED
@@ -1,79 +1 @@
1
- # app.py
2
- import cv2
3
- import gradio as gr
4
- from ultralytics import YOLO
5
-
6
- # ── Config ─────────────────────────────────────────────
7
- MODEL_PATH = "yolov8n.pt" # modelo pre-entrenado (COCO, clase “person”)
8
- CONF_THRES = 0.3 # confianza mínima
9
- LINE_RATIO = 0.5 # línea virtual en mitad de la altura
10
- # ───────────────────────────────────────────────────────
11
-
12
- model = YOLO(MODEL_PATH)
13
-
14
- # Estado global para entradas/salidas
15
- memory = {} # {track_id: previous_cy}
16
- in_count = 0
17
- out_count = 0
18
-
19
- def count_people(frame):
20
- global memory, in_count, out_count
21
-
22
- h, w = frame.shape[:2]
23
- line_y = int(h * LINE_RATIO)
24
-
25
- # detección + tracking interno (ByteTrack)
26
- results = model.track(
27
- frame,
28
- classes=[0], # solo “person”
29
- conf=CONF_THRES,
30
- persist=True,
31
- verbose=False
32
- )
33
-
34
- annotated = frame.copy()
35
- cv2.line(annotated, (0, line_y), (w, line_y), (0, 255, 255), 2)
36
-
37
- if results:
38
- for box in results[0].boxes:
39
- x1, y1, x2, y2 = map(int, box.xyxy[0])
40
- cx, cy = int((x1 + x2) / 2), int((y1 + y2) / 2)
41
- tid = int(box.id[0]) if box.id is not None else -1
42
-
43
- # lógica de cruce
44
- prev_cy = memory.get(tid, cy)
45
- if prev_cy < line_y <= cy: # entra
46
- in_count += 1
47
- elif prev_cy > line_y >= cy: # sale
48
- out_count += 1
49
- memory[tid] = cy
50
-
51
- # dibujo
52
- cv2.rectangle(annotated, (x1, y1), (x2, y2), (0, 255, 0), 1)
53
- cv2.circle(annotated, (cx, cy), 3, (0, 0, 255), -1)
54
- cv2.putText(annotated, str(tid), (x1, y1 - 5),
55
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)
56
-
57
- total = in_count - out_count
58
- cv2.putText(
59
- annotated,
60
- f"In: {in_count} Out: {out_count} Ocupación: {total}",
61
- (10, 30),
62
- cv2.FONT_HERSHEY_SIMPLEX,
63
- 1,
64
- (255, 255, 255),
65
- 2
66
- )
67
-
68
- return annotated, f"In: {in_count} | Out: {out_count} | Ocupación: {total}"
69
-
70
- demo = gr.Interface(
71
- fn=count_people,
72
- inputs=gr.Image(sources=["webcam"], streaming=True), # 👈 parámetro correcto
73
- outputs=[gr.Image(label="Video"), gr.Text(label="Contador")],
74
- live=True,
75
- title="Contador de personas (entrada única)"
76
- )
77
-
78
- if __name__ == "__main__":
79
- demo.launch()
 
1
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/61b22e8eb38ed4c779d540fc/rkXD8FcVjo6w33hleoJvs.png)