-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.py
More file actions
executable file
·59 lines (47 loc) · 1.78 KB
/
Copy pathAPI.py
File metadata and controls
executable file
·59 lines (47 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from flask import Flask, request, jsonify, send_file
import cv2
import numpy as np
from ultralytics import YOLO
import io
from PIL import Image
import base64
import os
app = Flask(__name__)
# Load YOLO model
model = YOLO("./weights/yolov8_best.pt")
def process_frame(img):
results = model(img)
person_count = 0
detections = []
for result in results:
for box in result.boxes:
cls = int(box.cls[0].item())
conf = box.conf[0].item()
if cls == 0: # Class ID 0 corresponds to "person"
person_count += 1
x1, y1, x2, y2 = map(int, box.xyxy[0])
detections.append({'id': person_count, 'confidence': conf, 'bbox': [x1, y1, x2, y2]})
return {'total_persons': person_count, 'detections': detections}
@app.route('/detect', methods=['POST'])
def detect_humans():
try:
mode = request.form.get('mode', 'image')
if mode == 'image':
if 'image' not in request.files:
return jsonify({'error': 'No image file provided'}), 400
file = request.files['image']
npimg = np.frombuffer(file.read(), np.uint8)
img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)
results = process_frame(img)
response = {
'results': results,
}
return jsonify(response)
elif mode == 'live':
return jsonify({'message': 'Client should start webcam and send frames for processing'})
else:
return jsonify({'error': 'Invalid mode. Use "image" or "live"'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)