| 83 | |
| 84 | |
| 85 | class ESRGAN(torch.nn.Module): |
| 86 | def __init__(self, model): |
| 87 | super().__init__() |
| 88 | self.model = model |
| 89 | |
| 90 | @staticmethod |
| 91 | def from_model_manager(model_manager): |
| 92 | return ESRGAN(model_manager.fetch_model("esrgan")) |
| 93 | |
| 94 | def process_image(self, image): |
| 95 | image = torch.Tensor(np.array(image, dtype=np.float32) / 255).permute(2, 0, 1) |
| 96 | return image |
| 97 | |
| 98 | def process_images(self, images): |
| 99 | images = [self.process_image(image) for image in images] |
| 100 | images = torch.stack(images) |
| 101 | return images |
| 102 | |
| 103 | def decode_images(self, images): |
| 104 | images = (images.permute(0, 2, 3, 1) * 255).clip(0, 255).numpy().astype(np.uint8) |
| 105 | images = [Image.fromarray(image) for image in images] |
| 106 | return images |
| 107 | |
| 108 | @torch.no_grad() |
| 109 | def upscale(self, images, batch_size=4, progress_bar=lambda x:x): |
| 110 | if not isinstance(images, list): |
| 111 | images = [images] |
| 112 | is_single_image = True |
| 113 | else: |
| 114 | is_single_image = False |
| 115 | |
| 116 | # Preprocess |
| 117 | input_tensor = self.process_images(images) |
| 118 | |
| 119 | # Interpolate |
| 120 | output_tensor = [] |
| 121 | for batch_id in progress_bar(range(0, input_tensor.shape[0], batch_size)): |
| 122 | batch_id_ = min(batch_id + batch_size, input_tensor.shape[0]) |
| 123 | batch_input_tensor = input_tensor[batch_id: batch_id_] |
| 124 | batch_input_tensor = batch_input_tensor.to( |
| 125 | device=self.model.conv_first.weight.device, |
| 126 | dtype=self.model.conv_first.weight.dtype) |
| 127 | batch_output_tensor = self.model(batch_input_tensor) |
| 128 | output_tensor.append(batch_output_tensor.cpu()) |
| 129 | |
| 130 | # Output |
| 131 | output_tensor = torch.concat(output_tensor, dim=0) |
| 132 | |
| 133 | # To images |
| 134 | output_images = self.decode_images(output_tensor) |
| 135 | if is_single_image: |
| 136 | output_images = output_images[0] |
| 137 | return output_images |