Real-ESRGAN

Форк
0
/
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

6
import os
7

8
os.system('pip install gfpgan')
9
os.system('python setup.py develop')
10

11
import cv2
12
import shutil
13
import tempfile
14
import torch
15
from basicsr.archs.rrdbnet_arch import RRDBNet
16
from basicsr.archs.srvgg_arch import SRVGGNetCompact
17

18
from realesrgan.utils import RealESRGANer
19

20
try:
21
    from cog import BasePredictor, Input, Path
22
    from gfpgan import GFPGANer
23
except Exception:
24
    print('please install cog and realesrgan package')
25

26

27
class Predictor(BasePredictor):
28

29
    def setup(self):
30
        os.makedirs('output', exist_ok=True)
31
        # download weights
32
        if not os.path.exists('weights/realesr-general-x4v3.pth'):
33
            os.system(
34
                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./weights'
35
            )
36
        if not os.path.exists('weights/GFPGANv1.4.pth'):
37
            os.system('wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./weights')
38
        if not os.path.exists('weights/RealESRGAN_x4plus.pth'):
39
            os.system(
40
                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./weights'
41
            )
42
        if not os.path.exists('weights/RealESRGAN_x4plus_anime_6B.pth'):
43
            os.system(
44
                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth -P ./weights'
45
            )
46
        if not os.path.exists('weights/realesr-animevideov3.pth'):
47
            os.system(
48
                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth -P ./weights'
49
            )
50

51
    def choose_model(self, scale, version, tile=0):
52
        half = True if torch.cuda.is_available() else False
53
        if version == 'General - RealESRGANplus':
54
            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
55
            model_path = 'weights/RealESRGAN_x4plus.pth'
56
            self.upsampler = RealESRGANer(
57
                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
58
        elif version == 'General - v3':
59
            model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
60
            model_path = 'weights/realesr-general-x4v3.pth'
61
            self.upsampler = RealESRGANer(
62
                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
63
        elif version == 'Anime - anime6B':
64
            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
65
            model_path = 'weights/RealESRGAN_x4plus_anime_6B.pth'
66
            self.upsampler = RealESRGANer(
67
                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
68
        elif version == 'AnimeVideo - v3':
69
            model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
70
            model_path = 'weights/realesr-animevideov3.pth'
71
            self.upsampler = RealESRGANer(
72
                scale=4, model_path=model_path, model=model, tile=tile, tile_pad=10, pre_pad=0, half=half)
73

74
        self.face_enhancer = GFPGANer(
75
            model_path='weights/GFPGANv1.4.pth',
76
            upscale=scale,
77
            arch='clean',
78
            channel_multiplier=2,
79
            bg_upsampler=self.upsampler)
80

81
    def predict(
82
        self,
83
        img: Path = Input(description='Input'),
84
        version: str = Input(
85
            description='RealESRGAN version. Please see [Readme] below for more descriptions',
86
            choices=['General - RealESRGANplus', 'General - v3', 'Anime - anime6B', 'AnimeVideo - v3'],
87
            default='General - v3'),
88
        scale: float = Input(description='Rescaling factor', default=2),
89
        face_enhance: bool = Input(
90
            description='Enhance faces with GFPGAN. Note that it does not work for anime images/vidoes', default=False),
91
        tile: int = Input(
92
            description=
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',
94
            default=0)
95
    ) -> Path:
96
        if tile <= 100 or tile is None:
97
            tile = 0
98
        print(f'img: {img}. version: {version}. scale: {scale}. face_enhance: {face_enhance}. tile: {tile}.')
99
        try:
100
            extension = os.path.splitext(os.path.basename(str(img)))[1]
101
            img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)
102
            if len(img.shape) == 3 and img.shape[2] == 4:
103
                img_mode = 'RGBA'
104
            elif len(img.shape) == 2:
105
                img_mode = None
106
                img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
107
            else:
108
                img_mode = None
109

110
            h, w = img.shape[0:2]
111
            if h < 300:
112
                img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)
113

114
            self.choose_model(scale, version, tile)
115

116
            try:
117
                if face_enhance:
118
                    _, _, output = self.face_enhancer.enhance(
119
                        img, has_aligned=False, only_center_face=False, paste_back=True)
120
                else:
121
                    output, _ = self.upsampler.enhance(img, outscale=scale)
122
            except RuntimeError as error:
123
                print('Error', error)
124
                print('If you encounter CUDA out of memory, try to set "tile" to a smaller size, e.g., 400.')
125

126
            if img_mode == 'RGBA':  # RGBA images should be saved in png format
127
                extension = 'png'
128
            # save_path = f'output/out.{extension}'
129
            # cv2.imwrite(save_path, output)
130
            out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'
131
            cv2.imwrite(str(out_path), output)
132
        except Exception as error:
133
            print('global exception: ', error)
134
        finally:
135
            clean_folder('output')
136
        return out_path
137

138

139
def clean_folder(folder):
140
    for filename in os.listdir(folder):
141
        file_path = os.path.join(folder, filename)
142
        try:
143
            if os.path.isfile(file_path) or os.path.islink(file_path):
144
                os.unlink(file_path)
145
            elif os.path.isdir(file_path):
146
                shutil.rmtree(file_path)
147
        except Exception as e:
148
            print(f'Failed to delete {file_path}. Reason: {e}')
149

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.