From 96352cc8acad88690164bfe5183ec34225a1c1de Mon Sep 17 00:00:00 2001 From: ariskadatabisnis Date: Thu, 19 Nov 2026 13:30:34 +0700 Subject: [PATCH] modified-obb --- main-obb.py | 179 +++++++++++++++++++++------------ receipts/receipts.jsonl | 15 +++ review-receipts/receipts.jsonl | 15 +++ 3 files changed, 145 insertions(+), 64 deletions(-) create mode 100644 receipts/receipts.jsonl create mode 100644 review-receipts/receipts.jsonl diff --git a/main-obb.py b/main-obb.py index e93c7ab..24e11cc 100644 --- a/main-obb.py +++ b/main-obb.py @@ -15,10 +15,8 @@ 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") -# Will be initialized in init_context 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 @@ -51,7 +49,8 @@ class Yolov9OBB: self.colors = [] np.random.seed(42) - for i in range(len(class_names)): + 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) @@ -73,25 +72,66 @@ class Yolov9OBB: return new_im, delta_w, delta_h, ratio - def predict(self, img): - input_tensor = np.expand_dims(img, 0) + 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}") - infer_request = self.compiled_model.create_infer_request() - infer_request.infer({0: input_tensor}) - - output = infer_request.get_output_tensor() - detections = output.data[0].T + 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:] - _, _, _, max_indx = cv2.minMaxLoc(classes_scores) - class_id = max_indx[1] + if len(classes_scores) == 0: + continue + + class_id = int(np.argmax(classes_scores)) if classes_scores[class_id] > self.conf_thresh: - confidences.append(classes_scores[class_id]) + confidences.append(float(classes_scores[class_id])) class_ids.append(class_id) x, y, w, h, angle = ( prediction[0].item(), @@ -104,6 +144,9 @@ class Yolov9OBB: 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 @@ -119,9 +162,17 @@ class Yolov9OBB: "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"] @@ -131,7 +182,6 @@ class Yolov9OBB: cx, cy, w, h, angle_rad = box angle_deg = angle_rad * 180 / math.pi - # Scale back to original image rx = img.shape[1] / (self.input_width - dw) ry = img.shape[0] / (self.input_height - dh) cx = cx * rx @@ -174,16 +224,10 @@ class Yolov9OBB: return points.astype(int).tolist() - def init_context(context): - """Nuclio init_context – called once per container. - - Loads the IR model and compiles it for the CPU. - """ global coconame context.logger.info("Init context OBB ----> 0%") - # Load class names try: with open(CLASSES_FILE, 'r') as f: classes_data = json.load(f) @@ -197,7 +241,6 @@ def init_context(context): context.user_data.model = model context.logger.info("Init context OBB ----> 100%") - def handler(context, event): context.logger.info("Run OpenVINO YOLOv9-OBB model") @@ -212,48 +255,56 @@ def handler(context, event): content_type="application/json", ) - 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") + 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({"error": "Failed to decode image"}), - status_code=400, + 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", ) - - 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"] # [cx, cy, w, h, angle_rad] - - 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, - ) diff --git a/receipts/receipts.jsonl b/receipts/receipts.jsonl new file mode 100644 index 0000000..a8d013e --- /dev/null +++ b/receipts/receipts.jsonl @@ -0,0 +1,15 @@ +{"tool":"","request_id":"tu-1795060224260-yl89","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060228709-h09d","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060232399-ykuo","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060236194-0m8y","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060240601-703s","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060244557-vt5l","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060251675-grxw","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060264135-lm3r","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060307104-0ra3","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060310439-i8nt","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060314283-h61o","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060363747-lpvx","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060371965-lmyv","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795061737171-cnjq","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795061747894-lu21","signed":false,"note":"no signer configured"} diff --git a/review-receipts/receipts.jsonl b/review-receipts/receipts.jsonl new file mode 100644 index 0000000..350c969 --- /dev/null +++ b/review-receipts/receipts.jsonl @@ -0,0 +1,15 @@ +{"tool":"","request_id":"tu-1795060224254-a9ke","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060228714-p7iz","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060232393-8cv1","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060236180-cnc5","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060240599-64cw","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060244549-bvu6","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060251660-o8no","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060264129-tft7","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060307118-mxue","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060310443-ruga","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060314268-by9l","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060363747-jazi","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795060371944-58zn","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795061737191-q3gw","signed":false,"note":"no signer configured"} +{"tool":"","request_id":"tu-1795061747888-0ga4","signed":false,"note":"no signer configured"}