forked from dsutanto/nuclio-handler
311 lines
10 KiB
Python
311 lines
10 KiB
Python
import base64
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import openvino as ov
|
|
from openvino.preprocess import PrePostProcessor
|
|
from openvino.preprocess import ColorFormat
|
|
from openvino import Layout, Type
|
|
|
|
MODEL_XML = os.getenv("MODEL_XML", "/models/best.xml")
|
|
MODEL_BIN = os.getenv("MODEL_BIN", "/models/best.bin")
|
|
CLASSES_FILE = os.getenv("CLASSES_FILE", "/opt/nuclio/classes.json")
|
|
|
|
coconame = []
|
|
|
|
class Yolov9OBB:
|
|
def __init__(
|
|
self, xml_model_path=MODEL_XML, bin_model_path=MODEL_BIN, conf=0.1, nms=0.4, class_names=None
|
|
):
|
|
core = ov.Core()
|
|
if bin_model_path:
|
|
model = core.read_model(
|
|
str(Path(xml_model_path)), str(Path(bin_model_path))
|
|
)
|
|
else:
|
|
model = core.read_model(str(Path(xml_model_path)))
|
|
|
|
ppp = PrePostProcessor(model)
|
|
ppp.input().tensor().set_element_type(Type.u8).set_layout(
|
|
Layout("NHWC")
|
|
).set_color_format(ColorFormat.BGR)
|
|
ppp.input().preprocess().convert_element_type(Type.f32).convert_color(
|
|
ColorFormat.RGB
|
|
).scale([255.0, 255.0, 255.0])
|
|
ppp.input().model().set_layout(Layout("NCHW"))
|
|
ppp.output().tensor().set_element_type(Type.f32)
|
|
model = ppp.build()
|
|
|
|
self.compiled_model = core.compile_model(model, "CPU")
|
|
|
|
self.input_width = 320
|
|
self.input_height = 320
|
|
self.conf_thresh = conf
|
|
self.nms_thresh = nms
|
|
self.colors = []
|
|
|
|
np.random.seed(42)
|
|
num_classes = len(class_names) if class_names else 0
|
|
for i in range(num_classes):
|
|
color = tuple(np.random.randint(100, 256, size=3))
|
|
self.colors.append(color)
|
|
|
|
def resize_and_pad(self, image):
|
|
old_h, old_w = image.shape[:2]
|
|
ratio = min(self.input_width / old_w, self.input_height / old_h)
|
|
new_w = int(old_w * ratio)
|
|
new_h = int(old_h * ratio)
|
|
|
|
image = cv2.resize(image, (new_w, new_h))
|
|
|
|
delta_w = self.input_width - new_w
|
|
delta_h = self.input_height - new_h
|
|
|
|
color = [100, 100, 100]
|
|
new_im = cv2.copyMakeBorder(
|
|
image, 0, delta_h, 0, delta_w, cv2.BORDER_CONSTANT, value=color
|
|
)
|
|
|
|
return new_im, delta_w, delta_h, ratio
|
|
|
|
def parse_output(self, output_tensor):
|
|
"""Parse model output handling both [N, 5+C] and [5+C, N] formats."""
|
|
data = output_tensor.data[0] # Remove batch dim
|
|
|
|
# Handle end2end format: [1, 300, 6] -> x1,y1,x2,y2,conf,cls
|
|
if len(data.shape) == 3 and data.shape[0] == 1 and data.shape[2] == 6:
|
|
# End2end format - already decoded boxes
|
|
dets = data[0] # [300, 6]
|
|
results = []
|
|
for det in dets:
|
|
x1, y1, x2, y2, conf, cls_id = det
|
|
if conf > self.conf_thresh:
|
|
cx = (x1 + x2) / 2
|
|
cy = (y1 + y2) / 2
|
|
w = x2 - x1
|
|
h = y2 - y1
|
|
angle = 0.0 # End2end doesn't provide angle
|
|
results.append({
|
|
"class_index": int(cls_id),
|
|
"confidence": float(conf),
|
|
"box": np.array([cx, cy, w, h, angle]),
|
|
})
|
|
return results
|
|
|
|
# Standard format: determine if [N, 5+C] or [5+C, N]
|
|
if len(data.shape) == 2:
|
|
expected_features = 5 + (len(self.colors) if self.colors else 0)
|
|
# Heuristic: the dimension matching expected_features is the feature dim
|
|
if data.shape[1] == expected_features:
|
|
detections = data # [N, 5+C] - correct
|
|
elif data.shape[0] == expected_features:
|
|
detections = data.T # [5+C, N] -> transpose
|
|
else:
|
|
# Fallback: assume larger dim is num_detections
|
|
if data.shape[0] > data.shape[1]:
|
|
detections = data
|
|
else:
|
|
detections = data.T
|
|
else:
|
|
raise ValueError(f"Unexpected output shape: {data.shape}")
|
|
|
|
return self._parse_detections(detections)
|
|
|
|
def _parse_detections(self, detections):
|
|
"""Parse detections in [N, 5+C] format."""
|
|
boxes = []
|
|
class_ids = []
|
|
confidences = []
|
|
angles = []
|
|
|
|
for prediction in detections:
|
|
if len(prediction) < 5:
|
|
continue
|
|
classes_scores = prediction[5:]
|
|
if len(classes_scores) == 0:
|
|
continue
|
|
|
|
class_id = int(np.argmax(classes_scores))
|
|
if classes_scores[class_id] > self.conf_thresh:
|
|
confidences.append(float(classes_scores[class_id]))
|
|
class_ids.append(class_id)
|
|
x, y, w, h, angle = (
|
|
prediction[0].item(),
|
|
prediction[1].item(),
|
|
prediction[2].item(),
|
|
prediction[3].item(),
|
|
prediction[4].item(),
|
|
)
|
|
box = np.array([x, y, w, h, angle])
|
|
boxes.append(box)
|
|
angles.append(angle)
|
|
|
|
if not boxes:
|
|
return []
|
|
|
|
indexes = cv2.dnn.NMSBoxesRotated(
|
|
[cv2.RotatedRect((b[0], b[1]), (b[2], b[3]), b[4] * 180 / math.pi) for b in boxes],
|
|
confidences, self.conf_thresh, self.nms_thresh
|
|
)
|
|
|
|
results = []
|
|
for i in indexes:
|
|
j = i.item()
|
|
results.append(
|
|
{
|
|
"class_index": class_ids[j],
|
|
"confidence": confidences[j],
|
|
"box": boxes[j],
|
|
}
|
|
)
|
|
return results
|
|
|
|
def predict(self, img):
|
|
input_tensor = np.expand_dims(img, 0)
|
|
|
|
infer_request = self.compiled_model.create_infer_request()
|
|
infer_request.infer({0: input_tensor})
|
|
|
|
output = infer_request.get_output_tensor()
|
|
return self.parse_output(output)
|
|
|
|
def draw(self, img, detections, dw, dh):
|
|
for detection in detections:
|
|
box = detection["box"]
|
|
classId = detection["class_index"]
|
|
confidence = detection["confidence"]
|
|
|
|
cx, cy, w, h, angle_rad = box
|
|
angle_deg = angle_rad * 180 / math.pi
|
|
|
|
rx = img.shape[1] / (self.input_width - dw)
|
|
ry = img.shape[0] / (self.input_height - dh)
|
|
cx = cx * rx
|
|
cy = cy * ry
|
|
w = w * rx
|
|
h = h * ry
|
|
|
|
rect = ((cx, cy), (w, h), angle_deg)
|
|
box_points = cv2.boxPoints(rect).astype(int)
|
|
cv2.drawContours(img, [box_points], 0, tuple(map(int, self.colors[classId])), 3)
|
|
|
|
class_string = coconame[classId] + " " + str(confidence)[:4]
|
|
cv2.putText(
|
|
img,
|
|
class_string,
|
|
(int(cx) + 5, int(cy) - 10),
|
|
cv2.FONT_HERSHEY_DUPLEX,
|
|
1,
|
|
(0, 0, 0),
|
|
2,
|
|
cv2.LINE_AA,
|
|
)
|
|
|
|
def obb_to_points(self, box, dw, dh, orig_w, orig_h):
|
|
cx, cy, w, h, angle_rad = box
|
|
angle_deg = angle_rad * 180 / math.pi
|
|
|
|
rx = orig_w / (self.input_width - dw)
|
|
ry = orig_h / (self.input_height - dh)
|
|
cx = cx * rx
|
|
cy = cy * ry
|
|
w = w * rx
|
|
h = h * ry
|
|
|
|
rect = ((cx, cy), (w, h), angle_deg)
|
|
points = cv2.boxPoints(rect)
|
|
|
|
points[:, 0] = np.clip(points[:, 0], 0, orig_w)
|
|
points[:, 1] = np.clip(points[:, 1], 0, orig_h)
|
|
|
|
return points.astype(int).tolist()
|
|
|
|
def init_context(context):
|
|
global coconame
|
|
context.logger.info("Init context OBB ----> 0%")
|
|
|
|
try:
|
|
with open(CLASSES_FILE, 'r') as f:
|
|
classes_data = json.load(f)
|
|
coconame = [cls['name'] for cls in sorted(classes_data, key=lambda x: x['id'])]
|
|
context.logger.info(f"Loaded {len(coconame)} classes")
|
|
except Exception as exc:
|
|
context.logger.error(f"Failed to load classes from {CLASSES_FILE}: {exc}")
|
|
coconame = []
|
|
|
|
model = Yolov9OBB(MODEL_XML, MODEL_BIN, conf=0.1, nms=0.4, class_names=coconame)
|
|
context.user_data.model = model
|
|
context.logger.info("Init context OBB ----> 100%")
|
|
|
|
def handler(context, event):
|
|
context.logger.info("Run OpenVINO YOLOv9-OBB model")
|
|
|
|
try:
|
|
data = event.body
|
|
image_b64 = data["image"]
|
|
except Exception as exc:
|
|
context.logger.error(f"Invalid request body: {exc}")
|
|
return context.Response(
|
|
body=json.dumps({"error": "Invalid request body"}),
|
|
status_code=400,
|
|
content_type="application/json",
|
|
)
|
|
|
|
try:
|
|
image_bytes = base64.b64decode(image_b64)
|
|
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
|
|
if image is None:
|
|
context.logger.error("Failed to decode image")
|
|
return context.Response(
|
|
body=json.dumps({"error": "Failed to decode image"}),
|
|
status_code=400,
|
|
content_type="application/json",
|
|
)
|
|
|
|
model = context.user_data.model
|
|
|
|
img_resized, dw, dh, ratio = model.resize_and_pad(image)
|
|
|
|
detections = model.predict(img_resized)
|
|
|
|
shapes = []
|
|
for detection in detections:
|
|
class_id = detection["class_index"]
|
|
confidence = float(detection["confidence"])
|
|
box = detection["box"]
|
|
|
|
points = model.obb_to_points(box, dw, dh, image.shape[1], image.shape[0])
|
|
|
|
flat_points = [coord for point in points for coord in point]
|
|
|
|
label = coconame[class_id] if class_id < len(coconame) else "unknown"
|
|
|
|
shapes.append(
|
|
{
|
|
"label": label,
|
|
"points": flat_points,
|
|
"type": "polygon",
|
|
"confidence": str(confidence),
|
|
}
|
|
)
|
|
|
|
context.logger.info(f"Detected {len(shapes)} OBB objects")
|
|
|
|
return context.Response(
|
|
body=json.dumps(shapes),
|
|
headers={},
|
|
content_type="application/json",
|
|
status_code=200,
|
|
)
|
|
except Exception as exc:
|
|
context.logger.error(f"Inference error: {exc}")
|
|
return context.Response(
|
|
body=json.dumps({"error": f"Inference failed: {str(exc)}"}),
|
|
status_code=500,
|
|
content_type="application/json",
|
|
)
|