Create handler.py
Browse files- handler.py +46 -0
handler.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from ultralytics import YOLO
|
| 3 |
+
|
| 4 |
+
class EndpointHandler():
|
| 5 |
+
def __init__(self, path=""):
|
| 6 |
+
# Preload all the elements you are going to need at inference.
|
| 7 |
+
# pseudo:
|
| 8 |
+
# self.model= load_model(path)
|
| 9 |
+
yolov8_model_name = 'yolov8_2023-07-19_yolov8m.pt'
|
| 10 |
+
self.model = YOLO(yolov8_model_name)
|
| 11 |
+
|
| 12 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 13 |
+
"""
|
| 14 |
+
data args:
|
| 15 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
| 16 |
+
kwargs
|
| 17 |
+
Return:
|
| 18 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
| 19 |
+
"""
|
| 20 |
+
# Get the prediction
|
| 21 |
+
result = self.model(data['inputs'])
|
| 22 |
+
# Get the original image with channel shifted
|
| 23 |
+
img = result[0].orig_img[:,:,::-1]
|
| 24 |
+
H, W, _ = img.shape
|
| 25 |
+
annotated = img.copy()
|
| 26 |
+
# Modify crop so that it is square
|
| 27 |
+
try:
|
| 28 |
+
x1, y1, x2, y2 = result[0].boxes.xyxy.numpy().astype('int')[0]
|
| 29 |
+
if result[0].boxes.conf[0].item() < 0.75: # if low in confidence
|
| 30 |
+
x1, y1, x2, y2 = 0, 0, W, H
|
| 31 |
+
else:
|
| 32 |
+
annotated = result[0].plot(labels=False, conf=False)[:,:,::-1]
|
| 33 |
+
except: # in case there is no detection
|
| 34 |
+
x1, y1, x2, y2 = 0, 0, W, H
|
| 35 |
+
|
| 36 |
+
h, w = y2-y1, x2-x1
|
| 37 |
+
offset = abs(h-w) // 2
|
| 38 |
+
if h > w:
|
| 39 |
+
x1 = max(x1 - offset, 0)
|
| 40 |
+
x2 = min(x2 + offset, W)
|
| 41 |
+
else:
|
| 42 |
+
y1 = max(y1 - offset, 0)
|
| 43 |
+
y2 = min(y2 + offset, H)
|
| 44 |
+
new_image = img[y1:y2, x1:x2]
|
| 45 |
+
# Return the annotated original image with the square cropped
|
| 46 |
+
return annotated, new_image
|