| 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] |
| landmarks = outputs.reshape(9, 2) |
| |
| landmarks[:, 0] *= orig_w |
| landmarks[:, 1] *= orig_h |
| for i, (x, y) in enumerate(landmarks): |
| print(f"Point {i}: ({x:.1f}, {y:.1f})") |
|
|
| |
| 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) |
|
|