2023-12-15 20:31:28 +00:00
|
|
|
"""Functions for image upscaling using RealESRGAN"""
|
|
|
|
|
2022-09-13 07:27:53 +00:00
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
from PIL import Image
|
|
|
|
|
2022-10-23 21:46:45 +00:00
|
|
|
from imaginairy.model_manager import get_cached_url_path
|
|
|
|
from imaginairy.utils import get_device
|
2023-05-08 03:37:15 +00:00
|
|
|
from imaginairy.utils.model_cache import memory_managed_model
|
2023-01-09 05:16:35 +00:00
|
|
|
from imaginairy.vendored.basicsr.rrdbnet_arch import RRDBNet
|
2023-01-09 06:03:16 +00:00
|
|
|
from imaginairy.vendored.realesrgan import RealESRGANer
|
2022-09-13 07:27:53 +00:00
|
|
|
|
|
|
|
|
2023-05-16 00:21:50 +00:00
|
|
|
@memory_managed_model("realesrgan_upsampler", memory_usage_mb=70)
|
2022-09-13 07:27:53 +00:00
|
|
|
def realesrgan_upsampler():
|
|
|
|
model = RRDBNet(
|
|
|
|
num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4
|
|
|
|
)
|
|
|
|
url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
|
|
|
|
model_path = get_cached_url_path(url)
|
2022-09-17 19:24:27 +00:00
|
|
|
device = get_device()
|
2023-05-16 00:21:50 +00:00
|
|
|
|
2023-05-16 03:23:10 +00:00
|
|
|
upsampler = RealESRGANer(
|
|
|
|
scale=4, model_path=model_path, model=model, tile=512, device=device
|
|
|
|
)
|
2022-09-13 07:27:53 +00:00
|
|
|
|
|
|
|
upsampler.device = torch.device(device)
|
|
|
|
upsampler.model.to(device)
|
|
|
|
|
|
|
|
return upsampler
|
|
|
|
|
|
|
|
|
|
|
|
def upscale_image(img):
|
|
|
|
img = img.convert("RGB")
|
2022-09-18 13:07:07 +00:00
|
|
|
|
2022-09-13 07:27:53 +00:00
|
|
|
np_img = np.array(img, dtype=np.uint8)
|
|
|
|
upsampler_output, img_mode = realesrgan_upsampler().enhance(np_img[:, :, ::-1])
|
|
|
|
return Image.fromarray(upsampler_output[:, :, ::-1], mode=img_mode)
|