forked from cvat-ai/cvat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
40 lines (34 loc) · 1.22 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
import json
import base64
from PIL import Image
import io
import torch
def init_context(context):
context.logger.info("Init context... 0%")
# Read the DL model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5m, yolov5l, yolov5x, custom
context.user_data.model = model
context.logger.info("Init context...100%")
def handler(context, event):
context.logger.info("Run yolo-v5 model")
data = event.body
buf = io.BytesIO(base64.b64decode(data["image"]))
threshold = float(data.get("threshold", 0.5))
context.user_data.model.conf = threshold
image = Image.open(buf)
yolo_results_json = context.user_data.model(image).pandas().xyxy[0].to_dict(orient='records')
encoded_results = []
for result in yolo_results_json:
encoded_results.append({
'confidence': result['confidence'],
'label': result['name'],
'points': [
result['xmin'],
result['ymin'],
result['xmax'],
result['ymax']
],
'type': 'rectangle'
})
return context.Response(body=json.dumps(encoded_results), headers={},
content_type='application/json', status_code=200)