1import argparse
2import time
3from contextlib import contextmanager
4
5import numpy as np
6import onnxruntime
7from PIL import Image
8
9
10@contextmanager
11def timer(name: str):
12 start = time.perf_counter()
13 yield
14 end = time.perf_counter()
15 print(f"{name}: {end - start:.3f} [sec]")
16
17
18def preprocess(image: Image.Image, size: int) -> np.ndarray:
19 image = image.resize((size, size))
20 image = np.float32(image) / 255.
21 image = np.transpose(image, (2, 0, 1)) # (w, h, c) -> (c, w, h)
22 image = np.expand_dims(image, axis=0) # (c, w, h) -> (b, c, w, h)
23 return image
24
25
26def postprocess(output: np.ndarray, original_size: tuple[int, int] = None) -> Image.Image:
27 output_image = np.squeeze(output[0, 0] * 255).astype(np.uint8)
28 output_image = Image.fromarray(output_image).convert("L")
29 if original_size:
30 output_image = output_image.resize(original_size)
31 return output_image
32
33
34def main():
35
36 parser = argparse.ArgumentParser()
37 parser.add_argument("--image", type=str, required=True, help="Path to input image")
38 parser.add_argument("--model", type=str, required=True, help="Path to ONNX model")
39 args = parser.parse_args()
40
41 input_image = Image.open(args.image).convert("RGB")
42 input_image.thumbnail((1536, 1536))
43
44 # Load input image and the model
45 with timer(f"Load model"):
46 session = onnxruntime.InferenceSession(args.model)
47
48 size = session.get_inputs()[0].shape[2] # width
49
50 # Inference
51 input_data = preprocess(input_image, size)
52 with timer(f"Inference"):
53 output_data = session.run(None, {"inputs": input_data})[0]
54 output_image = postprocess(output_data, input_image.size)
55 output_image.show()
56
57
58if __name__ == "__main__":
59 main()
60
The larger the image size, the more vivid the conversion results will be. Conversely, the smaller the image size, the stronger the deformation. Please use the size you like.
This repository is under MIT License.