Views
No views yet
1import cv2
2import numpy as np
3import onnxruntime as ort
4from PIL import Image
5
6# 設定
7MODEL_PATH = "birefnext-aniseg-int8-v0.1.onnx"
8INPUT_IMAGE = "input.jpg"
9OUTPUT_IMAGE = "output_mask.png"
10
11# ImageNetの正規化パラメータ
12MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
13STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
14
15providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if ort.get_device() == 'GPU' else ['CPUExecutionProvider']
16session = ort.InferenceSession(MODEL_PATH, providers=providers)
17
18input_name = session.get_inputs()[0].name
19output_name = session.get_outputs()[0].name
20
21img = Image.open(INPUT_IMAGE).convert('RGB')
22w0, h0 = img.size
23
24# 32の倍数にリサイズ
25w, h = (w0 // 32) * 32, (h0 // 32) * 32
26img_resized = img.resize((w, h), Image.BILINEAR)
27
28# 前処理
29img_array = np.array(img_resized, dtype=np.float32) / 255.0
30img_array = (img_array - MEAN) / STD
31input_tensor = img_array.transpose(2, 0, 1)[None]
32
33# 推論
34result = session.run([output_name], {input_name: input_tensor})[0]
35
36# 後処理
37mask = result[0, 0]
38mask_resized = cv2.resize(mask, (w0, h0), interpolation=cv2.INTER_LINEAR)
39mask_uint8 = (np.clip(mask_resized, 0, 1) * 255).astype(np.uint8)
40
41cv2.imwrite(OUTPUT_IMAGE, mask_uint8)
42print(f"Saved: {OUTPUT_IMAGE}")