Thekingbalxd commited on
Commit
1ca0559
·
verified ·
1 Parent(s): 8839f25

Create inference_codeformer_cpu.py

Browse files
Files changed (1) hide show
  1. inference_codeformer_cpu.py +266 -0
inference_codeformer_cpu.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # inference_codeformer_cpu.py
3
+ # CPU-only változat — kényszeríti a futást CPU-ra, letiltva a CUDA/half logikát.
4
+
5
+ import os
6
+ # Kényszerítjük, hogy a PyTorch ne lássa a GPU-kat
7
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
8
+
9
+ import warnings
10
+ import cv2
11
+ import argparse
12
+ import glob
13
+ import torch
14
+ from torchvision.transforms.functional import normalize
15
+ from basicsr.utils import imwrite, img2tensor, tensor2img
16
+ from basicsr.utils.download_util import load_file_from_url
17
+ from facelib.utils.face_restoration_helper import FaceRestoreHelper
18
+ from facelib.utils.misc import is_gray
19
+ from basicsr.utils.registry import ARCH_REGISTRY
20
+
21
+ pretrain_model_url = {
22
+ 'restoration': 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth',
23
+ }
24
+
25
+ def set_realesrgan(args):
26
+ """
27
+ CPU esetén letiltjuk a RealESRGAN-t (visszatér None-nal).
28
+ Ha valaki mégis GPU-val futtatná és CUDA elérhető, itt létrehozzuk az upsampler-t.
29
+ (A környezetünk CPU-only, így ez a függvény tipikusan None-t ad vissza.)
30
+ """
31
+ # importok helyben, mert ez a funkció opcionális
32
+ from basicsr.archs.rrdbnet_arch import RRDBNet
33
+ from basicsr.utils.realesrgan_utils import RealESRGANer
34
+
35
+ # CPU környezetben nem használunk fp16-et
36
+ use_half = False
37
+
38
+ if not torch.cuda.is_available():
39
+ warnings.warn('RealESRGAN: CUDA nem elérhető; a háttér feljavítás CPU-n letiltva.', RuntimeWarning)
40
+ return None
41
+
42
+ # Ha itt valaki GPU-n futtatja (nem jellemző ebben a CPU-only scriptben):
43
+ model = RRDBNet(
44
+ num_in_ch=3,
45
+ num_out_ch=3,
46
+ num_feat=64,
47
+ num_block=23,
48
+ num_grow_ch=32,
49
+ scale=2,
50
+ )
51
+ upsampler = RealESRGANer(
52
+ scale=2,
53
+ model_path="https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth",
54
+ model=model,
55
+ tile=args.bg_tile,
56
+ tile_pad=40,
57
+ pre_pad=0,
58
+ half=use_half
59
+ )
60
+ return upsampler
61
+
62
+ if __name__ == '__main__':
63
+ # explicit CPU device
64
+ device = torch.device("cpu")
65
+
66
+ parser = argparse.ArgumentParser()
67
+
68
+ parser.add_argument('-i', '--input_path', type=str, default='./inputs/whole_imgs',
69
+ help='Input image, video or folder. Default: inputs/whole_imgs')
70
+ parser.add_argument('-o', '--output_path', type=str, default=None,
71
+ help='Output folder. Default: results/<input_name>_<w>')
72
+ parser.add_argument('-w', '--fidelity_weight', type=float, default=0.5,
73
+ help='Balance the quality and fidelity. Default: 0.5')
74
+ parser.add_argument('-s', '--upscale', type=int, default=2,
75
+ help='The final upsampling scale of the image. Default: 2')
76
+ parser.add_argument('--has_aligned', action='store_true', help='Input are cropped and aligned faces. Default: False')
77
+ parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face. Default: False')
78
+ parser.add_argument('--draw_box', action='store_true', help='Draw the bounding box for the detected faces. Default: False')
79
+ # large det_model: 'YOLOv5l', 'retinaface_resnet50'
80
+ # small det_model: 'YOLOv5n', 'retinaface_mobile0.25'
81
+ parser.add_argument('--detection_model', type=str, default='retinaface_mobile0.25',
82
+ help='Face detector. Optional: retinaface_resnet50, retinaface_mobile0.25, YOLOv5l, YOLOv5n, dlib. Default: retinaface_mobile0.25')
83
+ parser.add_argument('--bg_upsampler', type=str, default='None', help='Background upsampler. Optional: realesrgan')
84
+ parser.add_argument('--face_upsample', action='store_true', help='Face upsampler after enhancement. Default: False')
85
+ parser.add_argument('--bg_tile', type=int, default=400, help='Tile size for background sampler. Default: 400')
86
+ parser.add_argument('--suffix', type=str, default=None, help='Suffix of the restored faces. Default: None')
87
+ parser.add_argument('--save_video_fps', type=float, default=None, help='Frame rate for saving video. Default: None')
88
+
89
+ args = parser.parse_args()
90
+
91
+ # ------------------------ input & output ------------------------
92
+ w = args.fidelity_weight
93
+ input_video = False
94
+ if args.input_path.endswith(('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG')): # input single img path
95
+ input_img_list = [args.input_path]
96
+ result_root = f'results/test_img_{w}'
97
+ elif args.input_path.endswith(('mp4', 'mov', 'avi', 'MP4', 'MOV', 'AVI')): # input video path
98
+ from basicsr.utils.video_util import VideoReader, VideoWriter
99
+ input_img_list = []
100
+ vidreader = VideoReader(args.input_path)
101
+ image = vidreader.get_frame()
102
+ while image is not None:
103
+ input_img_list.append(image)
104
+ image = vidreader.get_frame()
105
+ audio = vidreader.get_audio()
106
+ fps = vidreader.get_fps() if args.save_video_fps is None else args.save_video_fps
107
+ video_name = os.path.basename(args.input_path)[:-4]
108
+ result_root = f'results/{video_name}_{w}'
109
+ input_video = True
110
+ vidreader.close()
111
+ else: # input img folder
112
+ if args.input_path.endswith('/'):
113
+ args.input_path = args.input_path[:-1]
114
+ input_img_list = sorted(glob.glob(os.path.join(args.input_path, '*.[jpJP][pnPN]*[gG]')))
115
+ result_root = f'results/{os.path.basename(args.input_path)}_{w}'
116
+
117
+ if not args.output_path is None:
118
+ result_root = args.output_path
119
+
120
+ test_img_num = len(input_img_list)
121
+ if test_img_num == 0:
122
+ raise FileNotFoundError('No input image/video is found...\n'
123
+ '\tNote that --input_path for video should end with .mp4|.mov|.avi')
124
+
125
+ # ------------------ set up background upsampler ------------------
126
+ bg_upsampler = None
127
+ if args.bg_upsampler == 'realesrgan':
128
+ bg_upsampler = set_realesrgan(args)
129
+
130
+ # ------------------ set up face upsampler ------------------
131
+ if args.face_upsample:
132
+ if bg_upsampler is not None:
133
+ face_upsampler = bg_upsampler
134
+ else:
135
+ # próbáljuk létrehozni, de valószínűleg CPU-n None lesz
136
+ face_upsampler = set_realesrgan(args)
137
+ else:
138
+ face_upsampler = None
139
+
140
+ # ------------------ set up CodeFormer restorer -------------------
141
+ net = ARCH_REGISTRY.get('CodeFormer')(dim_embd=512, codebook_size=1024, n_head=8, n_layers=9,
142
+ connect_list=['32', '64', '128', '256']).to(device)
143
+
144
+ ckpt_path = load_file_from_url(url=pretrain_model_url['restoration'],
145
+ model_dir='weights/CodeFormer', progress=True, file_name=None)
146
+ # CPU-on fontos: map_location="cpu"
147
+ checkpoint = torch.load(ckpt_path, map_location='cpu')['params_ema']
148
+ net.load_state_dict(checkpoint)
149
+ net.eval()
150
+
151
+ # ------------------ set up FaceRestoreHelper -------------------
152
+ if not args.has_aligned:
153
+ print(f'Face detection model: {args.detection_model}')
154
+ if bg_upsampler is not None:
155
+ print(f'Background upsampling: True, Face upsampling: {args.face_upsample}')
156
+ else:
157
+ print(f'Background upsampling: False, Face upsampling: {args.face_upsample}')
158
+
159
+ face_helper = FaceRestoreHelper(
160
+ args.upscale,
161
+ face_size=512,
162
+ crop_ratio=(1, 1),
163
+ det_model = args.detection_model,
164
+ save_ext='png',
165
+ use_parse=True,
166
+ device=device)
167
+
168
+ # -------------------- start processing ---------------------
169
+ for i, img_path in enumerate(input_img_list):
170
+ face_helper.clean_all()
171
+
172
+ if isinstance(img_path, str):
173
+ img_name = os.path.basename(img_path)
174
+ basename, ext = os.path.splitext(img_name)
175
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
176
+ img = cv2.imread(img_path, cv2.IMREAD_COLOR)
177
+ else:
178
+ basename = str(i).zfill(6)
179
+ img_name = f'{video_name}_{basename}' if input_video else basename
180
+ print(f'[{i+1}/{test_img_num}] Processing: {img_name}')
181
+ img = img_path
182
+
183
+ if args.has_aligned:
184
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_LINEAR)
185
+ face_helper.is_gray = is_gray(img, threshold=10)
186
+ if face_helper.is_gray:
187
+ print('Grayscale input: True')
188
+ face_helper.cropped_faces = [img]
189
+ else:
190
+ face_helper.read_image(img)
191
+ num_det_faces = face_helper.get_face_landmarks_5(
192
+ only_center_face=args.only_center_face, resize=640, eye_dist_threshold=5)
193
+ print(f'\tdetect {num_det_faces} faces')
194
+ face_helper.align_warp_face()
195
+
196
+ # face restoration for each cropped face
197
+ for idx, cropped_face in enumerate(face_helper.cropped_faces):
198
+ cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
199
+ normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
200
+ cropped_face_t = cropped_face_t.unsqueeze(0).to(device)
201
+
202
+ try:
203
+ with torch.no_grad():
204
+ output = net(cropped_face_t, w=w, adain=True)[0]
205
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
206
+ # CPU-n nincs torch.cuda.empty_cache()
207
+ except Exception as error:
208
+ print(f'\tFailed inference for CodeFormer: {error}')
209
+ restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
210
+
211
+ restored_face = restored_face.astype('uint8')
212
+ face_helper.add_restored_face(restored_face, cropped_face)
213
+
214
+ # paste_back
215
+ if not args.has_aligned:
216
+ # upsample the background (valószínűleg None CPU-n)
217
+ if bg_upsampler is not None:
218
+ bg_img = bg_upsampler.enhance(img, outscale=args.upscale)[0]
219
+ else:
220
+ bg_img = None
221
+ face_helper.get_inverse_affine(None)
222
+ if args.face_upsample and face_upsampler is not None:
223
+ restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box, face_upsampler=face_upsampler)
224
+ else:
225
+ restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=args.draw_box)
226
+
227
+ # save faces
228
+ for idx, (cropped_face, restored_face) in enumerate(zip(face_helper.cropped_faces, face_helper.restored_faces)):
229
+ if not args.has_aligned:
230
+ save_crop_path = os.path.join(result_root, 'cropped_faces', f'{basename}_{idx:02d}.png')
231
+ imwrite(cropped_face, save_crop_path)
232
+ if args.has_aligned:
233
+ save_face_name = f'{basename}.png'
234
+ else:
235
+ save_face_name = f'{basename}_{idx:02d}.png'
236
+ if args.suffix is not None:
237
+ save_face_name = f'{save_face_name[:-4]}_{args.suffix}.png'
238
+ save_restore_path = os.path.join(result_root, 'restored_faces', save_face_name)
239
+ imwrite(restored_face, save_restore_path)
240
+
241
+ # save restored img
242
+ if not args.has_aligned and restored_img is not None:
243
+ if args.suffix is not None:
244
+ basename = f'{basename}_{args.suffix}'
245
+ save_restore_path = os.path.join(result_root, 'final_results', f'{basename}.png')
246
+ imwrite(restored_img, save_restore_path)
247
+
248
+ # save enhanced video
249
+ if input_video:
250
+ print('Video Saving...')
251
+ video_frames = []
252
+ img_list = sorted(glob.glob(os.path.join(result_root, 'final_results', '*.[jp][pn]g')))
253
+ for img_path in img_list:
254
+ img = cv2.imread(img_path)
255
+ video_frames.append(img)
256
+ height, width = video_frames[0].shape[:2]
257
+ if args.suffix is not None:
258
+ video_name = f'{video_name}_{args.suffix}.png'
259
+ save_restore_path = os.path.join(result_root, f'{video_name}.mp4')
260
+ vidwriter = VideoWriter(save_restore_path, height, width, fps, audio)
261
+
262
+ for f in video_frames:
263
+ vidwriter.write_frame(f)
264
+ vidwriter.close()
265
+
266
+ print(f'\nAll results are saved in {result_root}')