참고: Flask를 활용한 딥러닝 웹 애플리케이션 개발
Deploy your model using a Flask Web Service
flask 설치
- cmd창에서 다음과 같이 실행
pip install Flask
connect2web.py
- 기존 webcam inference code에서 웹에 맞게 수정하여 저장
from flask import Flask, render_template, Response
import cv2
from ultralytics import YOLO
import datetime
app = Flask(__name__)
WEBCAM_MODE = True
video_filepath = './DownloadVideo/test_01.mp4'
DET_CONF = 0.3
DET_IN_SIZE = 320
cap = None
if WEBCAM_MODE:
cap = cv2.VideoCapture(0)
else:
cap = cv2.VideoCapture(video_filepath)
model = YOLO("best.pt")
@app.route('/')
def index():
return render_template('index.html')
def generate_frames():
while True:
start = datetime.datetime.now()
success, frame = cap.read()
if not success:
print("웹캠 연결에 문제가 생겼습니다.")
break
if WEBCAM_MODE:
frame = cv2.flip(frame, 1)
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
result = model(img, conf=DET_CONF, verbose=False, imgsz=DET_IN_SIZE)[0]
xyxy_list = result.boxes.xyxy.to("cpu").numpy().astype("int32")
cls_list = result.boxes.cls.to("cpu").numpy().astype("int32")
conf_list = result.boxes.conf.to("cpu").numpy()
for xyxy, cls, conf in zip(xyxy_list, cls_list, conf_list):
pt1, pt2 = xyxy[:2], xyxy[2:]
txt = f"{result.names[cls]} - {conf*100:.3f}%"
cv2.rectangle(frame, pt1, pt2, color=(255, 0, 0), thickness=2)
cv2.putText(
frame,
f"ID: {tracked_objects[cls]['id']} - {txt}",
org=pt1,
fontFace=cv2.FONT_HERSHEY_COMPLEX,
fontScale=1,
color=(200, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
end = datetime.datetime.now()
total = (end - start).total_seconds()
print(f'Time to process 1 frame: {total * 1000:.0f} milliseconds')
@app.route('/video_feed')
def video_feed():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
HTML 템플릿 작성
- templates 폴더를 생성하고, 그 안에 index.html 파일을 만들고 다음과 같이 작성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Webcam Streaming</title>
</head>
<body>
<h1>Webcam Streaming with Flask</h1>
<img src="{{ url_for('video_feed') }}" width="640" height="480" style="border:1px solid #000;">
</body>
</html>
Flask 애플리케이션 실행
- 터미널 또는 명령 프롬프트에서 connect2web.py 파일이 있는 디렉토리로 이동한 후 아래 명령어를 실행
python connect2web.py
이후 브라우저에서 http://127.0.0.1:5000/에 접속하면 웹캠 스트리밍이 표시된다. 이러한 방식으로 Flask를 사용하여 파이썬 웹캠 실행 파일을 웹에서 실행할 수 있다.
동영상으로 테스트
'프로젝트 > Data_Analysis_Track_33_FinalProject' 카테고리의 다른 글
| Final project 최종 보고서(각종 문서) 및 정리 (0) | 2024.01.30 |
|---|---|
| FinalProject_10(개별 Action 수행, webcam detect + tracking기능 구현) (0) | 2024.01.25 |
| FinalProject_08(개별 Action 수행, webcam detect + tracking) (0) | 2024.01.18 |
| FinalProject_07(개별 Action 수행, AWS 학습) (0) | 2024.01.16 |
| FinalProject_06(개별 Action 수행, sequential img inference) (0) | 2024.01.12 |