forked from DanielChuDC/yolov5-fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
70 lines (59 loc) · 1.77 KB
/
main.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
from fastapi import FastAPI, File
from segmentation import get_yolov5, get_image_from_bytes
from starlette.responses import Response
import io
from PIL import Image
import json
from fastapi.middleware.cors import CORSMiddleware
model = get_yolov5()
app = FastAPI(
title="Custom YOLOV5 Machine Learning API",
description="""Obtain object value out of image
and return image and json result""",
version="0.0.1",
)
origins = [
"http://localhost",
"http://localhost:8000",
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/notify/v1/health')
def get_health():
"""
Usage on K8S
readinessProbe:
httpGet:
path: /notify/v1/health
port: 80
livenessProbe:
httpGet:
path: /notify/v1/health
port: 80
:return:
dict(msg='OK')
"""
return dict(msg='OK')
@app.post("/object-to-json")
async def detect_food_return_json_result(file: bytes = File(...)):
input_image = get_image_from_bytes(file)
results = model(input_image)
detect_res = results.pandas().xyxy[0].to_json(orient="records") # JSON img1 predictions
detect_res = json.loads(detect_res)
return {"result": detect_res}
@app.post("/object-to-img")
async def detect_food_return_base64_img(file: bytes = File(...)):
input_image = get_image_from_bytes(file)
results = model(input_image)
results.render() # updates results.imgs with boxes and labels
for img in results.imgs:
bytes_io = io.BytesIO()
img_base64 = Image.fromarray(img)
img_base64.save(bytes_io, format="jpeg")
return Response(content=bytes_io.getvalue(), media_type="image/jpeg")