CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/utils/flask_rest_api/restapi.py
Views: 475
1
"""
2
Run a rest API exposing the yolov5s object detection model
3
"""
4
import argparse
5
import io
6
7
import torch
8
from flask import Flask, request
9
from PIL import Image
10
11
app = Flask(__name__)
12
13
DETECTION_URL = "/v1/object-detection/yolov5s"
14
15
16
@app.route(DETECTION_URL, methods=["POST"])
17
def predict():
18
if not request.method == "POST":
19
return
20
21
if request.files.get("image"):
22
image_file = request.files["image"]
23
image_bytes = image_file.read()
24
25
img = Image.open(io.BytesIO(image_bytes))
26
27
results = model(img, size=640) # reduce size=320 for faster inference
28
return results.pandas().xyxy[0].to_json(orient="records")
29
30
31
if __name__ == "__main__":
32
parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
33
parser.add_argument("--port", default=5000, type=int, help="port number")
34
args = parser.parse_args()
35
36
model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache
37
app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat
38
39