Team Ai
Apppublic

LULDev/Image-Upscaler-GFPGAN-Algorithm

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py114 linesDownload Raw Back to root
1import os2 3import sys4from torchvision.transforms import functional5sys.modules["torchvision.transforms.functional_tensor"] = functional6 7from basicsr.archs.srvgg_arch import SRVGGNetCompact8from gfpgan.utils import GFPGANer9from realesrgan.utils import RealESRGANer10 11import torch12import cv213import gradio as gr14 15 16#Download Required Models17if not os.path.exists('realesr-general-x4v3.pth'):18    os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P .")19if not os.path.exists('GFPGANv1.2.pth'):20    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth -P .")21if not os.path.exists('GFPGANv1.3.pth'):22    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P .")23if not os.path.exists('GFPGANv1.4.pth'):24    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .")25if not os.path.exists('RestoreFormer.pth'):26    os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth -P .")27 28 29model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')30model_path = 'realesr-general-x4v3.pth'31half = True if torch.cuda.is_available() else False32upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)33 34 35# Save Image to the Directory36# os.makedirs('output', exist_ok=True)37 38def upscaler(img, version, scale):39 40    try:41        42        img = cv2.imread(img, cv2.IMREAD_UNCHANGED)43        if len(img.shape) == 3 and img.shape[2] == 4:44            img_mode = 'RGBA'45        elif len(img.shape) == 2:46            img_mode = None47            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)48        else:49            img_mode = None50 51 52        h, w = img.shape[0:2]53        if h < 300:54            img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)55 56        57        face_enhancer = GFPGANer(58            model_path=f'{version}.pth', 59            upscale=2, 60            arch='RestoreFormer' if version=='RestoreFormer' else 'clean',61            channel_multiplier=2,62            bg_upsampler=upsampler63        )64 65 66        try:67            _, _, output = face_enhancer.enhance(img, has_aligned=False, only_center_face=False, paste_back=True)68        except RuntimeError as error:69            print('Error', error)70 71 72        try:73            if scale != 2:74                interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS475                h, w = img.shape[0:2]76                output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation)77        except Exception as error:78            print('wrong scale input.', error)79 80        # Save Image to the Directory81        # ext = os.path.splitext(os.path.basename(str(img)))[1]82        # if img_mode == 'RGBA':83        #     ext = 'png'84        # else:85        #     ext = 'jpg'86        #87        # save_path = f'output/out.{ext}'88        # cv2.imwrite(save_path, output)89        # return output, save_path90 91        output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)92        return output93    except Exception as error:94        print('global exception', error)95        return None, None96 97if __name__ == "__main__":98 99    title = "Image Upscaler & Restoring [GFPGAN Algorithm]"100 101    demo = gr.Interface(102            upscaler, [103                gr.Image(type="filepath", label="Input"),104                gr.Radio(['GFPGANv1.2', 'GFPGANv1.3', 'GFPGANv1.4', 'RestoreFormer'], type="value", label='version'),105                gr.Number(label="Rescaling factor"),106            ], [107                gr.Image(type="numpy", label="Output"),108            ],109            title=title,110            allow_flagging="never"111        )112 113    demo.queue()114    demo.launch()