wzf19947 commited on
Commit
0961b15
·
1 Parent(s): 33bd4c6
Restormer/model_convert/Restormer.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input": "./Restormer_real_denoising_224x224_sim.onnx",
3
+ "output_dir": "./Restormer",
4
+ "output_name": "Restormer_real_denoising_224x224_sim.axmodel",
5
+ "model_type": "ONNX",
6
+ "target_hardware": "AX650",
7
+ "npu_mode": "NPU3",
8
+ "quant": {
9
+ "input_configs": [
10
+ {
11
+ "tensor_name": "input",
12
+ "calibration_dataset": "./SIDD.tar.gz",
13
+ "calibration_size": 32,
14
+ "calibration_mean": [0.0, 0.0, 0.0],
15
+ "calibration_std": [255.0, 255.0, 255.0]
16
+ }
17
+ ],
18
+ "calibration_method": "MinMax",
19
+ "precision_analysis": true,
20
+ "transformer_opt_level":1,
21
+ "precision_analysis_method": "EndToEnd",
22
+ "precision_analysis_mode": "NPUBackend",
23
+ "device": "cuda:1",
24
+ "layer_configs": [
25
+ {
26
+ "start_tensor_names": ["DEFAULT"],
27
+ "end_tensor_names": ["DEFAULT"],
28
+ "data_type": "U16"
29
+ }
30
+ ]
31
+ },
32
+ "input_processors": [
33
+ {
34
+ "tensor_name": "input",
35
+ "tensor_format": "RGB",
36
+ "tensor_layout": "NCHW",
37
+ "src_format": "BGR",
38
+ "src_dtype": "U8",
39
+ "src_layout": "NCHW",
40
+ "csc_mode": "NoCSC"
41
+ }
42
+ ],
43
+ "compiler": {
44
+ "check": 2
45
+ }
46
+ }
47
+
Restormer/model_convert/axmodel/Restormer_real_denoising_224x224_sim.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e262a8185d3139fe38fc4f70450911470bea2d93a61756ebcccbeaac0c039ed1
3
+ size 123639724
Restormer/pic/noisy.png ADDED

Git LFS Details

  • SHA256: 403034182fa320130dae0d75b92e85e0850771378e674d65455c403a4958e29c
  • Pointer size: 131 Bytes
  • Size of remote file: 171 kB
Restormer/python/axmodel_infer.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ AXModel 单图推理脚本 (不依赖 PyTorch / ONNX Runtime)。
4
+ 功能:读取单张图片 → 预处理到模型尺寸 → axengine 推理 → 还原到原图尺寸 → 保存「原图 + 去噪结果」横向拼接图。
5
+ - 原图 ≤ 模型尺寸:reflect pad 到模型尺寸,推理后裁回原图
6
+ - 原图 > 模型尺寸:resize 到模型尺寸,推理后 resize 回原图
7
+ 所有参数均以固定默认值写在脚本顶部,直接运行即可。
8
+ """
9
+
10
+ import os
11
+ import sys
12
+
13
+ import cv2
14
+ import numpy as np
15
+
16
+ # ═══════════════════════════════════════════════════════════════
17
+ # 固定默认参数(按需修改)
18
+ # ═══════════════════════════════════════════════════════════════
19
+ DEFAULT_AXMODEL = "./Restormer_real_denoising_224x224_sim.axmodel"
20
+ DEFAULT_INPUT_IMAGE = "noisy.png"
21
+ DEFAULT_OUTPUT_IMAGE = "axmodel_result.png"
22
+
23
+ # 模型导出时的固定输入尺寸 (H, W),必须能被 8 整除
24
+ MODEL_HEIGHT = 224
25
+ MODEL_WIDTH = 224
26
+
27
+ # 是否保存纯去噪结果(不拼接)
28
+ SAVE_RESTORED_ONLY = False
29
+ RESTORED_ONLY_PATH = "axmodel_result_restored.png"
30
+ # ═══════════════════════════════════════════════════════════════
31
+
32
+
33
+ def _load_image(path):
34
+ """用 OpenCV 读取图片,返回 RGB uint8 numpy (H,W,3) 或 (H,W,1)。"""
35
+ if not os.path.isfile(path):
36
+ raise FileNotFoundError(f"输入图片不存在: {path}")
37
+ img = cv2.imread(path, cv2.IMREAD_COLOR)
38
+ if img is None:
39
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
40
+ if img is None:
41
+ raise RuntimeError(f"无法读取图片: {path}")
42
+ return img[:, :, None] # (H,W,1)
43
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
44
+
45
+
46
+ def _save_image(path, img):
47
+ """保存 uint8 numpy 图片,自动处理灰度/彩色。"""
48
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
49
+ if img.ndim == 2:
50
+ cv2.imwrite(path, img)
51
+ elif img.shape[2] == 1:
52
+ cv2.imwrite(path, img[:, :, 0])
53
+ else:
54
+ cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
55
+
56
+
57
+ def _image_to_nchw(img):
58
+ """uint8 (H,W,C) → float32 NCHW [0,1]。"""
59
+ # return np.transpose(img.astype(np.float32) / 255.0, (2, 0, 1))[np.newaxis, ...]
60
+ return np.transpose(img.astype(np.float32), (2, 0, 1))[np.newaxis, ...]
61
+
62
+
63
+ def _nchw_to_image(arr):
64
+ """float32 NCHW [0,1] → uint8 (H,W,C)。"""
65
+ arr = arr.squeeze(0)
66
+ arr = np.transpose(arr, (1, 2, 0))
67
+ arr = np.clip(arr, 0.0, 1.0)
68
+ return (arr * 255.0).round().clip(0, 255).astype(np.uint8)
69
+
70
+
71
+ def _prepare_for_model(tensor, model_h, model_w):
72
+ """
73
+ 将 NCHW tensor 处理到模型固定尺寸:
74
+ - 原图 ≤ 模型尺寸:reflect pad → 返回 (padded, (orig_h, orig_w), "pad")
75
+ - 原图 > 模型尺寸:resize → 返回 (resized, (orig_h, orig_w), "resize")
76
+ """
77
+ _, c, orig_h, orig_w = tensor.shape
78
+ if orig_h <= model_h and orig_w <= model_w:
79
+ pad_h = model_h - orig_h
80
+ pad_w = model_w - orig_w
81
+ if pad_h or pad_w:
82
+ tensor = np.pad(tensor, ((0, 0), (0, 0), (0, pad_h), (0, pad_w)), mode="reflect")
83
+ return tensor.astype(np.uint8), (orig_h, orig_w), "pad"
84
+ else:
85
+ resized = np.zeros((1, c, model_h, model_w), dtype=np.float32)
86
+ for b in range(tensor.shape[0]):
87
+ for ch in range(c):
88
+ resized[b, ch] = cv2.resize(tensor[b, ch], (model_w, model_h), interpolation=cv2.INTER_LINEAR)
89
+ return resized.astype(np.uint8), (orig_h, orig_w), "resize"
90
+
91
+
92
+ def _restore_from_model(output_arr, orig_h, orig_w, mode):
93
+ """
94
+ 将模型输出还原到原图尺寸:
95
+ - mode="pad":裁掉 padding 区域
96
+ - mode="resize":resize 回原图尺寸
97
+ """
98
+ if mode == "pad":
99
+ return output_arr[:, :, :orig_h, :orig_w]
100
+ else:
101
+ _, c, _, _ = output_arr.shape
102
+ restored = np.zeros((1, c, orig_h, orig_w), dtype=np.float32)
103
+ for b in range(output_arr.shape[0]):
104
+ for ch in range(c):
105
+ restored[b, ch] = cv2.resize(output_arr[b, ch], (orig_w, orig_h), interpolation=cv2.INTER_LINEAR)
106
+ return restored
107
+
108
+
109
+ def main():
110
+ # ----- 命令行可覆盖前三个参数(可选) -----
111
+ axmodel_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_AXMODEL
112
+ input_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_INPUT_IMAGE
113
+ output_path = sys.argv[3] if len(sys.argv) > 3 else DEFAULT_OUTPUT_IMAGE
114
+
115
+ if MODEL_HEIGHT % 8 != 0 or MODEL_WIDTH % 8 != 0:
116
+ raise ValueError(f"MODEL_HEIGHT({MODEL_HEIGHT}) 和 MODEL_WIDTH({MODEL_WIDTH}) 必须能被 8 整除")
117
+
118
+ # ----- 加载 axengine -----
119
+ try:
120
+ import axengine as axe
121
+ except ImportError:
122
+ raise ImportError("请先安装 axengine")
123
+
124
+ session = axe.InferenceSession(axmodel_path, providers=["AxEngineExecutionProvider"])
125
+ input_name = session.get_inputs()[0].name
126
+ output_name = session.get_outputs()[0].name
127
+
128
+ # ----- 读取原图 -----
129
+ original_img = _load_image(input_path) # uint8 HWC RGB
130
+ orig_h, orig_w = original_img.shape[:2]
131
+ is_gray = original_img.ndim == 2 or original_img.shape[2] == 1
132
+
133
+ # ----- 预处理到模型尺寸 -----
134
+ tensor = _image_to_nchw(original_img)
135
+ tensor, (crop_h, crop_w), prep_mode = _prepare_for_model(tensor, MODEL_HEIGHT, MODEL_WIDTH)
136
+
137
+ print(f"[AXModel 推理] 模型: {axmodel_path}")
138
+ print(f"[AXModel 推理] 输入图片: {input_path} (原图尺寸: {orig_h}x{orig_w}, 模型输入尺寸: {MODEL_HEIGHT}x{MODEL_WIDTH}, 预处理模式: {prep_mode})")
139
+
140
+ # ----- axengine 推理 -----
141
+ ax_output = session.run([output_name], {input_name: tensor})[0]
142
+
143
+ # ----- 后处理:还原到原图尺寸 -----
144
+ restored_tensor = _restore_from_model(ax_output, crop_h, crop_w, prep_mode)
145
+ restored_img = _nchw_to_image(restored_tensor) # uint8 HWC RGB
146
+
147
+ # ----- 拼接:原图 || 去噪结果 -----
148
+ if is_gray:
149
+ orig_display = original_img[:, :, 0] if original_img.ndim == 3 else original_img
150
+ rest_display = restored_img[:, :, 0] if restored_img.ndim == 3 else restored_img
151
+ comparison = np.concatenate([orig_display, rest_display], axis=1)
152
+ else:
153
+ comparison = np.concatenate([original_img, restored_img], axis=1)
154
+
155
+ # ----- 保存结果 -----
156
+ _save_image(output_path, comparison)
157
+ print(f"[AXModel 推理] 拼接结果已保存到: {output_path} (左=原图, 右=去噪)")
158
+
159
+ if SAVE_RESTORED_ONLY:
160
+ _save_image(RESTORED_ONLY_PATH, restored_img)
161
+ print(f"[AXModel 推理] 纯去噪结果已保存到: {RESTORED_ONLY_PATH}")
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()
Restormer/python/onnx_infer.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ ONNX 单图推理脚本 (不依赖 PyTorch)。
4
+ 功能:读取单张图片 → 预处理到模型尺寸 → 推理 → 还原到原图尺寸 → 保存「原图 + 去噪结果」横向拼接图。
5
+ - 原图 ≤ 模型尺寸:reflect pad 到模型尺寸,推理后裁回原图
6
+ - 原图 > 模型尺寸:resize 到模型尺寸,推理后 resize 回原图
7
+ 所有参数均以固定默认值写在脚本顶部,直接运行即可。
8
+ """
9
+
10
+ import os
11
+ import sys
12
+
13
+ import cv2
14
+ import numpy as np
15
+
16
+ # ═══════════════════════════════════════════════════════════════
17
+ # 固定默认参数(按需修改)
18
+ # ═══════════════════════════════════════════════════════════════
19
+ DEFAULT_ONNX_MODEL = os.path.join("onnx_models", "real_denoising_224x224_sim.onnx")
20
+ DEFAULT_INPUT_IMAGE = os.path.join("demo", "mixed/noisy.png")
21
+ DEFAULT_OUTPUT_IMAGE = "onnx_result_compare.png"
22
+
23
+ # ONNX 模型导出时的固定输入尺寸 (H, W),必须能被 8 整除
24
+ MODEL_HEIGHT = 224
25
+ MODEL_WIDTH = 224
26
+
27
+ # 推理后端:cuda / cpu
28
+ PROVIDER = "cuda" # 可选: "cuda", "cpu"
29
+
30
+ # 是否保存纯去噪结果(不拼接)
31
+ SAVE_RESTORED_ONLY = False
32
+ RESTORED_ONLY_PATH = "onnx_result_restored.png"
33
+ # ═══════════════════════════════════════════════════════════════
34
+
35
+
36
+ def _load_image(path):
37
+ """用 OpenCV 读取图片,返回 RGB uint8 numpy (H,W,3) 或 (H,W,1)。"""
38
+ if not os.path.isfile(path):
39
+ raise FileNotFoundError(f"输入图片不存在: {path}")
40
+ img = cv2.imread(path, cv2.IMREAD_COLOR)
41
+ if img is None:
42
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
43
+ if img is None:
44
+ raise RuntimeError(f"无法读取图片: {path}")
45
+ return img[:, :, None] # (H,W,1)
46
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
47
+
48
+
49
+ def _save_image(path, img):
50
+ """保存 uint8 numpy 图片,自动处理灰度/彩色。"""
51
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
52
+ if img.ndim == 2:
53
+ cv2.imwrite(path, img)
54
+ elif img.shape[2] == 1:
55
+ cv2.imwrite(path, img[:, :, 0])
56
+ else:
57
+ cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
58
+
59
+
60
+ def _image_to_nchw(img):
61
+ """uint8 (H,W,C) → float32 NCHW [0,1]。"""
62
+ return np.transpose(img.astype(np.float32) / 255.0, (2, 0, 1))[np.newaxis, ...]
63
+
64
+
65
+ def _nchw_to_image(arr):
66
+ """float32 NCHW [0,1] → uint8 (H,W,C)。"""
67
+ arr = arr.squeeze(0)
68
+ arr = np.transpose(arr, (1, 2, 0))
69
+ arr = np.clip(arr, 0.0, 1.0)
70
+ return (arr * 255.0).round().clip(0, 255).astype(np.uint8)
71
+
72
+
73
+ def _prepare_for_model(tensor, model_h, model_w):
74
+ """
75
+ 将 NCHW tensor 处理到模型固定尺寸:
76
+ - 原图 ≤ 模型尺寸:reflect pad → 记录原始区域 → 返回 (padded, (crop_h, crop_w), mode="pad")
77
+ - 原图 > 模型尺寸:resize → 返回 (resized, (orig_h, orig_w), mode="resize")
78
+ """
79
+ _, c, orig_h, orig_w = tensor.shape
80
+ if orig_h <= model_h and orig_w <= model_w:
81
+ # 小图/等尺寸:reflect pad 到模型尺寸
82
+ pad_h = model_h - orig_h
83
+ pad_w = model_w - orig_w
84
+ if pad_h or pad_w:
85
+ tensor = np.pad(tensor, ((0, 0), (0, 0), (0, pad_h), (0, pad_w)), mode="reflect")
86
+ return tensor.astype(np.float32), (orig_h, orig_w), "pad"
87
+ else:
88
+ # 大图:resize 到模型尺寸
89
+ resized = np.zeros((1, c, model_h, model_w), dtype=np.float32)
90
+ for b in range(tensor.shape[0]):
91
+ for ch in range(c):
92
+ resized[b, ch] = cv2.resize(tensor[b, ch], (model_w, model_h), interpolation=cv2.INTER_LINEAR)
93
+ return resized.astype(np.float32), (orig_h, orig_w), "resize"
94
+
95
+
96
+ def _restore_from_model(output_arr, orig_h, orig_w, mode):
97
+ """
98
+ 将模型输出还原到原图尺寸:
99
+ - mode="pad":裁掉 padding 区域
100
+ - mode="resize":resize 回原图尺寸
101
+ """
102
+ if mode == "pad":
103
+ return output_arr[:, :, :orig_h, :orig_w]
104
+ else:
105
+ _, c, _, _ = output_arr.shape
106
+ restored = np.zeros((1, c, orig_h, orig_w), dtype=np.float32)
107
+ for b in range(output_arr.shape[0]):
108
+ for ch in range(c):
109
+ restored[b, ch] = cv2.resize(output_arr[b, ch], (orig_w, orig_h), interpolation=cv2.INTER_LINEAR)
110
+ return restored
111
+
112
+
113
+ def main():
114
+ # ----- 命令行覆盖参数(可选) -----
115
+ onnx_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_ONNX_MODEL
116
+ input_path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_INPUT_IMAGE
117
+ output_path = sys.argv[3] if len(sys.argv) > 3 else DEFAULT_OUTPUT_IMAGE
118
+
119
+ if MODEL_HEIGHT % 8 != 0 or MODEL_WIDTH % 8 != 0:
120
+ raise ValueError(f"MODEL_HEIGHT({MODEL_HEIGHT}) 和 MODEL_WIDTH({MODEL_WIDTH}) 必须能被 8 整除")
121
+
122
+ # ----- 加载 ONNX Runtime -----
123
+ try:
124
+ import onnxruntime as ort
125
+ except ImportError:
126
+ raise ImportError("请先安装 onnxruntime: pip install onnxruntime-gpu 或 pip install onnxruntime")
127
+
128
+ if PROVIDER == "cuda":
129
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
130
+ else:
131
+ providers = ["CPUExecutionProvider"]
132
+
133
+ session = ort.InferenceSession(onnx_path, providers=providers)
134
+ input_name = session.get_inputs()[0].name
135
+ output_name = session.get_outputs()[0].name
136
+
137
+ # ----- 读取原图 -----
138
+ original_img = _load_image(input_path) # uint8 HWC RGB
139
+ orig_h, orig_w = original_img.shape[:2]
140
+ is_gray = original_img.ndim == 2 or original_img.shape[2] == 1
141
+
142
+ # ----- 预处理到模型尺寸 -----
143
+ tensor = _image_to_nchw(original_img)
144
+ tensor, (crop_h, crop_w), prep_mode = _prepare_for_model(tensor, MODEL_HEIGHT, MODEL_WIDTH)
145
+
146
+ print(f"[ONNX 推理] 模型: {onnx_path}")
147
+ print(f"[ONNX 推理] 输入图片: {input_path} (原图尺寸: {orig_h}x{orig_w}, 模型输入尺寸: {MODEL_HEIGHT}x{MODEL_WIDTH}, 预处理模式: {prep_mode})")
148
+
149
+ # ----- ONNX 推理 -----
150
+ ort_output = session.run([output_name], {input_name: tensor})[0]
151
+
152
+ # ----- 后处理:还原到原图尺寸 -----
153
+ restored_tensor = _restore_from_model(ort_output, crop_h, crop_w, prep_mode)
154
+ restored_img = _nchw_to_image(restored_tensor) # uint8 HWC RGB, 尺寸 = (crop_h, crop_w)
155
+
156
+ # ----- 拼接:原图 || 去噪结果 -----
157
+ if is_gray:
158
+ orig_display = original_img[:, :, 0] if original_img.ndim == 3 else original_img
159
+ rest_display = restored_img[:, :, 0] if restored_img.ndim == 3 else restored_img
160
+ comparison = np.concatenate([orig_display, rest_display], axis=1)
161
+ else:
162
+ comparison = np.concatenate([original_img, restored_img], axis=1)
163
+
164
+ # ----- 保存结果 -----
165
+ _save_image(output_path, comparison)
166
+ print(f"[ONNX 推理] 拼接结果已保存到: {output_path} (左=原图, 右=去噪)")
167
+
168
+ if SAVE_RESTORED_ONLY:
169
+ _save_image(RESTORED_ONLY_PATH, restored_img)
170
+ print(f"[ONNX 推理] 纯去噪结果已保存到: {RESTORED_ONLY_PATH}")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
Restormer/res/axmodel_result.png ADDED

Git LFS Details

  • SHA256: 9689afda28fda6b03d9161a1138550dedaa00708500c9eff07febccfb64afb27
  • Pointer size: 131 Bytes
  • Size of remote file: 254 kB