-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_roboflow
More file actions
141 lines (115 loc) · 5.11 KB
/
model_roboflow
File metadata and controls
141 lines (115 loc) · 5.11 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
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
from flask import Flask, render_template, Response
import cv2
from roboflow import Roboflow
import threading
import requests
from datetime import datetime
import os
import time # 추가
# Roboflow API details
rf = Roboflow(api_key="Us3HvvWPK0OOkKDkROrX")
project = rf.workspace().project("road-damage-det")
model = project.version(2).model
# Global variables for inference result and submission time
global inference_result
inference_result = None
last_submission_time = 0 # 마지막 POST 요청 시간을 추적할 변수
# Flask app setup
app = Flask(__name__)
@app.route('/')
def index():
# Render index.html (기본 페이지 설정)
return render_template('index.html')
def async_infer(img_path):
"""비동기적으로 Roboflow API를 호출하여 추론을 처리하는 함수"""
global inference_result, last_submission_time
result = model.predict(img_path, confidence=40, overlap=30).json()
inference_result = result # 추론 결과를 전역 변수에 저장
print(inference_result)
# 현재 시간을 가져옴
current_time = time.time()
# Check if any predictions exceed confidence threshold and 2 seconds have passed since last POST
if current_time - last_submission_time >= 2: # 2초 경과 확인
for prediction in result.get('predictions', []):
if prediction['confidence'] >= 0.47:
# Pothole detected, submit form with image
submit_form({
'hazardType': '포트홀',
'dates': datetime.now().strftime("%Y-%m-%d"),
'hazardImage': img_path,
'gps': '36.6252,127.4571', # Example GPS coordinates
'state': '미조치'
})
# Update the last submission time
last_submission_time = current_time
break # Once a submission is made, stop further checks
def draw_inference(frame, result):
"""Draw inference results on the frame (only for confidence 0.47 and above)"""
for prediction in result['predictions']:
if prediction['confidence'] >= 0.47:
x, y, width, height = prediction['x'], prediction['y'], prediction['width'], prediction['height']
label = prediction['class']
# Draw bounding box
top_left = (int(x - width / 2), int(y - height / 2))
bottom_right = (int(x + width / 2), int(y + height / 2))
cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)
# Draw label
cv2.putText(frame, label, (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)
def get_frame():
# Get video stream from the camera
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
frame_count = 0
while True:
_, frame = cap.read()
frame_count += 1
# Perform inference every second frame
if frame_count % 2 == 0:
img_path = 'current_frame.jpg'
cv2.imwrite(img_path, frame)
# Asynchronously request inference
threading.Thread(target=async_infer, args=(img_path,)).start()
# Overlay inference results
if inference_result and 'predictions' in inference_result:
draw_inference(frame, inference_result)
# Encode frame to be sent to the browser
imgencode = cv2.imencode('.jpg', frame)[1]
stringData = imgencode.tobytes()
yield (b'--frame\r\n'
b'Content-Type: text/plain\r\n\r\n' + stringData + b'\r\n')
# Release video capture
del(cap)
@app.route('/calc')
def calc():
# Return the video stream as a response
return Response(get_frame(),
mimetype='multipart/x-mixed-replace; boundary=frame')
def submit_form(form):
"""Send the detected pothole image and metadata to the API"""
if not form.get('hazardType') or not form.get('dates') or not form.get('hazardImage') or not form.get('gps') or not form.get('state'):
print("모든 필드를 입력해주세요.")
return
try:
form_data = {
'hazardType': form['hazardType'],
'gps': form['gps'],
'state': form['state'],
'dates': datetime.strptime(form['dates'], "%Y-%m-%d").isoformat()
}
# Specify the file path in the current directory
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, form['hazardImage'])
files = {'photo': open(file_path, 'rb')}
# Send the POST request
response = requests.post('http://192.168.0.106/api/hazarddata/add', data=form_data, files=files)
# Process the response
if response.status_code == 200:
print('위험물이 등록되었습니다.')
else:
print(f"Error: {response.status_code} - {response.text}")
except Exception as e:
print(f"Error submitting form: {str(e)}")
if __name__ == '__main__':
# Run the Flask app
app.run(host='0.0.0.0', debug=True, threaded=True)