yssszzzzzzzzy commited on
Commit
6f8982e
·
verified ·
1 Parent(s): 77f167e

Upload 3 files

Browse files
Files changed (3) hide show
  1. RealDehazing_FPro.yml +135 -0
  2. RealDemoiring_FPro.yml +135 -0
  3. model.py +232 -110
RealDehazing_FPro.yml ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: Dehazing_FPro
3
+ model_type: ImageCleanModel
4
+ scale: 1
5
+ num_gpu: 8 # set num_gpu: 0 for cpu mode
6
+ manual_seed: 100
7
+
8
+ # dataset and data loader settings
9
+ datasets:
10
+ train:
11
+ name: TrainSet
12
+ type: Dataset_PairedImage_dehazeSOT
13
+ dataroot_gt: /mnt/sda/zsh/dataset/haze
14
+ dataroot_lq: /mnt/sda/zsh/dataset/haze
15
+ geometric_augs: true
16
+
17
+ filename_tmpl: '{}'
18
+ io_backend:
19
+ type: disk
20
+
21
+ # data loader
22
+ use_shuffle: true
23
+ num_worker_per_gpu: 8
24
+ batch_size_per_gpu: 8
25
+
26
+ ## ------- Training on single fixed-patch size 128x128---------
27
+ mini_batch_sizes: [2]
28
+ iters: [300000]
29
+ gt_size: 256
30
+ gt_sizes: [256]
31
+ ## ------------------------------------------------------------
32
+
33
+ dataset_enlarge_ratio: 1
34
+ prefetch_mode: ~
35
+
36
+ val:
37
+ name: ValSet
38
+ type: Dataset_PairedImage_dehazeSOT
39
+ dataroot_gt: /mnt/sda/zsh/dataset/haze
40
+ dataroot_lq: /mnt/sda/zsh/dataset/haze
41
+ gt_size: 256
42
+ io_backend:
43
+ type: disk
44
+
45
+ # network structures
46
+
47
+ network_g:
48
+ type: FPro
49
+ inp_channels: 3
50
+ out_channels: 3
51
+ # input_res: 128
52
+ dim: 48
53
+ # num_blocks: [4,6,6,8]
54
+ num_blocks: [2,3,6]
55
+ # num_refinement_blocks: 4
56
+ num_refinement_blocks: 2
57
+ # heads: [1,2,4,8]
58
+ heads: [2,4,8]
59
+ # ffn_expansion_factor: 2.66
60
+ ffn_expansion_factor: 3
61
+ bias: False
62
+ LayerNorm_type: WithBias
63
+ dual_pixel_task: False
64
+
65
+
66
+ # path
67
+ path:
68
+ pretrain_network_g: ~
69
+ strict_load_g: true
70
+ resume_state: ~
71
+
72
+ # training settings
73
+ train:
74
+ total_iter: 300000
75
+ warmup_iter: -1 # no warm up
76
+ use_grad_clip: true
77
+
78
+ # Split 300k iterations into two cycles.
79
+ # 1st cycle: fixed 3e-4 LR for 92k iters.
80
+ # 2nd cycle: cosine annealing (3e-4 to 1e-6) for 208k iters.
81
+ scheduler:
82
+ type: CosineAnnealingRestartCyclicLR
83
+ periods: [92000, 208000]
84
+ restart_weights: [1,1]
85
+ eta_mins: [0.0003,0.000001]
86
+
87
+ mixing_augs:
88
+ mixup: true
89
+ mixup_beta: 1.2
90
+ use_identity: true
91
+
92
+ optim_g:
93
+ type: AdamW
94
+ lr: !!float 3e-4
95
+ weight_decay: !!float 1e-4
96
+ betas: [0.9, 0.999]
97
+
98
+ # losses
99
+ pixel_opt:
100
+ type: L1Loss
101
+ loss_weight: 1
102
+ reduction: mean
103
+ fft_loss_opt:
104
+ type: FFTLoss
105
+ loss_weight: 0.1
106
+ reduction: mean
107
+
108
+ # validation settings
109
+ val:
110
+ window_size: 8
111
+ val_freq: !!float 4e3
112
+ save_img: false
113
+ rgb2bgr: true
114
+ use_image: false
115
+ max_minibatch: 8
116
+
117
+ metrics:
118
+ psnr: # metric name, can be arbitrary
119
+ type: calculate_psnr
120
+ crop_border: 0
121
+ test_y_channel: false
122
+
123
+ # logging settings
124
+ logger:
125
+ print_freq: 1000
126
+ save_checkpoint_freq: !!float 4e3
127
+ use_tb_logger: true
128
+ wandb:
129
+ project: ~
130
+ resume_id: ~
131
+
132
+ # dist training settings
133
+ dist_params:
134
+ backend: nccl
135
+ port: 29500
RealDemoiring_FPro.yml ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general settings
2
+ name: RealDemoiring_Restormer
3
+ model_type: ImageCleanModel
4
+ scale: 1
5
+ num_gpu: 8 # set num_gpu: 0 for cpu mode
6
+ manual_seed: 100
7
+
8
+ # dataset and data loader settings
9
+ datasets:
10
+ train:
11
+ name: TrainSet
12
+ type: Dataset_PairedImage_denseHaze
13
+ dataroot_gt: /home/ubuntu/zsh/datasets/TIP18/process/train/thin_target
14
+ dataroot_lq: /home/ubuntu/zsh/datasets/TIP18/process/train/thin_source
15
+ geometric_augs: False
16
+
17
+ filename_tmpl: '{}'
18
+ io_backend:
19
+ type: disk
20
+
21
+ # data loader
22
+ use_shuffle: true
23
+ num_worker_per_gpu: 8
24
+ batch_size_per_gpu: 8
25
+
26
+ ## ------- Training on single fixed-patch size 128x128---------
27
+ mini_batch_sizes: [2]
28
+ iters: [300000]
29
+ gt_size: 256
30
+ gt_sizes: [256]
31
+ ## ------------------------------------------------------------
32
+
33
+ dataset_enlarge_ratio: 1
34
+ prefetch_mode: ~
35
+
36
+ val:
37
+ name: ValSet
38
+ type: Dataset_PairedImage_denseHaze
39
+ dataroot_gt: /home/ubuntu/zsh/datasets/TIP18/process/val/thin_target
40
+ dataroot_lq: /home/ubuntu/zsh/datasets/TIP18/process/val/thin_source
41
+ gt_size: 256
42
+ io_backend:
43
+ type: disk
44
+
45
+ # network structures
46
+
47
+ network_g:
48
+ type: Restormer
49
+ inp_channels: 3
50
+ out_channels: 3
51
+ # input_res: 128
52
+ dim: 48
53
+ # num_blocks: [4,6,6,8]
54
+ num_blocks: [2,3,6]
55
+ # num_refinement_blocks: 4
56
+ num_refinement_blocks: 2
57
+ # heads: [1,2,4,8]
58
+ heads: [2,4,8]
59
+ # ffn_expansion_factor: 2.66
60
+ ffn_expansion_factor: 3
61
+ bias: False
62
+ LayerNorm_type: WithBias
63
+ dual_pixel_task: False
64
+
65
+
66
+ # path
67
+ path:
68
+ pretrain_network_g: ~
69
+ strict_load_g: true
70
+ resume_state: ~
71
+
72
+ # training settings
73
+ train:
74
+ total_iter: 300000
75
+ warmup_iter: -1 # no warm up
76
+ use_grad_clip: true
77
+
78
+ # Split 300k iterations into two cycles.
79
+ # 1st cycle: fixed 3e-4 LR for 92k iters.
80
+ # 2nd cycle: cosine annealing (3e-4 to 1e-6) for 208k iters.
81
+ scheduler:
82
+ type: CosineAnnealingRestartCyclicLR
83
+ periods: [92000, 208000]
84
+ restart_weights: [1,1]
85
+ eta_mins: [0.0003,0.000001]
86
+
87
+ mixing_augs:
88
+ mixup: true
89
+ mixup_beta: 1.2
90
+ use_identity: true
91
+
92
+ optim_g:
93
+ type: AdamW
94
+ lr: !!float 3e-4
95
+ weight_decay: !!float 1e-4
96
+ betas: [0.9, 0.999]
97
+
98
+ # losses
99
+ pixel_opt:
100
+ type: L1Loss
101
+ loss_weight: 1
102
+ reduction: mean
103
+ fft_loss_opt:
104
+ type: FFTLoss
105
+ loss_weight: 0.1
106
+ reduction: mean
107
+
108
+ # validation settings
109
+ val:
110
+ window_size: 8
111
+ val_freq: !!float 4e3
112
+ save_img: false
113
+ rgb2bgr: true
114
+ use_image: false
115
+ max_minibatch: 8
116
+
117
+ metrics:
118
+ psnr: # metric name, can be arbitrary
119
+ type: calculate_psnr
120
+ crop_border: 0
121
+ test_y_channel: false
122
+
123
+ # logging settings
124
+ logger:
125
+ print_freq: 1000
126
+ save_checkpoint_freq: !!float 4e3
127
+ use_tb_logger: true
128
+ wandb:
129
+ project: ~
130
+ resume_id: ~
131
+
132
+ # dist training settings
133
+ dist_params:
134
+ backend: nccl
135
+ port: 29500
model.py CHANGED
@@ -1,83 +1,165 @@
1
- # model.py - 整合版本:支持去雾和去摩尔纹
2
  import yaml, torch, math, numpy as np
3
  import torch.nn.functional as F
4
  from PIL import Image
5
  from io import BytesIO
6
  from basicsr.models.archs.FPro_arch import FPro
7
-
8
- # 强制使用 CPU
9
- device = torch.device('cpu')
10
-
11
- # 全局变量存储两个模型
 
 
 
 
 
 
 
12
  dehaze_model = None
13
  demoiring_model = None
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- def splitimage(imgtensor, crop_size=256, overlap_size=158):
17
- """切块函数,与原代码保持一致"""
 
 
 
18
  _, C, H, W = imgtensor.shape
19
- hstarts = [x for x in range(0, H, crop_size - overlap_size)]
20
- while hstarts and hstarts[-1] + crop_size >= H:
21
- hstarts.pop()
22
- hstarts.append(H - crop_size)
23
- wstarts = [x for x in range(0, W, crop_size - overlap_size)]
24
- while wstarts and wstarts[-1] + crop_size >= W:
25
- wstarts.pop()
26
- wstarts.append(W - crop_size)
27
  starts = []
28
- split_data = []
29
- for hs in hstarts:
30
- for ws in wstarts:
31
- cimgdata = imgtensor[:, :, hs:hs + crop_size, ws:ws + crop_size]
 
 
 
 
 
 
 
 
 
 
32
  starts.append((hs, ws))
33
- split_data.append(cimgdata)
34
- return split_data, starts
35
 
 
 
 
 
 
 
 
36
 
37
- def get_scoremap(H, W, C, B=1, is_mean=True):
38
- """权重图生成函数,与原代码保持一致"""
39
- center_h = H / 2
40
- center_w = W / 2
41
 
42
- score = torch.ones((B, C, H, W))
43
- if not is_mean:
44
- for h in range(H):
45
- for w in range(W):
46
- score[:, :, h, w] = 1.0 / (math.sqrt((h - center_h) ** 2 + (w - center_w) ** 2 + 1e-6))
47
- return score
48
 
 
 
49
 
50
- def mergeimage(split_data, starts, crop_size=256, resolution=(1, 3, 128, 128)):
51
- """图像合并函数,与原代码保持一致"""
52
- B, C, H, W = resolution[0], resolution[1], resolution[2], resolution[3]
53
- tot_score = torch.zeros((B, C, H, W))
54
- merge_img = torch.zeros((B, C, H, W))
55
- scoremap = get_scoremap(crop_size, crop_size, C, B=B, is_mean=True)
 
 
 
 
56
 
57
- for simg, cstart in zip(split_data, starts):
58
- hs, ws = cstart
59
- merge_img[:, :, hs:hs + crop_size, ws:ws + crop_size] += scoremap * simg
60
- tot_score[:, :, hs:hs + crop_size, ws:ws + crop_size] += scoremap
61
 
62
- merge_img = merge_img / tot_score
63
- return merge_img
 
64
 
65
 
66
  def init():
67
- """初始化两个模型"""
68
  global dehaze_model, demoiring_model
69
 
 
 
 
70
  # 初始化去雾模型
71
  try:
72
- print("正在加载去雾模型...")
73
- dehaze_cfg = yaml.safe_load(open("dehaze_config.yml", "r"))['network_g']
74
  dehaze_cfg.pop('type', None)
75
  dehaze_model = FPro(**dehaze_cfg)
76
- dehaze_model = dehaze_model.to(device)
 
77
  dehaze_ckpt = torch.load("dehaze.pth", map_location='cpu')
78
  dehaze_model.load_state_dict(dehaze_ckpt['params'])
 
79
  dehaze_model.eval()
80
- dehaze_model = dehaze_model.cpu()
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  print("去雾模型加载成功!")
82
  except Exception as e:
83
  print(f"去雾模型加载失败: {e}")
@@ -85,77 +167,76 @@ def init():
85
 
86
  # 初始化去摩尔纹模型
87
  try:
88
- print("正在加载去摩尔纹模型...")
89
- # 尝试加载YAML配置文件
90
  try:
91
- demoiring_cfg = yaml.safe_load(open("demoiring_config.yml", "r"))['network_g']
92
  demoiring_cfg.pop('type', None)
93
  except FileNotFoundError:
94
- # 如果没有单独的配置文件,使用默认配置
95
- print("未找到去摩尔纹配置文件,使用默认配置")
96
  demoiring_cfg = {
97
- 'inp_channels': 3,
98
- 'out_channels': 3,
99
- 'dim': 48,
100
- 'num_blocks': [4, 6, 6, 8],
101
- 'num_refinement_blocks': 4,
102
- 'heads': [1, 2, 4, 8],
103
- 'ffn_expansion_factor': 2.66,
104
- 'bias': False,
105
- 'LayerNorm_type': 'WithBias',
106
- 'dual_pixel_task': False
107
  }
108
 
109
  demoiring_model = FPro(**demoiring_cfg)
110
- demoiring_model = demoiring_model.to(device)
111
  demoiring_ckpt = torch.load("deblur.pth", map_location='cpu')
112
  demoiring_model.load_state_dict(demoiring_ckpt['params'])
 
113
  demoiring_model.eval()
114
- demoiring_model = demoiring_model.cpu()
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  print("去摩尔纹模型加载成功!")
116
  except Exception as e:
117
  print(f"去摩尔纹模型加载失败: {e}")
118
  demoiring_model = None
119
 
 
 
120
 
121
- def inference(body: bytes, task_type: str = "dehaze") -> bytes:
122
- """
123
- 推理函数:支持去雾和去摩尔纹
124
 
125
- Args:
126
- body: 图像字节流
127
- task_type: 任务类型,"dehaze" 或 "demoiring"
128
 
129
- Returns:
130
- 处理后的图像字节流
131
- """
132
- # 选择对应的模型
133
  if task_type == "dehaze":
134
  if dehaze_model is None:
135
  raise Exception("去雾模型未加载")
136
  model = dehaze_model
137
- # 去雾任务的参数
138
- crop_size_arg = 256
139
- overlap_size_arg = 158
140
  elif task_type == "demoiring":
141
  if demoiring_model is None:
142
  raise Exception("去摩尔纹模型未加载")
143
  model = demoiring_model
144
- # 去摩尔纹任务的参数(根据第一个代码)
145
- crop_size_arg = 256
146
- overlap_size_arg = 200
147
  else:
148
  raise Exception(f"不支持的任务类型: {task_type}")
149
 
150
- # 加载输入图
151
  img = Image.open(BytesIO(body)).convert("RGB")
152
- arr = np.float32(img) / 255.0
153
- t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)
154
 
155
- # 确保张量在 CPU 上
156
- t = t.to(device)
 
 
 
 
 
 
157
 
158
- # Padding in case images are not multiples of 8
159
  factor = 8
160
  h, w = t.shape[2], t.shape[3]
161
  H = ((h + factor) // factor) * factor
@@ -165,52 +246,93 @@ def inference(body: bytes, task_type: str = "dehaze") -> bytes:
165
  t = F.pad(t, (0, padw, 0, padh), 'reflect')
166
 
167
  B, C, H, W = t.shape
 
168
 
169
- # 如果图像小于等于切块大小,直接处理
170
- if H <= crop_size_arg and W <= crop_size_arg:
 
 
 
 
171
  with torch.no_grad():
 
172
  restored = model(t)
173
  else:
174
- # 使用切块逻辑
175
- split_data, starts = splitimage(t, crop_size=crop_size_arg, overlap_size=overlap_size_arg)
 
 
 
176
 
177
- # 对每个切块进行推理
178
  with torch.no_grad():
179
- for i, data in enumerate(split_data):
180
- data = data.to(device)
181
- split_data[i] = model(data).cpu()
 
 
 
 
 
 
 
 
182
 
183
  # 合并结果
184
- restored = mergeimage(split_data, starts, crop_size=crop_size_arg, resolution=(B, C, H, W))
185
- restored = restored.to(device)
 
 
 
 
 
 
186
 
187
- # Unpad images to original dimensions
188
- restored = restored[:, :, :h, :w]
 
 
 
189
 
190
- # 输出处理
191
- merged = torch.clamp(restored, 0, 1).squeeze(0).permute(1, 2, 0).numpy()
192
  merged = (merged * 255).astype(np.uint8)
193
 
194
- # 输出 PNG
195
  out_img = Image.fromarray(merged)
196
  buf = BytesIO()
197
  out_img.save(buf, format="PNG")
 
 
 
 
198
  return buf.getvalue()
199
 
200
 
201
  def dehaze_inference(body: bytes) -> bytes:
202
- """去雾推理的便捷函数"""
203
- return inference(body, task_type="dehaze")
204
 
205
 
206
  def demoiring_inference(body: bytes) -> bytes:
207
- """去摩尔纹推理的便捷函数"""
208
- return inference(body, task_type="demoiring")
209
 
210
 
211
  def get_model_status():
212
- """获取模型加载状态"""
213
  return {
214
  "dehaze_model_loaded": dehaze_model is not None,
215
- "demoiring_model_loaded": demoiring_model is not None
216
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model.py - 性能优化版本
2
  import yaml, torch, math, numpy as np
3
  import torch.nn.functional as F
4
  from PIL import Image
5
  from io import BytesIO
6
  from basicsr.models.archs.FPro_arch import FPro
7
+ import time
8
+ import cv2
9
+
10
+ # 检测可用设备
11
+ if torch.cuda.is_available():
12
+ device = torch.device('cuda')
13
+ print("使用 GPU 加速")
14
+ else:
15
+ device = torch.device('cpu')
16
+ print("使用 CPU 计算")
17
+
18
+ # 全局变量
19
  dehaze_model = None
20
  demoiring_model = None
21
 
22
+ # 性能配置
23
+ PERFORMANCE_CONFIG = {
24
+ 'max_resolution': 1024, # 最大处理分辨率
25
+ 'min_crop_size': 128, # 最小切块大小
26
+ 'use_fast_mode': True, # 快速模式
27
+ 'enable_torch_compile': True, # 启用模型编译(PyTorch 2.0+)
28
+ }
29
+
30
+
31
+ def optimize_image_size(image, max_size=1024):
32
+ """智能图像尺寸优化"""
33
+ w, h = image.size
34
+
35
+ # 如果图像已经很小,直接返回
36
+ if max(w, h) <= max_size:
37
+ return image, 1.0
38
+
39
+ # 计算缩放比例
40
+ scale = max_size / max(w, h)
41
+ new_w = int(w * scale)
42
+ new_h = int(h * scale)
43
+
44
+ # 确保尺寸是8的倍数
45
+ new_w = ((new_w + 7) // 8) * 8
46
+ new_h = ((new_h + 7) // 8) * 8
47
+
48
+ resized_image = image.resize((new_w, new_h), Image.LANCZOS)
49
+ return resized_image, scale
50
+
51
+
52
+ def smart_crop_strategy(H, W, min_size=128, max_size=512):
53
+ """智能切块策略"""
54
+ # 根据图像大小动态调整切块大小
55
+ if max(H, W) <= max_size:
56
+ return H, W, 0 # 不需要切块
57
+
58
+ # 计算最优切块大小
59
+ crop_size = min(max_size, max(min_size, min(H, W) // 2))
60
+ crop_size = ((crop_size + 7) // 8) * 8 # 确保是8的倍数
61
+
62
+ # 动态调整重叠大小
63
+ overlap = min(crop_size // 4, 64)
64
 
65
+ return crop_size, crop_size, overlap
66
+
67
+
68
+ def fast_splitimage(imgtensor, crop_size=256, overlap_size=64):
69
+ """优化的切块函数 - 减少内存分配"""
70
  _, C, H, W = imgtensor.shape
71
+
72
+ # 如果图像小于切块大小,直接返回
73
+ if H <= crop_size and W <= crop_size:
74
+ return [imgtensor], [(0, 0)]
75
+
76
+ step = crop_size - overlap_size
 
 
77
  starts = []
78
+
79
+ # 预计算所有位置
80
+ h_positions = list(range(0, H - crop_size + 1, step))
81
+ w_positions = list(range(0, W - crop_size + 1, step))
82
+
83
+ # 确保覆盖边界
84
+ if h_positions[-1] + crop_size < H:
85
+ h_positions.append(H - crop_size)
86
+ if w_positions[-1] + crop_size < W:
87
+ w_positions.append(W - crop_size)
88
+
89
+ # 生成切块(延迟计算,减少内存占用)
90
+ for hs in h_positions:
91
+ for ws in w_positions:
92
  starts.append((hs, ws))
 
 
93
 
94
+ return None, starts # 返回None表示延迟切块
95
+
96
+
97
+ def fast_mergeimage(results, starts, crop_size, H, W, C, B=1):
98
+ """优化的合并函数 - 使用简化权重"""
99
+ merge_img = torch.zeros((B, C, H, W), device=device)
100
+ weight_sum = torch.zeros((B, C, H, W), device=device)
101
 
102
+ # 使用简单的线性权重而不是复杂的距离权重
103
+ edge_fade = crop_size // 8 # 边缘渐变区域
 
 
104
 
105
+ for result, (hs, ws) in zip(results, starts):
106
+ result = result.to(device)
 
 
 
 
107
 
108
+ # 创建简单权重图
109
+ weight = torch.ones_like(result)
110
 
111
+ # 只在边缘应用权重衰减
112
+ if edge_fade > 0:
113
+ # 上边缘
114
+ weight[:, :, :edge_fade, :] *= torch.linspace(0.1, 1.0, edge_fade).view(1, 1, -1, 1)
115
+ # 下边缘
116
+ weight[:, :, -edge_fade:, :] *= torch.linspace(1.0, 0.1, edge_fade).view(1, 1, -1, 1)
117
+ # 左边缘
118
+ weight[:, :, :, :edge_fade] *= torch.linspace(0.1, 1.0, edge_fade).view(1, 1, 1, -1)
119
+ # 右边缘
120
+ weight[:, :, :, -edge_fade:] *= torch.linspace(1.0, 0.1, edge_fade).view(1, 1, 1, -1)
121
 
122
+ merge_img[:, :, hs:hs + crop_size, ws:ws + crop_size] += weight * result
123
+ weight_sum[:, :, hs:hs + crop_size, ws:ws + crop_size] += weight
 
 
124
 
125
+ # 避免除零
126
+ weight_sum = torch.clamp(weight_sum, min=1e-8)
127
+ return merge_img / weight_sum
128
 
129
 
130
  def init():
131
+ """优化的模型初始化"""
132
  global dehaze_model, demoiring_model
133
 
134
+ print("正在初始化模型...")
135
+ start_time = time.time()
136
+
137
  # 初始化去雾模型
138
  try:
139
+ print("加载去雾模型...")
140
+ dehaze_cfg = yaml.safe_load(open("RealDehazing_FPro.yml", "r"))['network_g']
141
  dehaze_cfg.pop('type', None)
142
  dehaze_model = FPro(**dehaze_cfg)
143
+
144
+ # 加载权重
145
  dehaze_ckpt = torch.load("dehaze.pth", map_location='cpu')
146
  dehaze_model.load_state_dict(dehaze_ckpt['params'])
147
+ dehaze_model.to(device)
148
  dehaze_model.eval()
149
+
150
+ # 模型编译优化 (PyTorch 2.0+)
151
+ if PERFORMANCE_CONFIG['enable_torch_compile'] and hasattr(torch, 'compile'):
152
+ try:
153
+ dehaze_model = torch.compile(dehaze_model)
154
+ print("去雾模型编译优化成功")
155
+ except Exception as e:
156
+ print(f"模型编译失败: {e}")
157
+
158
+ # 预热模型
159
+ with torch.no_grad():
160
+ dummy_input = torch.randn(1, 3, 256, 256).to(device)
161
+ _ = dehaze_model(dummy_input)
162
+
163
  print("去雾模型加载成功!")
164
  except Exception as e:
165
  print(f"去雾模型加载失败: {e}")
 
167
 
168
  # 初始化去摩尔纹模型
169
  try:
170
+ print("加载去摩尔纹模型...")
 
171
  try:
172
+ demoiring_cfg = yaml.safe_load(open("RealDemoiring_FPro.yml", "r"))['network_g']
173
  demoiring_cfg.pop('type', None)
174
  except FileNotFoundError:
 
 
175
  demoiring_cfg = {
176
+ 'inp_channels': 3, 'out_channels': 3, 'dim': 48,
177
+ 'num_blocks': [4, 6, 6, 8], 'num_refinement_blocks': 4,
178
+ 'heads': [1, 2, 4, 8], 'ffn_expansion_factor': 2.66,
179
+ 'bias': False, 'LayerNorm_type': 'WithBias', 'dual_pixel_task': False
 
 
 
 
 
 
180
  }
181
 
182
  demoiring_model = FPro(**demoiring_cfg)
 
183
  demoiring_ckpt = torch.load("deblur.pth", map_location='cpu')
184
  demoiring_model.load_state_dict(demoiring_ckpt['params'])
185
+ demoiring_model.to(device)
186
  demoiring_model.eval()
187
+
188
+ # 模型编译优化
189
+ if PERFORMANCE_CONFIG['enable_torch_compile'] and hasattr(torch, 'compile'):
190
+ try:
191
+ demoiring_model = torch.compile(demoiring_model)
192
+ print("去摩尔纹模型编译优化成功")
193
+ except Exception as e:
194
+ print(f"模型编译失败: {e}")
195
+
196
+ # 预热模型
197
+ with torch.no_grad():
198
+ dummy_input = torch.randn(1, 3, 256, 256).to(device)
199
+ _ = demoiring_model(dummy_input)
200
+
201
  print("去摩尔纹模型加载成功!")
202
  except Exception as e:
203
  print(f"去摩尔纹模型加载失败: {e}")
204
  demoiring_model = None
205
 
206
+ init_time = time.time() - start_time
207
+ print(f"模型初始化完成,耗时: {init_time:.2f}秒")
208
 
 
 
 
209
 
210
+ def fast_inference(body: bytes, task_type: str = "dehaze") -> bytes:
211
+ """优化的推理函数"""
212
+ start_time = time.time()
213
 
214
+ # 选择模型
 
 
 
215
  if task_type == "dehaze":
216
  if dehaze_model is None:
217
  raise Exception("去雾模型未加载")
218
  model = dehaze_model
 
 
 
219
  elif task_type == "demoiring":
220
  if demoiring_model is None:
221
  raise Exception("去摩尔纹模型未加载")
222
  model = demoiring_model
 
 
 
223
  else:
224
  raise Exception(f"不支持的任务类型: {task_type}")
225
 
226
+ # 图像加载和预处理
227
  img = Image.open(BytesIO(body)).convert("RGB")
228
+ original_size = img.size
 
229
 
230
+ # 智能尺寸优化
231
+ if PERFORMANCE_CONFIG['use_fast_mode']:
232
+ img, scale_factor = optimize_image_size(img, PERFORMANCE_CONFIG['max_resolution'])
233
+ print(f"图像缩放比例: {scale_factor:.2f}")
234
+
235
+ # 转换为张量
236
+ arr = np.float32(img) / 255.0
237
+ t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(device)
238
 
239
+ # Padding
240
  factor = 8
241
  h, w = t.shape[2], t.shape[3]
242
  H = ((h + factor) // factor) * factor
 
246
  t = F.pad(t, (0, padw, 0, padh), 'reflect')
247
 
248
  B, C, H, W = t.shape
249
+ print(f"处理图像尺寸: {H}x{W}")
250
 
251
+ # 智能切块策略
252
+ crop_size, _, overlap_size = smart_crop_strategy(H, W)
253
+
254
+ if crop_size == H and crop_size == W:
255
+ # 小图像直接处理
256
+ print("直接处理整图")
257
  with torch.no_grad():
258
+ torch.cuda.empty_cache() if torch.cuda.is_available() else None
259
  restored = model(t)
260
  else:
261
+ # 大图像切块处理
262
+ print(f"切块处理,切块大小: {crop_size}x{crop_size}, 重叠: {overlap_size}")
263
+
264
+ # 获取切块位置
265
+ _, starts = fast_splitimage(t, crop_size, overlap_size)
266
 
267
+ results = []
268
  with torch.no_grad():
269
+ for i, (hs, ws) in enumerate(starts):
270
+ if torch.cuda.is_available():
271
+ torch.cuda.empty_cache()
272
+
273
+ # 动态切块
274
+ patch = t[:, :, hs:hs + crop_size, ws:ws + crop_size]
275
+ result = model(patch)
276
+ results.append(result.cpu()) # 立即移到CPU释放GPU内存
277
+
278
+ if i % 5 == 0: # 每5个切块打印一次进度
279
+ print(f"处理进度: {i + 1}/{len(starts)}")
280
 
281
  # 合并结果
282
+ print("合并结果...")
283
+ # 将结果移回GPU进行合并
284
+ results = [r.to(device) for r in results]
285
+ restored = fast_mergeimage(results, starts, crop_size, H, W, C, B)
286
+
287
+ # 后处理
288
+ restored = restored[:, :, :h, :w] # 去除padding
289
+ merged = torch.clamp(restored, 0, 1).cpu().squeeze(0).permute(1, 2, 0).numpy()
290
 
291
+ # 恢复原始尺寸
292
+ if PERFORMANCE_CONFIG['use_fast_mode'] and scale_factor < 1.0:
293
+ merged_img = Image.fromarray((merged * 255).astype(np.uint8))
294
+ merged_img = merged_img.resize(original_size, Image.LANCZOS)
295
+ merged = np.array(merged_img).astype(np.float32) / 255.0
296
 
 
 
297
  merged = (merged * 255).astype(np.uint8)
298
 
299
+ # 输出
300
  out_img = Image.fromarray(merged)
301
  buf = BytesIO()
302
  out_img.save(buf, format="PNG")
303
+
304
+ total_time = time.time() - start_time
305
+ print(f"总���理时间: {total_time:.2f}秒")
306
+
307
  return buf.getvalue()
308
 
309
 
310
  def dehaze_inference(body: bytes) -> bytes:
311
+ """去雾推理"""
312
+ return fast_inference(body, task_type="dehaze")
313
 
314
 
315
  def demoiring_inference(body: bytes) -> bytes:
316
+ """去摩尔纹推理"""
317
+ return fast_inference(body, task_type="demoiring")
318
 
319
 
320
  def get_model_status():
321
+ """获取模型状态"""
322
  return {
323
  "dehaze_model_loaded": dehaze_model is not None,
324
+ "demoiring_model_loaded": demoiring_model is not None,
325
+ "device": str(device),
326
+ "performance_mode": "Fast" if PERFORMANCE_CONFIG['use_fast_mode'] else "Quality"
327
+ }
328
+
329
+
330
+ def update_performance_config(max_resolution=1024, fast_mode=True):
331
+ """更新性能配置"""
332
+ PERFORMANCE_CONFIG['max_resolution'] = max_resolution
333
+ PERFORMANCE_CONFIG['use_fast_mode'] = fast_mode
334
+ print(f"性能配置更新: 最大分辨率={max_resolution}, 快速模式={'开启' if fast_mode else '关闭'}")
335
+
336
+
337
+ # 兼容性函数
338
+ inference = fast_inference