File size: 1,366 Bytes
e811d70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import cv2
import numpy as np
import onnxruntime as ort

MODEL_PATH = "cat_landmark_model.onnx"

def preprocess(img_path):
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    orig_h, orig_w = img.shape[:2]
    img_resized = cv2.resize(img, (224, 224))
    tensor = img_resized.astype(np.float32).transpose(2, 0, 1) / 255.0
    return np.expand_dims(tensor, 0), orig_w, orig_h

def run(img_path):
    session = ort.InferenceSession(MODEL_PATH)
    tensor, orig_w, orig_h = preprocess(img_path)
    outputs = session.run(None, {"input": tensor})[0][0]  # shape: (18,)
    landmarks = outputs.reshape(9, 2)
    # denormalize back to original image coords
    landmarks[:, 0] *= orig_w
    landmarks[:, 1] *= orig_h
    for i, (x, y) in enumerate(landmarks):
        print(f"Point {i}: ({x:.1f}, {y:.1f})")

    # draw bounding box around landmarks
    img = cv2.imread(img_path)
    x1, y1 = landmarks.min(axis=0).astype(int)
    x2, y2 = landmarks.max(axis=0).astype(int)
    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
    for (x, y) in landmarks.astype(int):
        cv2.circle(img, (x, y), 3, (0, 0, 255), -1)
    out_path = "output.jpg"
    cv2.imwrite(out_path, img)
    print(f"Saved to {out_path}")

if __name__ == "__main__":
    img_path = sys.argv[1] if len(sys.argv) > 1 else "test.jpg"
    run(img_path)