Spaces:
Runtime error
Runtime error
add image tiling from Real-ESRGAN to save memory
Browse files- ESRGANer.py +152 -0
- app.py +5 -3
- inference.py +13 -33
- inference_manga_v2.py +13 -35
- process_image.py +1 -5
ESRGANer.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageChops
|
2 |
+
import numpy as np
|
3 |
+
import cv2 as cv
|
4 |
+
import math
|
5 |
+
import torch
|
6 |
+
from torch.nn import functional as F
|
7 |
+
|
8 |
+
"""
|
9 |
+
Borrowed and adapted from https://github.com/xinntao/Real-ESRGAN/blob/master/realesrgan/utils.py
|
10 |
+
Thank you xinntao!
|
11 |
+
"""
|
12 |
+
class ESRGANer():
|
13 |
+
"""A helper class for upsampling images with ESRGAN.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4.
|
17 |
+
model (nn.Module): The defined network. Default: None.
|
18 |
+
tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop
|
19 |
+
input images into tiles, and then process each of them. Finally, they will be merged into one image.
|
20 |
+
0 denotes for do not use tile. Default: 500.
|
21 |
+
tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10.
|
22 |
+
pre_pad (int): Pad the input images to avoid border artifacts. Default: 10.
|
23 |
+
"""
|
24 |
+
|
25 |
+
def __init__(self,
|
26 |
+
scale=4,
|
27 |
+
model=None,
|
28 |
+
tile=300,
|
29 |
+
tile_pad=10,
|
30 |
+
pre_pad=10
|
31 |
+
):
|
32 |
+
self.scale = scale
|
33 |
+
self.tile_size = tile
|
34 |
+
self.tile_pad = tile_pad
|
35 |
+
self.pre_pad = pre_pad
|
36 |
+
self.mod_scale = None
|
37 |
+
|
38 |
+
self.model = model
|
39 |
+
|
40 |
+
def pre_process(self, img):
|
41 |
+
"""Pre-process, such as pre-pad and mod pad, so that the images can be divisible
|
42 |
+
"""
|
43 |
+
self.img = img
|
44 |
+
|
45 |
+
# pre_pad
|
46 |
+
if self.pre_pad != 0:
|
47 |
+
self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), 'reflect')
|
48 |
+
# mod pad for divisible borders
|
49 |
+
if self.scale == 2:
|
50 |
+
self.mod_scale = 2
|
51 |
+
elif self.scale == 1:
|
52 |
+
self.mod_scale = 4
|
53 |
+
if self.mod_scale is not None:
|
54 |
+
self.mod_pad_h, self.mod_pad_w = 0, 0
|
55 |
+
_, _, h, w = self.img.size()
|
56 |
+
if (h % self.mod_scale != 0):
|
57 |
+
self.mod_pad_h = (self.mod_scale - h % self.mod_scale)
|
58 |
+
if (w % self.mod_scale != 0):
|
59 |
+
self.mod_pad_w = (self.mod_scale - w % self.mod_scale)
|
60 |
+
self.img = F.pad(self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), 'reflect')
|
61 |
+
|
62 |
+
def process(self):
|
63 |
+
# model inference
|
64 |
+
self.output = self.model(self.img)
|
65 |
+
|
66 |
+
def tile_process(self):
|
67 |
+
"""It will first crop input images to tiles, and then process each tile.
|
68 |
+
Finally, all the processed tiles are merged into one images.
|
69 |
+
|
70 |
+
Modified from: https://github.com/ata4/esrgan-launcher
|
71 |
+
"""
|
72 |
+
batch, channel, height, width = self.img.shape
|
73 |
+
output_height = height * self.scale
|
74 |
+
output_width = width * self.scale
|
75 |
+
output_shape = (batch, channel, output_height, output_width)
|
76 |
+
|
77 |
+
# start with black image
|
78 |
+
self.output = self.img.new_zeros(output_shape)
|
79 |
+
tiles_x = math.ceil(width / self.tile_size)
|
80 |
+
tiles_y = math.ceil(height / self.tile_size)
|
81 |
+
|
82 |
+
# loop over all tiles
|
83 |
+
for y in range(tiles_y):
|
84 |
+
for x in range(tiles_x):
|
85 |
+
# extract tile from input image
|
86 |
+
ofs_x = x * self.tile_size
|
87 |
+
ofs_y = y * self.tile_size
|
88 |
+
# input tile area on total image
|
89 |
+
input_start_x = ofs_x
|
90 |
+
input_end_x = min(ofs_x + self.tile_size, width)
|
91 |
+
input_start_y = ofs_y
|
92 |
+
input_end_y = min(ofs_y + self.tile_size, height)
|
93 |
+
|
94 |
+
# input tile area on total image with padding
|
95 |
+
input_start_x_pad = max(input_start_x - self.tile_pad, 0)
|
96 |
+
input_end_x_pad = min(input_end_x + self.tile_pad, width)
|
97 |
+
input_start_y_pad = max(input_start_y - self.tile_pad, 0)
|
98 |
+
input_end_y_pad = min(input_end_y + self.tile_pad, height)
|
99 |
+
|
100 |
+
# input tile dimensions
|
101 |
+
input_tile_width = input_end_x - input_start_x
|
102 |
+
input_tile_height = input_end_y - input_start_y
|
103 |
+
tile_idx = y * tiles_x + x + 1
|
104 |
+
input_tile = self.img[:, :, input_start_y_pad:input_end_y_pad, input_start_x_pad:input_end_x_pad]
|
105 |
+
|
106 |
+
# upscale tile
|
107 |
+
try:
|
108 |
+
with torch.no_grad():
|
109 |
+
output_tile = self.model(input_tile)
|
110 |
+
except RuntimeError as error:
|
111 |
+
print('Error', error)
|
112 |
+
print(f'Processing tile {tile_idx}/{tiles_x * tiles_y}')
|
113 |
+
|
114 |
+
# output tile area on total image
|
115 |
+
output_start_x = input_start_x * self.scale
|
116 |
+
output_end_x = input_end_x * self.scale
|
117 |
+
output_start_y = input_start_y * self.scale
|
118 |
+
output_end_y = input_end_y * self.scale
|
119 |
+
|
120 |
+
# output tile area without padding
|
121 |
+
output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale
|
122 |
+
output_end_x_tile = output_start_x_tile + input_tile_width * self.scale
|
123 |
+
output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale
|
124 |
+
output_end_y_tile = output_start_y_tile + input_tile_height * self.scale
|
125 |
+
|
126 |
+
# put tile into output image
|
127 |
+
self.output[:, :, output_start_y:output_end_y,
|
128 |
+
output_start_x:output_end_x] = output_tile[:, :, output_start_y_tile:output_end_y_tile,
|
129 |
+
output_start_x_tile:output_end_x_tile]
|
130 |
+
|
131 |
+
def post_process(self):
|
132 |
+
# remove extra pad
|
133 |
+
if self.mod_scale is not None:
|
134 |
+
_, _, h, w = self.output.size()
|
135 |
+
self.output = self.output[:, :, 0:h - self.mod_pad_h * self.scale, 0:w - self.mod_pad_w * self.scale]
|
136 |
+
# remove prepad
|
137 |
+
if self.pre_pad != 0:
|
138 |
+
_, _, h, w = self.output.size()
|
139 |
+
self.output = self.output[:, :, 0:h - self.pre_pad * self.scale, 0:w - self.pre_pad * self.scale]
|
140 |
+
return self.output
|
141 |
+
|
142 |
+
@torch.no_grad()
|
143 |
+
def enhance(self, img):
|
144 |
+
self.pre_process(img)
|
145 |
+
|
146 |
+
if self.tile_size > 0:
|
147 |
+
self.tile_process()
|
148 |
+
else:
|
149 |
+
self.process()
|
150 |
+
output_img = self.post_process()
|
151 |
+
|
152 |
+
return output_img
|
app.py
CHANGED
@@ -3,8 +3,6 @@ import util
|
|
3 |
import process_image
|
4 |
from run_cmd import run_cmd
|
5 |
|
6 |
-
run_cmd("pip install split-image")
|
7 |
-
|
8 |
is_colab = util.is_google_colab()
|
9 |
|
10 |
css = '''
|
@@ -37,7 +35,11 @@ with gr.Blocks(title=title, css=css) as demo:
|
|
37 |
# {title}
|
38 |
This space uses old ESRGAN architecture to upscale images, using models made by the community.
|
39 |
|
40 |
-
Once upscaled, click or tap the download button under the image to download it.
|
|
|
|
|
|
|
|
|
41 |
""")
|
42 |
|
43 |
with gr.Box():
|
|
|
3 |
import process_image
|
4 |
from run_cmd import run_cmd
|
5 |
|
|
|
|
|
6 |
is_colab = util.is_google_colab()
|
7 |
|
8 |
css = '''
|
|
|
35 |
# {title}
|
36 |
This space uses old ESRGAN architecture to upscale images, using models made by the community.
|
37 |
|
38 |
+
Once the photo upscaled, click or tap the **download button** under the image to download it. **The preview image is not the upscaled one**
|
39 |
+
|
40 |
+
I'll add more models after optimizing to size of the output image, right now it could be quite big.
|
41 |
+
|
42 |
+
**Colab coming soon™**
|
43 |
""")
|
44 |
|
45 |
with gr.Box():
|
inference.py
CHANGED
@@ -4,8 +4,8 @@ import cv2
|
|
4 |
import numpy as np
|
5 |
import torch
|
6 |
import architecture as arch
|
7 |
-
from split_image import split_image
|
8 |
from run_cmd import run_cmd
|
|
|
9 |
|
10 |
def is_cuda():
|
11 |
if torch.cuda.is_available():
|
@@ -39,37 +39,17 @@ for k, v in model.named_parameters():
|
|
39 |
v.requires_grad = False
|
40 |
model = model.to(device)
|
41 |
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
|
46 |
-
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
if file_path == img_path:
|
53 |
-
continue
|
54 |
-
|
55 |
-
# Read image
|
56 |
-
img = cv2.imread(file_path, cv2.IMREAD_COLOR)
|
57 |
-
img = img * 1.0 / 255
|
58 |
-
img = torch.from_numpy(np.transpose(img[:, :, [2, 1, 0]], (2, 0, 1))).float()
|
59 |
-
img_LR = img.unsqueeze(0)
|
60 |
-
img_LR = img_LR.to(device)
|
61 |
-
|
62 |
-
print(f"Start upscaling tile {x}...")
|
63 |
-
with torch.no_grad():
|
64 |
-
output = model(img_LR).data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
65 |
-
output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0))
|
66 |
-
output = (output * 255.0).round()
|
67 |
-
print(f"Finished upscaling tile {x}, saving tile.")
|
68 |
-
cv2.imwrite(file_path, output)
|
69 |
-
|
70 |
-
# Join all tiles
|
71 |
-
run_cmd(f"cd {base_path} && split-image {image_name} 7 7 -r --quiet")
|
72 |
-
|
73 |
-
# Open image and save as png with the ouput name
|
74 |
-
img_out = cv2.imread(img_path);
|
75 |
-
cv2.imwrite(output_dir, img_out, [int(cv2.IMWRITE_PNG_COMPRESSION), 5])
|
|
|
4 |
import numpy as np
|
5 |
import torch
|
6 |
import architecture as arch
|
|
|
7 |
from run_cmd import run_cmd
|
8 |
+
from ESRGANer import ESRGANer
|
9 |
|
10 |
def is_cuda():
|
11 |
if torch.cuda.is_available():
|
|
|
39 |
v.requires_grad = False
|
40 |
model = model.to(device)
|
41 |
|
42 |
+
# Read image
|
43 |
+
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
|
44 |
+
img = img * 1.0 / 255
|
45 |
+
img = torch.from_numpy(np.transpose(img[:, :, [2, 1, 0]], (2, 0, 1))).float()
|
46 |
+
img_LR = img.unsqueeze(0)
|
47 |
+
img_LR = img_LR.to(device)
|
48 |
|
49 |
+
upsampler = ESRGANer(model=model)
|
50 |
+
output = upsampler.enhance(img_LR)
|
51 |
|
52 |
+
output = output.squeeze().float().cpu().clamp_(0, 1).numpy()
|
53 |
+
output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0))
|
54 |
+
output = (output * 255.0).round()
|
55 |
+
cv2.imwrite(output_dir, output, [int(cv2.IMWRITE_PNG_COMPRESSION), 5])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
inference_manga_v2.py
CHANGED
@@ -4,8 +4,7 @@ import cv2
|
|
4 |
import numpy as np
|
5 |
import torch
|
6 |
import architecture as arch
|
7 |
-
from
|
8 |
-
from run_cmd import run_cmd
|
9 |
|
10 |
def is_cuda():
|
11 |
if torch.cuda.is_available():
|
@@ -33,38 +32,17 @@ for k, v in model.named_parameters():
|
|
33 |
v.requires_grad = False
|
34 |
model = model.to(device)
|
35 |
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
for root, dirs, files in os.walk(base_path, topdown=True):
|
43 |
-
for x, name in enumerate(files):
|
44 |
-
file_path = os.path.join(root, name)
|
45 |
-
|
46 |
-
if file_path == img_path:
|
47 |
-
continue
|
48 |
-
|
49 |
-
# Read image
|
50 |
-
img = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
|
51 |
-
img = img * 1.0 / 255
|
52 |
-
img = torch.from_numpy(img[np.newaxis, :, :]).float()
|
53 |
-
img_LR = img.unsqueeze(0)
|
54 |
-
img_LR = img_LR.to(device)
|
55 |
-
|
56 |
-
print(f"Start upscaling tile {x}...")
|
57 |
-
with torch.no_grad():
|
58 |
-
output = model(img_LR).squeeze(dim=0).float().cpu().clamp_(0, 1).numpy()
|
59 |
-
output = np.transpose(output, (1, 2, 0))
|
60 |
-
output = (output * 255.0).round()
|
61 |
-
print(f"Finished upscaling tile {x}, saving tile.")
|
62 |
-
cv2.imwrite(file_path, output)
|
63 |
-
|
64 |
-
# Join all tiles
|
65 |
-
run_cmd(f"cd {base_path} && split-image {image_name} 7 7 -r --quiet")
|
66 |
-
|
67 |
-
# Open image and save as png with the ouput name
|
68 |
-
img_out = cv2.imread(img_path);
|
69 |
-
cv2.imwrite(output_dir, img_out, [int(cv2.IMWRITE_PNG_COMPRESSION), 5])
|
70 |
|
|
|
|
|
|
|
|
|
|
4 |
import numpy as np
|
5 |
import torch
|
6 |
import architecture as arch
|
7 |
+
from ESRGANer import ESRGANer
|
|
|
8 |
|
9 |
def is_cuda():
|
10 |
if torch.cuda.is_available():
|
|
|
32 |
v.requires_grad = False
|
33 |
model = model.to(device)
|
34 |
|
35 |
+
# Read image
|
36 |
+
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
|
37 |
+
img = img * 1.0 / 255
|
38 |
+
img = torch.from_numpy(img[np.newaxis, :, :]).float()
|
39 |
+
img_LR = img.unsqueeze(0)
|
40 |
+
img_LR = img_LR.to(device)
|
41 |
|
42 |
+
upsampler = ESRGANer(model=model)
|
43 |
+
output = upsampler.enhance(img_LR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
output = output.squeeze(dim=0).float().cpu().clamp_(0, 1).numpy()
|
46 |
+
output = np.transpose(output, (1, 2, 0))
|
47 |
+
output = (output * 255.0).round()
|
48 |
+
cv2.imwrite(output_dir, output, [int(cv2.IMWRITE_PNG_COMPRESSION), 5])
|
process_image.py
CHANGED
@@ -16,10 +16,9 @@ def inference(img, size, type):
|
|
16 |
OUTPUT_DIR = os.path.join(temp_path, f"output_image{str(_id)}")
|
17 |
img_in_path = os.path.join(INPUT_DIR, "input.jpg")
|
18 |
img_out_path = os.path.join(OUTPUT_DIR, f"output_{size}.png")
|
19 |
-
run_cmd(f"rm -rf {INPUT_DIR}")
|
20 |
-
run_cmd(f"rm -rf {OUTPUT_DIR}")
|
21 |
run_cmd(f"mkdir {INPUT_DIR}")
|
22 |
run_cmd(f"mkdir {OUTPUT_DIR}")
|
|
|
23 |
img.save(img_in_path, "PNG")
|
24 |
|
25 |
if type == "Manga":
|
@@ -32,9 +31,6 @@ def inference(img, size, type):
|
|
32 |
if size == "x2":
|
33 |
img_out = img_out.resize((img_out.width // 2, img_out.height // 2), resample=Image.BICUBIC)
|
34 |
|
35 |
-
#img_out.save(img_out_path, optimize=True) # Add more optimizations
|
36 |
-
#img_out = Image.open(img_out_path)
|
37 |
-
|
38 |
# Remove input and output image
|
39 |
run_cmd(f"rm -rf {INPUT_DIR}")
|
40 |
|
|
|
16 |
OUTPUT_DIR = os.path.join(temp_path, f"output_image{str(_id)}")
|
17 |
img_in_path = os.path.join(INPUT_DIR, "input.jpg")
|
18 |
img_out_path = os.path.join(OUTPUT_DIR, f"output_{size}.png")
|
|
|
|
|
19 |
run_cmd(f"mkdir {INPUT_DIR}")
|
20 |
run_cmd(f"mkdir {OUTPUT_DIR}")
|
21 |
+
|
22 |
img.save(img_in_path, "PNG")
|
23 |
|
24 |
if type == "Manga":
|
|
|
31 |
if size == "x2":
|
32 |
img_out = img_out.resize((img_out.width // 2, img_out.height // 2), resample=Image.BICUBIC)
|
33 |
|
|
|
|
|
|
|
34 |
# Remove input and output image
|
35 |
run_cmd(f"rm -rf {INPUT_DIR}")
|
36 |
|