#!/usr/bin/env python3 """OpenVINO inference CLI for the Klyff PCB defect detector.""" from __future__ import annotations import argparse import json from dataclasses import asdict, dataclass from pathlib import Path from typing import Sequence import cv2 import numpy as np import openvino as ov ROOT = Path(__file__).resolve().parent DEFAULT_MODEL = ROOT / "artifacts" / "model.xml" DEFAULT_MODEL_PROC = ROOT / "artifacts" / "model-proc.json" @dataclass(frozen=True) class Detection: class_id: int label: str confidence: float box_xyxy: tuple[float, float, float, float] def load_labels(model_proc_path: Path) -> list[str]: config = json.loads(model_proc_path.read_text(encoding="utf-8")) labels = config["output_postproc"][0]["labels"] if not isinstance(labels, list) or not labels or not all(isinstance(x, str) for x in labels): raise ValueError(f"Expected a non-empty label list in {model_proc_path}") return labels def letterbox(image: np.ndarray, size: int = 640) -> tuple[np.ndarray, float, tuple[int, int]]: height, width = image.shape[:2] scale = min(size / height, size / width) resized_width, resized_height = round(width * scale), round(height * scale) resized = cv2.resize(image, (resized_width, resized_height), interpolation=cv2.INTER_LINEAR) pad_width, pad_height = size - resized_width, size - resized_height left, top = pad_width // 2, pad_height // 2 padded = cv2.copyMakeBorder( resized, top, pad_height - top, left, pad_width - left, cv2.BORDER_CONSTANT, value=(114, 114, 114), ) tensor = padded[:, :, ::-1].transpose(2, 0, 1) return np.ascontiguousarray(tensor, dtype=np.float32)[None] / 255.0, scale, (left, top) def box_iou(one: np.ndarray, many: np.ndarray) -> np.ndarray: intersection = np.prod( np.maximum(np.minimum(one[2:], many[:, 2:]) - np.maximum(one[:2], many[:, :2]), 0), axis=1 ) one_area = np.prod(np.maximum(one[2:] - one[:2], 0)) many_area = np.prod(np.maximum(many[:, 2:] - many[:, :2], 0), axis=1) return intersection / np.maximum(one_area + many_area - intersection, 1e-9) def class_aware_nms(boxes: np.ndarray, scores: np.ndarray, class_ids: np.ndarray, threshold: float) -> list[int]: kept: list[int] = [] for class_id in np.unique(class_ids): candidates = np.flatnonzero(class_ids == class_id) order = candidates[np.argsort(scores[candidates])[::-1]] while order.size: current = int(order[0]) kept.append(current) if order.size == 1: break remaining = order[1:] order = remaining[box_iou(boxes[current], boxes[remaining]) <= threshold] return sorted(kept, key=lambda index: float(scores[index]), reverse=True) def decode(output: np.ndarray, labels: Sequence[str], image_shape: tuple[int, int], scale: float, padding: tuple[int, int], confidence: float, iou: float) -> list[Detection]: predictions = np.squeeze(output, axis=0).T expected = 4 + len(labels) if predictions.shape[1] != expected: raise ValueError(f"Expected {expected} output channels, got {predictions.shape[1]}") class_scores = predictions[:, 4:] class_ids = class_scores.argmax(axis=1) scores = class_scores[np.arange(len(class_scores)), class_ids] selected = scores >= confidence xywh, scores, class_ids = predictions[selected, :4], scores[selected], class_ids[selected] if not xywh.size: return [] boxes = np.empty_like(xywh) boxes[:, 0] = xywh[:, 0] - xywh[:, 2] / 2 boxes[:, 1] = xywh[:, 1] - xywh[:, 3] / 2 boxes[:, 2] = xywh[:, 0] + xywh[:, 2] / 2 boxes[:, 3] = xywh[:, 1] + xywh[:, 3] / 2 boxes[:, [0, 2]] = (boxes[:, [0, 2]] - padding[0]) / scale boxes[:, [1, 3]] = (boxes[:, [1, 3]] - padding[1]) / scale height, width = image_shape boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, width) boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, height) return [ Detection(int(class_ids[i]), labels[int(class_ids[i])], float(scores[i]), tuple(float(value) for value in boxes[i])) for i in class_aware_nms(boxes, scores, class_ids, iou) ] class PcbAnomalyDetector: def __init__(self, model_path: Path = DEFAULT_MODEL, model_proc_path: Path = DEFAULT_MODEL_PROC, device: str = "CPU") -> None: self.labels = load_labels(model_proc_path) core = ov.Core() model = core.read_model(model=model_path) if tuple(model.input(0).shape) != (1, 3, 640, 640): raise ValueError(f"Unsupported input shape: {model.input(0).shape}") self.compiled_model = core.compile_model(model=model, device_name=device) self.output = self.compiled_model.output(0) def predict(self, image: np.ndarray, confidence: float = 0.60, iou: float = 0.70) -> list[Detection]: tensor, scale, padding = letterbox(image) result = self.compiled_model([tensor])[self.output] return decode(result, self.labels, image.shape[:2], scale, padding, confidence, iou) def annotate(image: np.ndarray, detections: Sequence[Detection]) -> np.ndarray: rendered = image.copy() for detection in detections: x1, y1, x2, y2 = (round(value) for value in detection.box_xyxy) cv2.rectangle(rendered, (x1, y1), (x2, y2), (0, 200, 255), 2) cv2.putText(rendered, f"{detection.label} {detection.confidence:.2f}", (x1, max(y1 - 7, 15)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 255), 2) return rendered def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("--model", type=Path, default=DEFAULT_MODEL) parser.add_argument("--model-proc", type=Path, default=DEFAULT_MODEL_PROC) parser.add_argument("--device", default="CPU") parser.add_argument("--confidence", type=float, default=0.60) parser.add_argument("--iou", type=float, default=0.70) parser.add_argument("--output", type=Path) args = parser.parse_args() if not 0 <= args.confidence <= 1 or not 0 <= args.iou <= 1: raise SystemExit("--confidence and --iou must be between 0 and 1") image = cv2.imread(str(args.image)) if image is None: raise SystemExit(f"Could not read image: {args.image}") detector = PcbAnomalyDetector(args.model, args.model_proc, args.device) detections = detector.predict(image, args.confidence, args.iou) print(json.dumps([asdict(item) for item in detections], indent=2)) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) if not cv2.imwrite(str(args.output), annotate(image, detections)): raise SystemExit(f"Could not write output image: {args.output}") if __name__ == "__main__": main()