GFPGAN
/
cog_predict.py
161 строка · 6.6 Кб
1# flake8: noqa
2# This file is used for deploying replicate models
3# running: cog predict -i img=@inputs/whole_imgs/10045.png -i version='v1.4' -i scale=2
4# push: cog push r8.im/tencentarc/gfpgan
5# push (backup): cog push r8.im/xinntao/gfpgan
6
7import os8
9os.system('python setup.py develop')10os.system('pip install realesrgan')11
12import cv213import shutil14import tempfile15import torch16from basicsr.archs.srvgg_arch import SRVGGNetCompact17
18from gfpgan import GFPGANer19
20try:21from cog import BasePredictor, Input, Path22from realesrgan.utils import RealESRGANer23except Exception:24print('please install cog and realesrgan package')25
26
27class Predictor(BasePredictor):28
29def setup(self):30os.makedirs('output', exist_ok=True)31# download weights32if not os.path.exists('gfpgan/weights/realesr-general-x4v3.pth'):33os.system(34'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./gfpgan/weights'35)36if not os.path.exists('gfpgan/weights/GFPGANv1.2.pth'):37os.system(38'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth -P ./gfpgan/weights')39if not os.path.exists('gfpgan/weights/GFPGANv1.3.pth'):40os.system(41'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P ./gfpgan/weights')42if not os.path.exists('gfpgan/weights/GFPGANv1.4.pth'):43os.system(44'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./gfpgan/weights')45if not os.path.exists('gfpgan/weights/RestoreFormer.pth'):46os.system(47'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth -P ./gfpgan/weights'48)49
50# background enhancer with RealESRGAN51model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')52model_path = 'gfpgan/weights/realesr-general-x4v3.pth'53half = True if torch.cuda.is_available() else False54self.upsampler = RealESRGANer(55scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)56
57# Use GFPGAN for face enhancement58self.face_enhancer = GFPGANer(59model_path='gfpgan/weights/GFPGANv1.4.pth',60upscale=2,61arch='clean',62channel_multiplier=2,63bg_upsampler=self.upsampler)64self.current_version = 'v1.4'65
66def predict(67self,68img: Path = Input(description='Input'),69version: str = Input(70description='GFPGAN version. v1.3: better quality. v1.4: more details and better identity.',71choices=['v1.2', 'v1.3', 'v1.4', 'RestoreFormer'],72default='v1.4'),73scale: float = Input(description='Rescaling factor', default=2),74) -> Path:75weight = 0.576print(img, version, scale, weight)77try:78extension = os.path.splitext(os.path.basename(str(img)))[1]79img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)80if len(img.shape) == 3 and img.shape[2] == 4:81img_mode = 'RGBA'82elif len(img.shape) == 2:83img_mode = None84img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)85else:86img_mode = None87
88h, w = img.shape[0:2]89if h < 300:90img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)91
92if self.current_version != version:93if version == 'v1.2':94self.face_enhancer = GFPGANer(95model_path='gfpgan/weights/GFPGANv1.2.pth',96upscale=2,97arch='clean',98channel_multiplier=2,99bg_upsampler=self.upsampler)100self.current_version = 'v1.2'101elif version == 'v1.3':102self.face_enhancer = GFPGANer(103model_path='gfpgan/weights/GFPGANv1.3.pth',104upscale=2,105arch='clean',106channel_multiplier=2,107bg_upsampler=self.upsampler)108self.current_version = 'v1.3'109elif version == 'v1.4':110self.face_enhancer = GFPGANer(111model_path='gfpgan/weights/GFPGANv1.4.pth',112upscale=2,113arch='clean',114channel_multiplier=2,115bg_upsampler=self.upsampler)116self.current_version = 'v1.4'117elif version == 'RestoreFormer':118self.face_enhancer = GFPGANer(119model_path='gfpgan/weights/RestoreFormer.pth',120upscale=2,121arch='RestoreFormer',122channel_multiplier=2,123bg_upsampler=self.upsampler)124
125try:126_, _, output = self.face_enhancer.enhance(127img, has_aligned=False, only_center_face=False, paste_back=True, weight=weight)128except RuntimeError as error:129print('Error', error)130
131try:132if scale != 2:133interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4134h, w = img.shape[0:2]135output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation)136except Exception as error:137print('wrong scale input.', error)138
139if img_mode == 'RGBA': # RGBA images should be saved in png format140extension = 'png'141# save_path = f'output/out.{extension}'142# cv2.imwrite(save_path, output)143out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'144cv2.imwrite(str(out_path), output)145except Exception as error:146print('global exception: ', error)147finally:148clean_folder('output')149return out_path150
151
152def clean_folder(folder):153for filename in os.listdir(folder):154file_path = os.path.join(folder, filename)155try:156if os.path.isfile(file_path) or os.path.islink(file_path):157os.unlink(file_path)158elif os.path.isdir(file_path):159shutil.rmtree(file_path)160except Exception as e:161print(f'Failed to delete {file_path}. Reason: {e}')162