Real-ESRGAN
/
cog_predict.py
148 строк · 6.5 Кб
1# flake8: noqa
2# This file is used for deploying replicate models
3# running: cog predict -i img=@inputs/00017_gray.png -i version='General - v3' -i scale=2 -i face_enhance=True -i tile=0
4# push: cog push r8.im/xinntao/realesrgan
5
6import os
7
8os.system('pip install gfpgan')
9os.system('python setup.py develop')
10
11import cv2
12import shutil
13import tempfile
14import torch
15from basicsr.archs.rrdbnet_arch import RRDBNet
16from basicsr.archs.srvgg_arch import SRVGGNetCompact
17
18from realesrgan.utils import RealESRGANer
19
20try:
21from cog import BasePredictor, Input, Path
22from gfpgan import GFPGANer
23except 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 weights
32if not os.path.exists('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 ./weights'
35)
36if not os.path.exists('weights/GFPGANv1.4.pth'):
37os.system('wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./weights')
38if not os.path.exists('weights/RealESRGAN_x4plus.pth'):
39os.system(
40'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./weights'
41)
42if not os.path.exists('weights/RealESRGAN_x4plus_anime_6B.pth'):
43os.system(
44'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P ./weights'
45)
46if not os.path.exists('weights/realesr-animevideov3.pth'):
47os.system(
48'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P ./weights'
49)
50
51def choose_model(self, scale, version, tile=0):
52half = True if torch.cuda.is_available() else False
53if version == 'General - RealESRGANplus':
54model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
55model_path = 'weights/RealESRGAN_x4plus.pth'
56self.upsampler = RealESRGANer(
57scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
58elif version == 'General - v3':
59model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
60model_path = 'weights/realesr-general-x4v3.pth'
61self.upsampler = RealESRGANer(
62scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
63elif version == 'Anime - anime6B':
64model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
65model_path = 'weights/RealESRGAN_x4plus_anime_6B.pth'
66self.upsampler = RealESRGANer(
67scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
68elif version == 'AnimeVideo - v3':
69model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
70model_path = 'weights/realesr-animevideov3.pth'
71self.upsampler = RealESRGANer(
72scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
73
74self.face_enhancer = GFPGANer(
75model_path='weights/GFPGANv1.4.pth',
76upscale=scale,
77arch='clean',
78channel_multiplier=2,
79bg_upsampler=self.upsampler)
80
81def predict(
82self,
83img: Path = Input(description='Input'),
84version: str = Input(
85description='RealESRGAN version. Please see [Readme] below for more descriptions',
86choices=['General - RealESRGANplus', 'General - v3', 'Anime - anime6B', 'AnimeVideo - v3'],
87default='General - v3'),
88scale: float = Input(description='Rescaling factor', default=2),
89face_enhance: bool = Input(
90description='Enhance faces with GFPGAN. Note that it does not work for anime images/vidoes', default=False),
91tile: int = Input(
92description=
93'Tile size. Default is 0, that is no tile. When encountering the out-of-GPU-memory issue, please specify it, e.g., 400 or 200',
94default=0)
95) -> Path:
96if tile <= 100 or tile is None:
97tile = 0
98print(f'img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}.')
99try:
100extension = os.path.splitext(os.path.basename(str(img)))[1]
101img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)
102if len(img.shape) == 3 and img.shape[2] == 4:
103img_mode = 'RGBA'
104elif len(img.shape) == 2:
105img_mode = None
106img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
107else:
108img_mode = None
109
110h, w = img.shape[0:2]
111if h < 300:
112img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
113
114self.choose_model(scale, version, tile)
115
116try:
117if face_enhance:
118_, _, output = self.face_enhancer.enhance(
119img, has_aligned=False, only_center_face=False, paste_back=True)
120else:
121output, _ = self.upsampler.enhance(img, outscale=scale)
122except RuntimeError as error:
123print('Error', error)
124print('If you encounter CUDA out of memory, try to set "tile" to a smaller size, e.g., 400.')
125
126if img_mode == 'RGBA': # RGBA images should be saved in png format
127extension = 'png'
128# save_path = f'output/out.{extension}'
129# cv2.imwrite(save_path, output)
130out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'
131cv2.imwrite(str(out_path), output)
132except Exception as error:
133print('global exception: ', error)
134finally:
135clean_folder('output')
136return out_path
137
138
139def clean_folder(folder):
140for filename in os.listdir(folder):
141file_path = os.path.join(folder, filename)
142try:
143if os.path.isfile(file_path) or os.path.islink(file_path):
144os.unlink(file_path)
145elif os.path.isdir(file_path):
146shutil.rmtree(file_path)
147except Exception as e:
148print(f'Failed to delete {file_path}. Reason: {e}')
149