CoolFace
Apppublic

Kims12/2-2_Image-Upscaler-and-Restoring-GFPGAN-Algorithm

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py93 linesDownload Raw Back to root
1import os2import sys3from torchvision.transforms import functional4sys.modules["torchvision.transforms.functional_tensor"] = functional5 6from basicsr.archs.srvgg_arch import SRVGGNetCompact7from gfpgan.utils import GFPGANer8from realesrgan.utils import RealESRGANer9 10import torch11import cv212import gradio as gr13 14# 필수 모델 다운로드15if not os.path.exists('realesr-general-x4v3.pth'):16    os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P .")17if not os.path.exists('GFPGANv1.2.pth'):18    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth -P .")19if not os.path.exists('GFPGANv1.3.pth'):20    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P .")21if not os.path.exists('GFPGANv1.4.pth'):22    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .")23if not os.path.exists('RestoreFormer.pth'):24    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth -P .")25 26model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')27model_path = 'realesr-general-x4v3.pth'28half = True if torch.cuda.is_available() else False29upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)30 31# 이미지 저장 디렉토리 생성 (필요시 주석 해제)32# os.makedirs('output', exist_ok=True)33 34def upscaler(img, version, scale):35    try:36        img = cv2.imread(img, cv2.IMREAD_UNCHANGED)37        if len(img.shape) == 3 and img.shape[2] == 4:38            img_mode = 'RGBA'39        elif len(img.shape) == 2:40            img_mode = None41            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)42        else:43            img_mode = None44 45        h, w = img.shape[0:2]46        if h < 300:47            img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)48 49        face_enhancer = GFPGANer(50            model_path=f'{version}.pth',51            upscale=2,52            arch='RestoreFormer' if version=='RestoreFormer' else 'clean',53            channel_multiplier=2,54            bg_upsampler=upsampler55        )56 57        try:58            _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)59        except RuntimeError as error:60            print('오류', error)61 62        try:63            if scale != 2:64                interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS465                h, w = img.shape[0:2]66                output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation)67        except Exception as error:68            print('잘못된 재스케일링 입력.', error)69 70        output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)71        return output72    except Exception as error:73        print('전역 예외', error)74        return None, None75 76if __name__ == "__main__":77    title = "이미지 업스케일 및 복원 [GFPGAN 알고리즘]"78 79    demo = gr.Interface(80            upscaler, [81                gr.Image(type="filepath", label="입력"),82                gr.Radio(['GFPGANv1.2', 'GFPGANv1.3', 'GFPGANv1.4', 'RestoreFormer'], type="value", label="버전", value="GFPGANv1.4", visible=False),83                gr.Number(label="재스케일링 계수", value=0, visible=False),84            ], [85                gr.Image(type="numpy", label="출력"),86            ],87            title=title,88            examples=[["예제.png", "GFPGANv1.4", 0]],89            allow_flagging="never"90        )91 92    demo.queue()93    demo.launch()