File size: 7,791 Bytes
9fdfcae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import argparse
import math
from pathlib import Path

import cv2
import numpy as np

REPO_DIR = Path(__file__).parent.parent
DEFAULT_MODEL = REPO_DIR / "model" / "best.onnx"

CLASSES = {
    0: "Body",
    1: "Lens",
    2: "System",
}

COLORS = {
    0: (76, 175, 80),
    1: (33, 150, 243),
    2: (255, 152, 0),
}


def letterbox(
    image: np.ndarray,
    imageSize: int,
    fillColor: tuple[int, int, int] = (114, 114, 114),
) -> tuple[np.ndarray, float, int, int]:
    height, width = image.shape[:2]
    scale = min(imageSize / width, imageSize / height)

    resizedWidth = int(round(width * scale))
    resizedHeight = int(round(height * scale))

    resized = cv2.resize(
        image,
        (resizedWidth, resizedHeight),
        interpolation=cv2.INTER_LINEAR,
    )

    padX = (imageSize - resizedWidth) // 2
    padY = (imageSize - resizedHeight) // 2

    canvas = np.full(
        (imageSize, imageSize, 3),
        fillColor,
        dtype=np.uint8,
    )
    canvas[
        padY : padY + resizedHeight,
        padX : padX + resizedWidth,
    ] = resized

    return canvas, scale, padX, padY


def parseOutput(
    output: np.ndarray,
    confidenceThreshold: float,
    scale: float,
    padX: int,
    padY: int,
    imageShape: tuple[int, int, int],
) -> tuple[
    list[tuple[tuple[float, float], tuple[float, float], float]], list[float], list[int]
]:
    if output.ndim == 3:
        output = output[0]

    if output.shape[0] < output.shape[1]:
        predictions = output.T
    else:
        predictions = output

    classCount = len(CLASSES)
    expectedValues = 5 + classCount
    if predictions.shape[1] != expectedValues:
        raise ValueError(
            f"Expected {expectedValues} ONNX outputs per prediction, "
            f"got {predictions.shape[1]}"
        )

    imageHeight, imageWidth = imageShape[:2]
    boxes = []
    scores = []
    classIds = []

    for prediction in predictions:
        classScores = prediction[4 : 4 + classCount]
        classId = int(np.argmax(classScores))
        score = float(classScores[classId])
        if score < confidenceThreshold:
            continue

        centerX, centerY, width, height = prediction[:4]
        angleRadians = float(prediction[4 + classCount])

        centerX = (float(centerX) - padX) / scale
        centerY = (float(centerY) - padY) / scale
        width = float(width) / scale
        height = float(height) / scale

        centerX = min(max(centerX, 0.0), float(imageWidth - 1))
        centerY = min(max(centerY, 0.0), float(imageHeight - 1))
        width = max(width, 1.0)
        height = max(height, 1.0)

        boxes.append(
            (
                (centerX, centerY),
                (width, height),
                math.degrees(angleRadians),
            )
        )
        scores.append(score)
        classIds.append(classId)

    return boxes, scores, classIds


def runRotatedNms(
    boxes: list[tuple[tuple[float, float], tuple[float, float], float]],
    scores: list[float],
    classIds: list[int],
    confidenceThreshold: float,
    nmsThreshold: float,
) -> list[int]:
    keptIndexes = []

    for classId in sorted(set(classIds)):
        localIndexes = [
            index for index, boxClassId in enumerate(classIds) if boxClassId == classId
        ]
        localBoxes = [boxes[index] for index in localIndexes]
        localScores = [scores[index] for index in localIndexes]

        selected = cv2.dnn.NMSBoxesRotated(
            localBoxes,
            localScores,
            confidenceThreshold,
            nmsThreshold,
        )

        if len(selected) == 0:
            continue

        for selectedIndex in np.array(selected).flatten():
            keptIndexes.append(localIndexes[int(selectedIndex)])

    return keptIndexes


def drawDetections(
    image: np.ndarray,
    boxes: list[tuple[tuple[float, float], tuple[float, float], float]],
    scores: list[float],
    classIds: list[int],
    indexes: list[int],
) -> np.ndarray:
    output = image.copy()

    for index in indexes:
        classId = classIds[index]
        color = COLORS.get(classId, (255, 255, 255))
        label = f"{CLASSES.get(classId, classId)} {scores[index]:.2f}"

        points = cv2.boxPoints(boxes[index])
        points = np.intp(points)

        cv2.polylines(output, [points], True, color, 2, cv2.LINE_AA)

        labelX = int(points[:, 0].min())
        labelY = int(points[:, 1].min()) - 8
        labelY = max(labelY, 20)

        textSize, baseline = cv2.getTextSize(
            label,
            cv2.FONT_HERSHEY_SIMPLEX,
            0.6,
            2,
        )
        textWidth, textHeight = textSize

        cv2.rectangle(
            output,
            (labelX, labelY - textHeight - baseline),
            (labelX + textWidth + 6, labelY + baseline),
            color,
            -1,
        )
        cv2.putText(
            output,
            label,
            (labelX + 3, labelY),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.6,
            (255, 255, 255),
            2,
            cv2.LINE_AA,
        )

    return output


def getOutputPath(imagePath: Path, outputPath: Path | None) -> Path:
    if outputPath:
        return outputPath

    return imagePath.with_name(f"{imagePath.stem}_obb{imagePath.suffix}")


def parseArgs() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("image", type=Path, help="Image to run inference on.")
    parser.add_argument(
        "--model",
        type=Path,
        default=DEFAULT_MODEL,
        help="Path to the exported YOLO OBB ONNX model.",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Path to save the image with bounding box overlays.",
    )
    parser.add_argument(
        "--imgsz",
        type=int,
        default=960,
        help="Input image size used when exporting the ONNX model.",
    )
    parser.add_argument(
        "--conf",
        type=float,
        default=0.25,
        help="Confidence threshold for detections.",
    )
    parser.add_argument(
        "--iou",
        type=float,
        default=0.45,
        help="Rotated NMS IoU threshold.",
    )
    return parser.parse_args()


def main() -> None:
    args = parseArgs()
    imagePath = args.image
    modelPath = args.model
    outputPath = getOutputPath(imagePath, args.output)

    if not imagePath.exists():
        raise FileNotFoundError(f"Image not found: {imagePath}")

    if not modelPath.exists():
        raise FileNotFoundError(f"ONNX model not found: {modelPath}")

    image = cv2.imread(str(imagePath))
    if image is None:
        raise ValueError(f"Could not read image: {imagePath}")

    inputImage, scale, padX, padY = letterbox(image, args.imgsz)
    blob = cv2.dnn.blobFromImage(
        inputImage,
        scalefactor=1 / 255.0,
        size=(args.imgsz, args.imgsz),
        mean=(0, 0, 0),
        swapRB=True,
        crop=False,
    )

    net = cv2.dnn.readNetFromONNX(str(modelPath))
    net.setInput(blob)
    output = net.forward()

    boxes, scores, classIds = parseOutput(
        output,
        args.conf,
        scale,
        padX,
        padY,
        image.shape,
    )
    keptIndexes = runRotatedNms(
        boxes,
        scores,
        classIds,
        args.conf,
        args.iou,
    )

    result = drawDetections(
        image,
        boxes,
        scores,
        classIds,
        keptIndexes,
    )

    outputPath.parent.mkdir(parents=True, exist_ok=True)
    if not cv2.imwrite(str(outputPath), result):
        raise ValueError(f"Could not write output image: {outputPath}")

    print(f"Detections: {len(keptIndexes)}")
    print(f"Saved: {outputPath}")


if __name__ == "__main__":
    main()