-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp3.py
143 lines (113 loc) · 4.21 KB
/
app3.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
from flask import Flask, jsonify
from flask_mqtt import Mqtt
from crowd_detector import YOLOv11CrowdDetector
from fatigue_detector import YOLOv11FatigueDetector
from PIL import Image
from io import BytesIO
import cv2
import logging
import json
from datetime import datetime
import numpy as np
import base64
import time
import threading
import gc
from ultralytics import YOLO
app = Flask(__name__)
try:
crowd_detector = YOLOv11CrowdDetector()
# crowd_detector = YOLOv11FatigueDetector()
# print(crowd_detector)
# model = YOLO('yolov8n.pt')
except Exception as e:
logging.error("Gagal menginisialisasi YOLOv11CrowdDetector: %s", e)
# MQTT Configuration
app.config['MQTT_BROKER_URL'] = 'localhost'
app.config['MQTT_BROKER_PORT'] = 1883
# app.config['MQTT_USERNAME'] = ''
# app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_REFRESH_TIME'] = 1.0
# Initialize MQTT
mqtt = Mqtt(app)
# Subscription Topics
CROWD_FRAME_TOPIC = 'mqtt-crowd-frame'
FATIGUE_FRAME_TOPIC = 'mqtt-fatigue-frame'
# Publication Topics
CROWD_RESULT_TOPIC = 'mqtt-crowd-result'
FATIGUE_RESULT_TOPIC = 'mqtt-fatigue-result'
# Global variables to store latest received messages
latest_crowd_frame = None
latest_fatigue_frame = None
# Base64 to image
# Fungsi untuk Memproses Frame dari Data Base64
def process_frame(frame_data):
try:
if ',' in frame_data:
frame_data = frame_data.split(',')[1]
frame_bytes = base64.b64decode(frame_data)
frame_pil = Image.open(BytesIO(frame_bytes))
frame = cv2.cvtColor(np.array(frame_pil), cv2.COLOR_RGB2BGR)
return frame
except Exception as e:
logging.error(f"Error processing frame: {e}")
return None
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
print('Connected to MQTT Broker')
# Subscribe to topics
mqtt.subscribe(CROWD_FRAME_TOPIC)
mqtt.subscribe(FATIGUE_FRAME_TOPIC)
print(f'Subscribed to {CROWD_FRAME_TOPIC} and {FATIGUE_FRAME_TOPIC}')
@mqtt.on_message()
def handle_mqtt_message(clientt, userdata, message):
global latest_crowd_frame, latest_fatigue_frame
topic = message.topic
payload = message.payload.decode('utf-8')
try:
# parse the payload
data = json.loads(payload)
if topic == CROWD_FRAME_TOPIC:
latest_crowd_frame = data
# print(latest_crowd_frame)
# proccess frame
frame = process_frame(data)
# frame, detection_data = crowd_detector.detect_and_annotate(frame)
# fatigue_status = crowd_detector.get_fatigue_category(detection_data)
results = crowd_detector.detect_and_annotate(frame)
# num_people = len(detection_data)
# Extract relevant data from the results
detections = []
for result in results:
for box in result.boxes:
detections.append({
# 'class': model.names[int(box.cls)], # Nama kelas
'confidence': float(box.conf), # Skor kepercayaan
'box': [float(coord) for coord in box.xyxy[0].tolist()] # Koordinat bounding box
})
# process crowd frame and publish result
mqtt.publish(CROWD_RESULT_TOPIC, json.dumps({'detection_data': detections}))
elif topic == FATIGUE_FRAME_TOPIC:
latest_fatigue_frame = data
print(latest_fatigue_frame)
# frame, detection_data = crowd_detector.detect_and_annotate(frame)
# fatigue_status = crowd_detector.get_fatigue_category(detection_data)
# process fatigue frame and publish result
# fatigue_result = process_fatigue_frame(data)
# mqtt.publish(FATIGUE_RESULT_TOPIC, json.dumps(fatigue_result))
except json.JSONDecodeError:
print(f'Error decoding JSON from topic {topic}')
except Exception as e:
print(f'Error processing message from {topic}: {e}')
def process_crowd_frame(frame_data):
return {
'status': 'true',
'message': 'this is crowd frame'
}
def process_fatigue_frame(frame_data):
return {
'status': 'true',
'message': 'this is fatigue frame'
}
if __name__ == '__app__':
app.run(debug=True)