Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, Response, render_template, request
|
| 2 |
+
import torch
|
| 3 |
+
from ultralytics import YOLO
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# Load YOLOv8 model
|
| 10 |
+
model = YOLO("yolov8x.pt")
|
| 11 |
+
|
| 12 |
+
# Store user-provided IP Webcam URL
|
| 13 |
+
IP_WEBCAM_URL = None
|
| 14 |
+
|
| 15 |
+
def generate_frames():
|
| 16 |
+
global IP_WEBCAM_URL
|
| 17 |
+
if not IP_WEBCAM_URL:
|
| 18 |
+
return
|
| 19 |
+
|
| 20 |
+
cap = cv2.VideoCapture(IP_WEBCAM_URL)
|
| 21 |
+
|
| 22 |
+
while True:
|
| 23 |
+
success, frame = cap.read()
|
| 24 |
+
if not success:
|
| 25 |
+
break
|
| 26 |
+
|
| 27 |
+
# Perform YOLOv8 object detection
|
| 28 |
+
results = model.predict(frame)
|
| 29 |
+
|
| 30 |
+
for result in results:
|
| 31 |
+
for box in result.boxes:
|
| 32 |
+
x1, y1, x2, y2 = map(int, box.xyxy[0])
|
| 33 |
+
label = result.names[int(box.cls[0])]
|
| 34 |
+
conf = box.conf[0].item()
|
| 35 |
+
|
| 36 |
+
# Draw bounding box
|
| 37 |
+
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 38 |
+
cv2.putText(frame, f"{label} {conf:.2f}", (x1, y1 - 10),
|
| 39 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
|
| 40 |
+
|
| 41 |
+
# Encode frame as JPEG
|
| 42 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
| 43 |
+
frame_bytes = buffer.tobytes()
|
| 44 |
+
|
| 45 |
+
yield (b'--frame\r\n'
|
| 46 |
+
b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
|
| 47 |
+
|
| 48 |
+
cap.release()
|
| 49 |
+
|
| 50 |
+
@app.route('/', methods=['GET', 'POST'])
|
| 51 |
+
def index():
|
| 52 |
+
global IP_WEBCAM_URL
|
| 53 |
+
if request.method == 'POST':
|
| 54 |
+
IP_WEBCAM_URL = request.form['ip_url']
|
| 55 |
+
return render_template('index.html', ip_url=IP_WEBCAM_URL)
|
| 56 |
+
|
| 57 |
+
@app.route('/video_feed')
|
| 58 |
+
def video_feed():
|
| 59 |
+
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
|
| 60 |
+
|
| 61 |
+
if __name__ == '__main__':
|
| 62 |
+
app.run(host="0.0.0.0", port=5000, debug=True)
|