forked from dsutanto/nuclio-handler
add-obb
This commit is contained in:
1 parent
c595c9102f
commit
28085cc9cb
1 file changed
+2
-48
+2
-48
@@ -1,12 +1,3 @@
|
||||
"""Nuclio handler for CVAT automatic annotation using OpenVINO 2025 IR (.xml/.bin) with OBB (Oriented Bounding Box) support.
|
||||
|
||||
This file extends the YOLOv9 inference logic with OBB detection capability.
|
||||
It loads an OpenVINO Intermediate Representation (IR) model consisting of a
|
||||
``.xml`` file (network topology) and a ``.bin`` file (weights).
|
||||
|
||||
Adjust ``MODEL_XML`` and ``MODEL_BIN`` if your files are located elsewhere.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import math
|
||||
@@ -20,11 +11,9 @@ from openvino.preprocess import PrePostProcessor
|
||||
from openvino.preprocess import ColorFormat
|
||||
from openvino import Layout, Type
|
||||
|
||||
# Paths to the IR model files – change if your model is in a different location.
|
||||
MODEL_XML = os.getenv("MODEL_XML", "/models/best.xml")
|
||||
MODEL_BIN = os.getenv("MODEL_BIN", "/models/best.bin")
|
||||
|
||||
# Read class names from JSON file
|
||||
classes_file = os.getenv("CLASSES_FILE", "/opt/nuclio/classes.json")
|
||||
with open(classes_file, 'r') as f:
|
||||
classes_data = json.load(f)
|
||||
@@ -35,9 +24,7 @@ class Yolov9OBB:
|
||||
def __init__(
|
||||
self, xml_model_path=MODEL_XML, bin_model_path=MODEL_BIN, conf=0.1, nms=0.4
|
||||
):
|
||||
# Step 1. Initialize OpenVINO Runtime core
|
||||
core = ov.Core()
|
||||
# Step 2. Read a model
|
||||
if bin_model_path:
|
||||
model = core.read_model(
|
||||
str(Path(xml_model_path)), str(Path(bin_model_path))
|
||||
@@ -45,21 +32,15 @@ class Yolov9OBB:
|
||||
else:
|
||||
model = core.read_model(str(Path(xml_model_path)))
|
||||
|
||||
# Step 3. Initialize Preprocessing for the model
|
||||
ppp = PrePostProcessor(model)
|
||||
# Specify input image format
|
||||
ppp.input().tensor().set_element_type(Type.u8).set_layout(
|
||||
Layout("NHWC")
|
||||
).set_color_format(ColorFormat.BGR)
|
||||
# Specify preprocess pipeline to input image without resizing
|
||||
ppp.input().preprocess().convert_element_type(Type.f32).convert_color(
|
||||
ColorFormat.RGB
|
||||
).scale([255.0, 255.0, 255.0])
|
||||
# Specify model's input layout
|
||||
ppp.input().model().set_layout(Layout("NCHW"))
|
||||
# Specify output results format
|
||||
ppp.output().tensor().set_element_type(Type.f32)
|
||||
# Embed above steps in the graph
|
||||
model = ppp.build()
|
||||
|
||||
self.compiled_model = core.compile_model(model, "CPU")
|
||||
@@ -70,7 +51,6 @@ class Yolov9OBB:
|
||||
self.nms_thresh = nms
|
||||
self.colors = []
|
||||
|
||||
# Create random colors
|
||||
np.random.seed(42)
|
||||
for i in range(len(coconame)):
|
||||
color = tuple(np.random.randint(100, 256, size=3))
|
||||
@@ -95,24 +75,20 @@ class Yolov9OBB:
|
||||
return new_im, delta_w, delta_h, ratio
|
||||
|
||||
def predict(self, img):
|
||||
# Step 4. Create tensor from image
|
||||
input_tensor = np.expand_dims(img, 0)
|
||||
|
||||
# Step 5. Create an infer request for model inference
|
||||
infer_request = self.compiled_model.create_infer_request()
|
||||
infer_request.infer({0: input_tensor})
|
||||
|
||||
# Step 6. Retrieve inference results
|
||||
output = infer_request.get_output_tensor()
|
||||
detections = output.data[0].T
|
||||
|
||||
# Step 7. Postprocessing for OBB (5 params: x, y, w, h, angle)
|
||||
boxes = []
|
||||
class_ids = []
|
||||
confidences = []
|
||||
angles = []
|
||||
for prediction in detections:
|
||||
classes_scores = prediction[5:] # OBB: x,y,w,h,angle + classes
|
||||
classes_scores = prediction[5:]
|
||||
_, _, _, max_indx = cv2.minMaxLoc(classes_scores)
|
||||
class_id = max_indx[1]
|
||||
if classes_scores[class_id] > self.conf_thresh:
|
||||
@@ -125,7 +101,6 @@ class Yolov9OBB:
|
||||
prediction[3].item(),
|
||||
prediction[4].item(),
|
||||
)
|
||||
# Store as [x, y, w, h, angle] - center format with angle in radians
|
||||
box = np.array([x, y, w, h, angle])
|
||||
boxes.append(box)
|
||||
angles.append(angle)
|
||||
@@ -142,7 +117,7 @@ class Yolov9OBB:
|
||||
{
|
||||
"class_index": class_ids[j],
|
||||
"confidence": confidences[j],
|
||||
"box": boxes[j], # [cx, cy, w, h, angle_rad]
|
||||
"box": boxes[j],
|
||||
}
|
||||
)
|
||||
|
||||
@@ -165,12 +140,10 @@ class Yolov9OBB:
|
||||
w = w * rx
|
||||
h = h * ry
|
||||
|
||||
# Draw rotated rectangle
|
||||
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)
|
||||
|
||||
# Label
|
||||
class_string = coconame[classId] + " " + str(confidence)[:4]
|
||||
cv2.putText(
|
||||
img,
|
||||
@@ -184,7 +157,6 @@ class Yolov9OBB:
|
||||
)
|
||||
|
||||
def obb_to_points(self, box, dw, dh, orig_w, orig_h):
|
||||
"""Convert OBB [cx, cy, w, h, angle_rad] to 4 corner points in original image coordinates."""
|
||||
cx, cy, w, h, angle_rad = box
|
||||
angle_deg = angle_rad * 180 / math.pi
|
||||
|
||||
@@ -198,7 +170,6 @@ class Yolov9OBB:
|
||||
rect = ((cx, cy), (w, h), angle_deg)
|
||||
points = cv2.boxPoints(rect)
|
||||
|
||||
# Clip to image bounds
|
||||
points[:, 0] = np.clip(points[:, 0], 0, orig_w)
|
||||
points[:, 1] = np.clip(points[:, 1], 0, orig_h)
|
||||
|
||||
@@ -206,10 +177,6 @@ class Yolov9OBB:
|
||||
|
||||
|
||||
def init_context(context):
|
||||
"""Nuclio init_context – called once per container.
|
||||
|
||||
Loads the IR model and compiles it for the CPU.
|
||||
"""
|
||||
context.logger.info("Init context OBB ----> 0%")
|
||||
model = Yolov9OBB(MODEL_XML, MODEL_BIN, conf=0.1, nms=0.4)
|
||||
context.user_data.model = model
|
||||
@@ -217,14 +184,8 @@ def init_context(context):
|
||||
|
||||
|
||||
def handler(context, event):
|
||||
"""Nuclio handler – called for every request.
|
||||
|
||||
Expects a JSON body with a base‑64 encoded image under the key ``"image"``.
|
||||
Returns a CVAT‑compatible JSON with detected OBB objects (4 corner points).
|
||||
"""
|
||||
context.logger.info("Run OpenVINO YOLOv9-OBB model")
|
||||
|
||||
# Parse request body
|
||||
try:
|
||||
data = event.body
|
||||
image_b64 = data["image"]
|
||||
@@ -236,7 +197,6 @@ def handler(context, event):
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
# Decode image
|
||||
image_bytes = base64.b64decode(image_b64)
|
||||
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
if image is None:
|
||||
@@ -247,26 +207,20 @@ def handler(context, event):
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
# Get model from context
|
||||
model = context.user_data.model
|
||||
|
||||
# Preprocess: resize and pad
|
||||
img_resized, dw, dh, ratio = model.resize_and_pad(image)
|
||||
|
||||
# Inference
|
||||
detections = model.predict(img_resized)
|
||||
|
||||
# Convert detections to CVAT-compatible format (polygon with 4 points)
|
||||
shapes = []
|
||||
for detection in detections:
|
||||
class_id = detection["class_index"]
|
||||
confidence = float(detection["confidence"])
|
||||
box = detection["box"] # [cx, cy, w, h, angle_rad]
|
||||
|
||||
# Convert to 4 corner points
|
||||
points = model.obb_to_points(box, dw, dh, image.shape[1], image.shape[0])
|
||||
|
||||
# Flatten points for CVAT format: [x1, y1, x2, y2, x3, y3, x4, y4]
|
||||
flat_points = [coord for point in points for coord in point]
|
||||
|
||||
label = coconame[class_id] if class_id < len(coconame) else "unknown"
|
||||
|
||||
Reference in new issue
Block a user