mednow commited on
Commit
a1074ad
1 Parent(s): 3a53ca6

Upload 36 files

Browse files
RealESRGAN/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .model import RealESRGAN
2
+ from .model import RRDBNet
3
+ from .differences import DifferencesCalculate
RealESRGAN/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (330 Bytes). View file
 
RealESRGAN/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (383 Bytes). View file
 
RealESRGAN/__pycache__/arch_utils.cpython-310.pyc ADDED
Binary file (7.19 kB). View file
 
RealESRGAN/__pycache__/arch_utils.cpython-311.pyc ADDED
Binary file (11.5 kB). View file
 
RealESRGAN/__pycache__/differences.cpython-310.pyc ADDED
Binary file (1.18 kB). View file
 
RealESRGAN/__pycache__/differences.cpython-311.pyc ADDED
Binary file (2.06 kB). View file
 
RealESRGAN/__pycache__/model.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
RealESRGAN/__pycache__/model.cpython-311.pyc ADDED
Binary file (6.86 kB). View file
 
RealESRGAN/__pycache__/rrdbnet_arch.cpython-310.pyc ADDED
Binary file (4.51 kB). View file
 
RealESRGAN/__pycache__/rrdbnet_arch.cpython-311.pyc ADDED
Binary file (8.24 kB). View file
 
RealESRGAN/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.99 kB). View file
 
RealESRGAN/__pycache__/utils.cpython-311.pyc ADDED
Binary file (6.22 kB). View file
 
RealESRGAN/arch_utils.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn as nn
4
+ from torch.nn import functional as F
5
+ from torch.nn import init as init
6
+ from torch.nn.modules.batchnorm import _BatchNorm
7
+
8
+ @torch.no_grad()
9
+ def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
10
+ """Initialize network weights.
11
+
12
+ Args:
13
+ module_list (list[nn.Module] | nn.Module): Modules to be initialized.
14
+ scale (float): Scale initialized weights, especially for residual
15
+ blocks. Default: 1.
16
+ bias_fill (float): The value to fill bias. Default: 0
17
+ kwargs (dict): Other arguments for initialization function.
18
+ """
19
+ if not isinstance(module_list, list):
20
+ module_list = [module_list]
21
+ for module in module_list:
22
+ for m in module.modules():
23
+ if isinstance(m, nn.Conv2d):
24
+ init.kaiming_normal_(m.weight, **kwargs)
25
+ m.weight.data *= scale
26
+ if m.bias is not None:
27
+ m.bias.data.fill_(bias_fill)
28
+ elif isinstance(m, nn.Linear):
29
+ init.kaiming_normal_(m.weight, **kwargs)
30
+ m.weight.data *= scale
31
+ if m.bias is not None:
32
+ m.bias.data.fill_(bias_fill)
33
+ elif isinstance(m, _BatchNorm):
34
+ init.constant_(m.weight, 1)
35
+ if m.bias is not None:
36
+ m.bias.data.fill_(bias_fill)
37
+
38
+
39
+ def make_layer(basic_block, num_basic_block, **kwarg):
40
+ """Make layers by stacking the same blocks.
41
+
42
+ Args:
43
+ basic_block (nn.module): nn.module class for basic block.
44
+ num_basic_block (int): number of blocks.
45
+
46
+ Returns:
47
+ nn.Sequential: Stacked blocks in nn.Sequential.
48
+ """
49
+ layers = []
50
+ for _ in range(num_basic_block):
51
+ layers.append(basic_block(**kwarg))
52
+ return nn.Sequential(*layers)
53
+
54
+
55
+ class ResidualBlockNoBN(nn.Module):
56
+ """Residual block without BN.
57
+
58
+ It has a style of:
59
+ ---Conv-ReLU-Conv-+-
60
+ |________________|
61
+
62
+ Args:
63
+ num_feat (int): Channel number of intermediate features.
64
+ Default: 64.
65
+ res_scale (float): Residual scale. Default: 1.
66
+ pytorch_init (bool): If set to True, use pytorch default init,
67
+ otherwise, use default_init_weights. Default: False.
68
+ """
69
+
70
+ def __init__(self, num_feat=64, res_scale=1, pytorch_init=False):
71
+ super(ResidualBlockNoBN, self).__init__()
72
+ self.res_scale = res_scale
73
+ self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
74
+ self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True)
75
+ self.relu = nn.ReLU(inplace=True)
76
+
77
+ if not pytorch_init:
78
+ default_init_weights([self.conv1, self.conv2], 0.1)
79
+
80
+ def forward(self, x):
81
+ identity = x
82
+ out = self.conv2(self.relu(self.conv1(x)))
83
+ return identity + out * self.res_scale
84
+
85
+
86
+ class Upsample(nn.Sequential):
87
+ """Upsample module.
88
+
89
+ Args:
90
+ scale (int): Scale factor. Supported scales: 2^n and 3.
91
+ num_feat (int): Channel number of intermediate features.
92
+ """
93
+
94
+ def __init__(self, scale, num_feat):
95
+ m = []
96
+ if (scale & (scale - 1)) == 0: # scale = 2^n
97
+ for _ in range(int(math.log(scale, 2))):
98
+ m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
99
+ m.append(nn.PixelShuffle(2))
100
+ elif scale == 3:
101
+ m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
102
+ m.append(nn.PixelShuffle(3))
103
+ else:
104
+ raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
105
+ super(Upsample, self).__init__(*m)
106
+
107
+
108
+ def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True):
109
+ """Warp an image or feature map with optical flow.
110
+
111
+ Args:
112
+ x (Tensor): Tensor with size (n, c, h, w).
113
+ flow (Tensor): Tensor with size (n, h, w, 2), normal value.
114
+ interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'.
115
+ padding_mode (str): 'zeros' or 'border' or 'reflection'.
116
+ Default: 'zeros'.
117
+ align_corners (bool): Before pytorch 1.3, the default value is
118
+ align_corners=True. After pytorch 1.3, the default value is
119
+ align_corners=False. Here, we use the True as default.
120
+
121
+ Returns:
122
+ Tensor: Warped image or feature map.
123
+ """
124
+ assert x.size()[-2:] == flow.size()[1:3]
125
+ _, _, h, w = x.size()
126
+ # create mesh grid
127
+ grid_y, grid_x = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))
128
+ grid = torch.stack((grid_x, grid_y), 2).float() # W(x), H(y), 2
129
+ grid.requires_grad = False
130
+
131
+ vgrid = grid + flow
132
+ # scale grid to [-1,1]
133
+ vgrid_x = 2.0 * vgrid[:, :, :, 0] / max(w - 1, 1) - 1.0
134
+ vgrid_y = 2.0 * vgrid[:, :, :, 1] / max(h - 1, 1) - 1.0
135
+ vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3)
136
+ output = F.grid_sample(x, vgrid_scaled, mode=interp_mode, padding_mode=padding_mode, align_corners=align_corners)
137
+
138
+ # TODO, what if align_corners=False
139
+ return output
140
+
141
+
142
+ def resize_flow(flow, size_type, sizes, interp_mode='bilinear', align_corners=False):
143
+ """Resize a flow according to ratio or shape.
144
+
145
+ Args:
146
+ flow (Tensor): Precomputed flow. shape [N, 2, H, W].
147
+ size_type (str): 'ratio' or 'shape'.
148
+ sizes (list[int | float]): the ratio for resizing or the final output
149
+ shape.
150
+ 1) The order of ratio should be [ratio_h, ratio_w]. For
151
+ downsampling, the ratio should be smaller than 1.0 (i.e., ratio
152
+ < 1.0). For upsampling, the ratio should be larger than 1.0 (i.e.,
153
+ ratio > 1.0).
154
+ 2) The order of output_size should be [out_h, out_w].
155
+ interp_mode (str): The mode of interpolation for resizing.
156
+ Default: 'bilinear'.
157
+ align_corners (bool): Whether align corners. Default: False.
158
+
159
+ Returns:
160
+ Tensor: Resized flow.
161
+ """
162
+ _, _, flow_h, flow_w = flow.size()
163
+ if size_type == 'ratio':
164
+ output_h, output_w = int(flow_h * sizes[0]), int(flow_w * sizes[1])
165
+ elif size_type == 'shape':
166
+ output_h, output_w = sizes[0], sizes[1]
167
+ else:
168
+ raise ValueError(f'Size type should be ratio or shape, but got type {size_type}.')
169
+
170
+ input_flow = flow.clone()
171
+ ratio_h = output_h / flow_h
172
+ ratio_w = output_w / flow_w
173
+ input_flow[:, 0, :, :] *= ratio_w
174
+ input_flow[:, 1, :, :] *= ratio_h
175
+ resized_flow = F.interpolate(
176
+ input=input_flow, size=(output_h, output_w), mode=interp_mode, align_corners=align_corners)
177
+ return resized_flow
178
+
179
+
180
+ # TODO: may write a cpp file
181
+ def pixel_unshuffle(x, scale):
182
+ """ Pixel unshuffle.
183
+
184
+ Args:
185
+ x (Tensor): Input feature with shape (b, c, hh, hw).
186
+ scale (int): Downsample ratio.
187
+
188
+ Returns:
189
+ Tensor: the pixel unshuffled feature.
190
+ """
191
+ b, c, hh, hw = x.size()
192
+ out_channel = c * (scale**2)
193
+ assert hh % scale == 0 and hw % scale == 0
194
+ h = hh // scale
195
+ w = hw // scale
196
+ x_view = x.view(b, c, h, scale, w, scale)
197
+ return x_view.permute(0, 1, 3, 5, 2, 4).reshape(b, out_channel, h, w)
RealESRGAN/differences.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import matplotlib.pyplot as plt
4
+
5
+ class DifferencesCalculate:
6
+ def display(input_folder, result_folder):
7
+ dir = os.getcwd()
8
+ img_input = DifferencesCalculate.imread(dir + "\\" + input_folder)
9
+ img_output = DifferencesCalculate.imread(dir + "\\" + result_folder)
10
+ fig = plt.figure(figsize=(25, 10))
11
+ ax1 = fig.add_subplot(1, 2, 1)
12
+ plt.title('Original Image (In)', fontsize=16)
13
+ ax1.axis('off')
14
+ ax2 = fig.add_subplot(1, 2, 2)
15
+ plt.title('High Quality (Out)', fontsize=16)
16
+ ax2.axis('off')
17
+ ax1.imshow(img_input)
18
+ ax2.imshow(img_output)
19
+
20
+ def imread(img_path):
21
+ img = cv2.imread(img_path)
22
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
23
+ return img
RealESRGAN/model.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import cv2
4
+ from PIL import Image
5
+ import numpy as np
6
+ from huggingface_hub import hf_hub_url, cached_download
7
+ from .rrdbnet_arch import RRDBNet
8
+ from .utils import (
9
+ pad_reflect,
10
+ split_image_into_overlapping_patches,
11
+ stich_together,
12
+ unpad_image,
13
+ )
14
+
15
+ HF_MODELS = {
16
+ 2: dict(
17
+ repo_id="sberbank-ai/Real-ESRGAN",
18
+ filename="RealESRGAN_x2.pth",
19
+ ),
20
+ 4: dict(
21
+ repo_id="sberbank-ai/Real-ESRGAN",
22
+ filename="RealESRGAN_x4.pth",
23
+ ),
24
+ 6: dict(
25
+ repo_id="alicangonullu/ESRGAN-Ulti",
26
+ filename="RealESRGAN_x4plus.pth",
27
+ ),
28
+ 8: dict(
29
+ repo_id="sberbank-ai/Real-ESRGAN",
30
+ filename="RealESRGAN_x8.pth",
31
+ ),
32
+ }
33
+
34
+ class RealESRGAN:
35
+ def __init__(self, device, anime=False, scale=4):
36
+ self.device = device
37
+ self.scale = scale
38
+ if anime:
39
+ self.model = RRDBNet(
40
+ num_in_ch=3,
41
+ num_out_ch=3,
42
+ num_feat=64,
43
+ num_block=6,
44
+ num_grow_ch=32,
45
+ scale=scale,
46
+ )
47
+ else:
48
+ self.model = RRDBNet(
49
+ num_in_ch=3,
50
+ num_out_ch=3,
51
+ num_feat=64,
52
+ num_block=23,
53
+ num_grow_ch=32,
54
+ scale=scale,
55
+ )
56
+
57
+ def load_weights(self, model_path, download=True):
58
+ if not os.path.exists(model_path) and download:
59
+ assert self.scale in [2, 4, 8], "You can download models only with scales: 2, 4, 8"
60
+ config = HF_MODELS[self.scale]
61
+ cache_dir = os.path.dirname(model_path)
62
+ local_filename = os.path.basename(model_path)
63
+ config_file_url = hf_hub_url(repo_id=config["repo_id"], filename=config["filename"])
64
+ cached_download(config_file_url, cache_dir=cache_dir, force_filename=local_filename)
65
+ print("Weights downloaded to:", os.path.join(cache_dir, local_filename))
66
+
67
+ loadnet = torch.load(model_path)
68
+ if "params" in loadnet:
69
+ self.model.load_state_dict(loadnet["params"], strict=True)
70
+ elif "params_ema" in loadnet:
71
+ self.model.load_state_dict(loadnet["params_ema"], strict=True)
72
+ else:
73
+ self.model.load_state_dict(loadnet, strict=True)
74
+ self.model.eval()
75
+ self.model.to(self.device)
76
+
77
+ @torch.cuda.amp.autocast()
78
+ def predict(self, lr_image, batch_size=4, patches_size=192, padding=24, pad_size=15):
79
+ scale = self.scale
80
+ device = self.device
81
+ lr_image = np.array(lr_image)
82
+ lr_image = pad_reflect(lr_image, pad_size)
83
+
84
+ patches, p_shape = split_image_into_overlapping_patches(
85
+ lr_image, patch_size=patches_size, padding_size=padding
86
+ )
87
+ img = torch.FloatTensor(patches / 255).permute((0, 3, 1, 2)).to(device).detach()
88
+
89
+ with torch.no_grad():
90
+ res = self.model(img[0:batch_size])
91
+ for i in range(batch_size, img.shape[0], batch_size):
92
+ res = torch.cat((res, self.model(img[i : i + batch_size])), 0)
93
+
94
+ sr_image = res.permute((0, 2, 3, 1)).clamp_(0, 1).cpu()
95
+ np_sr_image = sr_image.numpy()
96
+
97
+ padded_size_scaled = tuple(np.multiply(p_shape[0:2], scale)) + (3,)
98
+ scaled_image_shape = tuple(np.multiply(lr_image.shape[0:2], scale)) + (3,)
99
+ np_sr_image = stich_together(
100
+ np_sr_image,
101
+ padded_image_shape=padded_size_scaled,
102
+ target_shape=scaled_image_shape,
103
+ padding_size=padding * scale,
104
+ )
105
+ sr_img = (np_sr_image * 255).astype(np.uint8)
106
+ sr_img = unpad_image(sr_img, pad_size * scale)
107
+ sr_img = Image.fromarray(sr_img)
108
+ return sr_img
109
+
110
+ def face_enhance(self, img, scale=4):
111
+ from gfpgan import GFPGANer
112
+ face_enhancer = GFPGANer(
113
+ model_path=r"C:\Users\Admin\Downloads\Term 3\Big Data Capstone Project\Real-ESRGAN-GFP\Img-Upscale-AI\model\GFPGANv1.3.pth",
114
+ upscale=scale,
115
+ arch="clean",
116
+ channel_multiplier=2,
117
+ )
118
+ _, _, output = face_enhancer.enhance(
119
+ img, has_aligned=False, only_center_face=False, paste_back=True
120
+ )
121
+ return output
RealESRGAN/rrdbnet_arch.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn as nn
3
+ from torch.nn import functional as F
4
+ from .arch_utils import default_init_weights, make_layer, pixel_unshuffle
5
+
6
+
7
+ class ResidualDenseBlock(nn.Module):
8
+ """Residual Dense Block.
9
+
10
+ Used in RRDB block in ESRGAN.
11
+
12
+ Args:
13
+ num_feat (int): Channel number of intermediate features.
14
+ num_grow_ch (int): Channels for each growth.
15
+ """
16
+
17
+ def __init__(self, num_feat=64, num_grow_ch=32):
18
+ super(ResidualDenseBlock, self).__init__()
19
+ self.conv1 = nn.Conv2d(num_feat, num_grow_ch, 3, 1, 1)
20
+ self.conv2 = nn.Conv2d(num_feat + num_grow_ch, num_grow_ch, 3, 1, 1)
21
+ self.conv3 = nn.Conv2d(num_feat + 2 * num_grow_ch, num_grow_ch, 3, 1, 1)
22
+ self.conv4 = nn.Conv2d(num_feat + 3 * num_grow_ch, num_grow_ch, 3, 1, 1)
23
+ self.conv5 = nn.Conv2d(num_feat + 4 * num_grow_ch, num_feat, 3, 1, 1)
24
+
25
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
26
+
27
+ # initialization
28
+ default_init_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1)
29
+
30
+ def forward(self, x):
31
+ x1 = self.lrelu(self.conv1(x))
32
+ x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
33
+ x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
34
+ x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
35
+ x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
36
+ # Emperically, we use 0.2 to scale the residual for better performance
37
+ return x5 * 0.2 + x
38
+
39
+
40
+ class RRDB(nn.Module):
41
+ """Residual in Residual Dense Block.
42
+
43
+ Used in RRDB-Net in ESRGAN.
44
+
45
+ Args:
46
+ num_feat (int): Channel number of intermediate features.
47
+ num_grow_ch (int): Channels for each growth.
48
+ """
49
+
50
+ def __init__(self, num_feat, num_grow_ch=32):
51
+ super(RRDB, self).__init__()
52
+ self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)
53
+ self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)
54
+ self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)
55
+
56
+ def forward(self, x):
57
+ out = self.rdb1(x)
58
+ out = self.rdb2(out)
59
+ out = self.rdb3(out)
60
+ # Emperically, we use 0.2 to scale the residual for better performance
61
+ return out * 0.2 + x
62
+
63
+
64
+ class RRDBNet(nn.Module):
65
+ """Networks consisting of Residual in Residual Dense Block, which is used
66
+ in ESRGAN.
67
+
68
+ ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.
69
+
70
+ We extend ESRGAN for scale x2 and scale x1.
71
+ Note: This is one option for scale 1, scale 2 in RRDBNet.
72
+ We first employ the pixel-unshuffle (an inverse operation of pixelshuffle to reduce the spatial size
73
+ and enlarge the channel size before feeding inputs into the main ESRGAN architecture.
74
+
75
+ Args:
76
+ num_in_ch (int): Channel number of inputs.
77
+ num_out_ch (int): Channel number of outputs.
78
+ num_feat (int): Channel number of intermediate features.
79
+ Default: 64
80
+ num_block (int): Block number in the trunk network. Defaults: 23
81
+ num_grow_ch (int): Channels for each growth. Default: 32.
82
+ """
83
+
84
+ def __init__(self, num_in_ch, num_out_ch, scale=4, num_feat=64, num_block=23, num_grow_ch=32):
85
+ super(RRDBNet, self).__init__()
86
+ self.scale = scale
87
+ if scale == 2:
88
+ num_in_ch = num_in_ch * 4
89
+ elif scale == 1:
90
+ num_in_ch = num_in_ch * 16
91
+ self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)
92
+ self.body = make_layer(RRDB, num_block, num_feat=num_feat, num_grow_ch=num_grow_ch)
93
+ self.conv_body = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
94
+ # upsample
95
+ self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
96
+ self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
97
+ if scale == 8:
98
+ self.conv_up3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
99
+ self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
100
+ self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
101
+
102
+ self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
103
+
104
+ def forward(self, x):
105
+ if self.scale == 2:
106
+ feat = pixel_unshuffle(x, scale=2)
107
+ elif self.scale == 1:
108
+ feat = pixel_unshuffle(x, scale=4)
109
+ else:
110
+ feat = x
111
+ feat = self.conv_first(feat)
112
+ body_feat = self.conv_body(self.body(feat))
113
+ feat = feat + body_feat
114
+ # upsample
115
+ feat = self.lrelu(self.conv_up1(F.interpolate(feat, scale_factor=2, mode='nearest')))
116
+ feat = self.lrelu(self.conv_up2(F.interpolate(feat, scale_factor=2, mode='nearest')))
117
+ if self.scale == 8:
118
+ feat = self.lrelu(self.conv_up3(F.interpolate(feat, scale_factor=2, mode='nearest')))
119
+ out = self.conv_last(self.lrelu(self.conv_hr(feat)))
120
+ return out
RealESRGAN/utils.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ def pad_reflect(image, pad_size):
4
+ imsize = image.shape
5
+ height, width = imsize[:2]
6
+ new_img = np.zeros([height+pad_size*2, width+pad_size*2, imsize[2]]).astype(np.uint8)
7
+ new_img[pad_size:-pad_size, pad_size:-pad_size, :] = image
8
+
9
+ new_img[0:pad_size, pad_size:-pad_size, :] = np.flip(image[0:pad_size, :, :], axis=0) #top
10
+ new_img[-pad_size:, pad_size:-pad_size, :] = np.flip(image[-pad_size:, :, :], axis=0) #bottom
11
+ new_img[:, 0:pad_size, :] = np.flip(new_img[:, pad_size:pad_size*2, :], axis=1) #left
12
+ new_img[:, -pad_size:, :] = np.flip(new_img[:, -pad_size*2:-pad_size, :], axis=1) #right
13
+
14
+ return new_img
15
+
16
+ def unpad_image(image, pad_size):
17
+ return image[pad_size:-pad_size, pad_size:-pad_size, :]
18
+
19
+
20
+ def process_array(image_array, expand=True):
21
+ """ Process a 3-dimensional array into a scaled, 4 dimensional batch of size 1. """
22
+
23
+ image_batch = image_array / 255.0
24
+ if expand:
25
+ image_batch = np.expand_dims(image_batch, axis=0)
26
+ return image_batch
27
+
28
+
29
+ def process_output(output_tensor):
30
+ """ Transforms the 4-dimensional output tensor into a suitable image format. """
31
+
32
+ sr_img = output_tensor.clip(0, 1) * 255
33
+ sr_img = np.uint8(sr_img)
34
+ return sr_img
35
+
36
+
37
+ def pad_patch(image_patch, padding_size, channel_last=True):
38
+ """ Pads image_patch with with padding_size edge values. """
39
+
40
+ if channel_last:
41
+ return np.pad(
42
+ image_patch,
43
+ ((padding_size, padding_size), (padding_size, padding_size), (0, 0)),
44
+ 'edge',
45
+ )
46
+ else:
47
+ return np.pad(
48
+ image_patch,
49
+ ((0, 0), (padding_size, padding_size), (padding_size, padding_size)),
50
+ 'edge',
51
+ )
52
+
53
+
54
+ def unpad_patches(image_patches, padding_size):
55
+ return image_patches[:, padding_size:-padding_size, padding_size:-padding_size, :]
56
+
57
+
58
+ def split_image_into_overlapping_patches(image_array, patch_size, padding_size=2):
59
+ """ Splits the image into partially overlapping patches.
60
+ The patches overlap by padding_size pixels.
61
+ Pads the image twice:
62
+ - first to have a size multiple of the patch size,
63
+ - then to have equal padding at the borders.
64
+ Args:
65
+ image_array: numpy array of the input image.
66
+ patch_size: size of the patches from the original image (without padding).
67
+ padding_size: size of the overlapping area.
68
+ """
69
+
70
+ xmax, ymax, _ = image_array.shape
71
+ x_remainder = xmax % patch_size
72
+ y_remainder = ymax % patch_size
73
+
74
+ # modulo here is to avoid extending of patch_size instead of 0
75
+ x_extend = (patch_size - x_remainder) % patch_size
76
+ y_extend = (patch_size - y_remainder) % patch_size
77
+
78
+ # make sure the image is divisible into regular patches
79
+ extended_image = np.pad(image_array, ((0, x_extend), (0, y_extend), (0, 0)), 'edge')
80
+
81
+ # add padding around the image to simplify computations
82
+ padded_image = pad_patch(extended_image, padding_size, channel_last=True)
83
+
84
+ xmax, ymax, _ = padded_image.shape
85
+ patches = []
86
+
87
+ x_lefts = range(padding_size, xmax - padding_size, patch_size)
88
+ y_tops = range(padding_size, ymax - padding_size, patch_size)
89
+
90
+ for x in x_lefts:
91
+ for y in y_tops:
92
+ x_left = x - padding_size
93
+ y_top = y - padding_size
94
+ x_right = x + patch_size + padding_size
95
+ y_bottom = y + patch_size + padding_size
96
+ patch = padded_image[x_left:x_right, y_top:y_bottom, :]
97
+ patches.append(patch)
98
+
99
+ return np.array(patches), padded_image.shape
100
+
101
+
102
+ def stich_together(patches, padded_image_shape, target_shape, padding_size=4):
103
+ """ Reconstruct the image from overlapping patches.
104
+ After scaling, shapes and padding should be scaled too.
105
+ Args:
106
+ patches: patches obtained with split_image_into_overlapping_patches
107
+ padded_image_shape: shape of the padded image contructed in split_image_into_overlapping_patches
108
+ target_shape: shape of the final image
109
+ padding_size: size of the overlapping area.
110
+ """
111
+
112
+ xmax, ymax, _ = padded_image_shape
113
+ patches = unpad_patches(patches, padding_size)
114
+ patch_size = patches.shape[1]
115
+ n_patches_per_row = ymax // patch_size
116
+
117
+ complete_image = np.zeros((xmax, ymax, 3))
118
+
119
+ row = -1
120
+ col = 0
121
+ for i in range(len(patches)):
122
+ if i % n_patches_per_row == 0:
123
+ row += 1
124
+ col = 0
125
+ complete_image[
126
+ row * patch_size: (row + 1) * patch_size, col * patch_size: (col + 1) * patch_size,:
127
+ ] = patches[i]
128
+ col += 1
129
+ return complete_image[0: target_shape[0], 0: target_shape[1], :]
dataset/download link.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Please download the dataset from below link.
2
+
3
+ https://www.kaggle.com/datasets/adityachandrasekhar/image-super-resolution
model/RealESRGAN_x2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c830d067d54fc767b9543a8432f36d91bc2de313584e8bbfe4ac26a47339e899
3
+ size 67061725
model/RealESRGAN_x4plus.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1
3
+ size 67040989
model/RealESRGAN_x4plus_anime_6B.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f872d837d3c90ed2e05227bed711af5671a6fd1c9f7d7e91c911a61f155e99da
3
+ size 17938799
model/RealESRGAN_x8.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b72fb469d12f05a4770813d2603eb1b550f40df6fb8b37d6c7bc2db3d2bff5e
3
+ size 67189359
static/icons/anime.png ADDED
static/icons/download icon.png ADDED
static/icons/enhance icon.png ADDED
static/icons/hamburger icon.png ADDED
static/icons/loading.gif ADDED
static/icons/upload icon.png ADDED
static/icons/upscale icon.png ADDED
templates/index.html ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import torch
4
+ from RealESRGAN import RealESRGAN
5
+ from io import BytesIO
6
+ import base64
7
+ import streamlit.components.v1 as components
8
+
9
+ # Function to load the model based on scale and anime toggle
10
+ def load_model(scale, anime=False):
11
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
12
+ model = RealESRGAN(device, scale=scale, anime=anime)
13
+ model_path = {
14
+ (2, False): 'model/RealESRGAN_x2.pth',
15
+ (4, False): 'model/RealESRGAN_x4plus.pth',
16
+ (8, False): 'model/RealESRGAN_x8.pth',
17
+ (4, True): 'model/RealESRGAN_x4plus_anime_6B.pth'
18
+ }[(scale, anime)]
19
+ model.load_weights(model_path)
20
+ return model
21
+
22
+ def enhance_image(image, scale, anime):
23
+ model = load_model(scale, anime=anime)
24
+ sr_image = model.predict(image)
25
+
26
+ buffer = BytesIO()
27
+ sr_image.save(buffer, format="PNG")
28
+ buffer.seek(0)
29
+ return sr_image, buffer
30
+
31
+ def get_base64_image(image):
32
+ buffered = BytesIO()
33
+ image.save(buffered, format="PNG")
34
+ return base64.b64encode(buffered.getvalue()).decode()
35
+
36
+ def image_comparison_slider(original_base64, enhanced_base64):
37
+ slider_html = f"""
38
+ <style>
39
+ .img-comp-container {{
40
+ position: relative;
41
+ width: 100%;
42
+ max-width: 800px;
43
+ margin: auto;
44
+ }}
45
+ .img-comp-img {{
46
+ position: absolute;
47
+ width: 100%;
48
+ height: 100%;
49
+ overflow: hidden;
50
+ }}
51
+ .img-comp-img img {{
52
+ width: 100%;
53
+ height: auto;
54
+ display: block;
55
+ }}
56
+ .img-comp-overlay {{
57
+ position: absolute;
58
+ top: 0;
59
+ left: 0;
60
+ width: 50%; /* Start at 50% for better default view */
61
+ height: 100%;
62
+ overflow: hidden;
63
+ background-color: rgba(0,0,0,0.5);
64
+ transition: 0.4s;
65
+ }}
66
+ .img-comp-slider {{
67
+ position: absolute;
68
+ cursor: ew-resize;
69
+ width: 40px;
70
+ height: 40px;
71
+ background-color: #2196F3;
72
+ border-radius: 50%;
73
+ transform: translateY(-50%);
74
+ top: 50%;
75
+ left: 50%;
76
+ margin-left: -20px;
77
+ margin-top: -20px;
78
+ z-index: 9;
79
+ opacity: 0.7;
80
+ transition: 0.3s;
81
+ }}
82
+ .img-comp-slider:hover {{
83
+ opacity: 1;
84
+ }}
85
+ </style>
86
+ <div class="img-comp-container">
87
+ <div class="img-comp-img">
88
+ <img src="data:image/png;base64,{original_base64}" />
89
+ </div>
90
+ <div class="img-comp-img">
91
+ <img src="data:image/png;base64,{enhanced_base64}" />
92
+ </div>
93
+ <div class="img-comp-overlay"></div>
94
+ <div class="img-comp-slider"></div>
95
+ </div>
96
+ <script>
97
+ function initComparisons() {{
98
+ var x, i;
99
+ x = document.getElementsByClassName("img-comp-container");
100
+ for (i = 0; i < x.length; i++) {{
101
+ compareImages(x[i]);
102
+ }}
103
+ function compareImages(img) {{
104
+ var slider, overlay, clicked = 0, w, h;
105
+ w = img.offsetWidth;
106
+ h = img.offsetHeight;
107
+ slider = img.getElementsByClassName("img-comp-slider")[0];
108
+ overlay = img.getElementsByClassName("img-comp-overlay")[0];
109
+ img.addEventListener("mousemove", slide);
110
+ img.addEventListener("touchmove", slide);
111
+ img.addEventListener("mousedown", setActive);
112
+ window.addEventListener("mouseup", removeActive);
113
+ function slide(e) {{
114
+ if (clicked === 0) return false;
115
+ e.preventDefault();
116
+ var pos = getCursorPos(e);
117
+ if (pos.x > w) pos.x = w;
118
+ if (pos.x < 0) pos.x = 0;
119
+ slider.style.left = pos.x + "px";
120
+ overlay.style.width = pos.x + "px";
121
+ }}
122
+ function getCursorPos(e) {{
123
+ var a, x = 0;
124
+ e = (e.changedTouches) ? e.changedTouches[0] : e;
125
+ a = img.getBoundingClientRect();
126
+ x = e.pageX - a.left;
127
+ x = x - window.pageXOffset;
128
+ return {{ x: x }};
129
+ }}
130
+ function setActive(e) {{
131
+ clicked = 1;
132
+ e.preventDefault();
133
+ }}
134
+ function removeActive() {{
135
+ clicked = 0;
136
+ }}
137
+ }}
138
+ }}
139
+ initComparisons();
140
+ </script>
141
+ """
142
+ components.html(slider_html, height=600, scrolling=True)
143
+
144
+
145
+
146
+ def main():
147
+ st.title("Generative AI Image Restoration")
148
+
149
+ # Image upload
150
+ uploaded_image = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"])
151
+
152
+ if uploaded_image is not None:
153
+ image = Image.open(uploaded_image)
154
+ st.image(image, caption="Original Image", use_column_width=True)
155
+
156
+ # Anime toggle
157
+ anime = st.checkbox("Anime Image", value=False)
158
+
159
+ # Conditional scale options
160
+ if anime:
161
+ scale = "4x" # Set to 4x automatically when anime is selected
162
+ else:
163
+ scale = st.radio("Upscaling Factor", ["2x", "4x", "8x"], index=0)
164
+
165
+ scale_value = int(scale.replace('x', ''))
166
+
167
+ # Enhance button
168
+ if st.button("Restore Image"):
169
+ enhanced_image, buffer = enhance_image(image, scale_value, anime)
170
+
171
+ # Convert images to base64 for comparison slider
172
+ original_base64 = get_base64_image(image)
173
+ enhanced_base64 = get_base64_image(enhanced_image)
174
+
175
+ # Show comparison slider
176
+ image_comparison_slider(original_base64, enhanced_base64)
177
+
178
+ # Download button
179
+ st.download_button(
180
+ label="Download Enhanced Image",
181
+ data=buffer,
182
+ file_name="enhanced_image.png",
183
+ mime="image/png"
184
+ )
185
+
186
+ if __name__ == "__main__":
187
+ main()
uploads/70.png ADDED
uploads/WhatsApp_Image_2024-06-29_at_1.57.25_PM.jpeg ADDED
uploads/comic.png ADDED
uploads/input.png ADDED
uploads/upscaled_output.png ADDED