"""python example.py [conf]: prints the 4 corners (TL, TR, BR, BL, in photo pixels) of every card found.""" import sys import cv2 import numpy as np import onnxruntime as ort model, photo = sys.argv[1], sys.argv[2] conf = float(sys.argv[3]) if len(sys.argv) > 3 else 0.525 # 0.525 fp32, 0.625 int8 (picked on the validation split) session = ort.InferenceSession(model, providers=["CPUExecutionProvider"]) size = session.get_inputs()[0].shape[2] bgr = cv2.imread(photo, cv2.IMREAD_COLOR) # applies the EXIF orientation h, w = bgr.shape[:2] g = size / max(h, w) nw, nh = round(w * g), round(h * g) px, py = (size - nw) // 2, (size - nh) // 2 canvas = np.full((size, size, 3), 114, np.uint8) canvas[py : py + nh, px : px + nw] = cv2.resize(bgr, (nw, nh)) x = np.ascontiguousarray(canvas[..., ::-1].transpose(2, 0, 1)[None].astype(np.float32) / 255) out = session.run(None, {session.get_inputs()[0].name: x})[0][0].T # (N, 4 box + 1 score + 4 x 3 keypoints) out = out[out[:, 4] > conf] boxes = np.stack([out[:, 0] - out[:, 2] / 2, out[:, 1] - out[:, 3] / 2, out[:, 0] + out[:, 2] / 2, out[:, 1] + out[:, 3] / 2], 1) keep = cv2.dnn.NMSBoxes( [[b[0], b[1], b[2] - b[0], b[3] - b[1]] for b in boxes.tolist()], out[:, 4].tolist(), conf, 0.6 ) for i in np.array(keep, dtype=int).reshape(-1): corners = (out[i, 5:].reshape(4, 3)[:, :2] - [px, py]) / g print(round(float(out[i, 4]), 3), corners.round(1).tolist())