(
image: PIL.Image.Image,
ratio: float,
)
| 112 | |
| 113 | |
| 114 | def resize_foreground( |
| 115 | image: PIL.Image.Image, |
| 116 | ratio: float, |
| 117 | ) -> PIL.Image.Image: |
| 118 | image = np.array(image) |
| 119 | assert image.shape[-1] == 4 |
| 120 | alpha = np.where(image[..., 3] > 0) |
| 121 | y1, y2, x1, x2 = ( |
| 122 | alpha[0].min(), |
| 123 | alpha[0].max(), |
| 124 | alpha[1].min(), |
| 125 | alpha[1].max(), |
| 126 | ) |
| 127 | # crop the foreground |
| 128 | fg = image[y1:y2, x1:x2] |
| 129 | # pad to square |
| 130 | size = max(fg.shape[0], fg.shape[1]) |
| 131 | ph0, pw0 = (size - fg.shape[0]) // 2, (size - fg.shape[1]) // 2 |
| 132 | ph1, pw1 = size - fg.shape[0] - ph0, size - fg.shape[1] - pw0 |
| 133 | new_image = np.pad( |
| 134 | fg, |
| 135 | ((ph0, ph1), (pw0, pw1), (0, 0)), |
| 136 | mode="constant", |
| 137 | constant_values=((0, 0), (0, 0), (0, 0)), |
| 138 | ) |
| 139 | |
| 140 | # compute padding according to the ratio |
| 141 | new_size = int(new_image.shape[0] / ratio) |
| 142 | # pad to size, double side |
| 143 | ph0, pw0 = (new_size - size) // 2, (new_size - size) // 2 |
| 144 | ph1, pw1 = new_size - size - ph0, new_size - size - pw0 |
| 145 | new_image = np.pad( |
| 146 | new_image, |
| 147 | ((ph0, ph1), (pw0, pw1), (0, 0)), |
| 148 | mode="constant", |
| 149 | constant_values=((0, 0), (0, 0), (0, 0)), |
| 150 | ) |
| 151 | new_image = Image.fromarray(new_image) |
| 152 | return new_image |
| 153 | |
| 154 | |
| 155 | def rgba_to_white_background(image: PIL.Image.Image) -> torch.Tensor: |
no outgoing calls
no test coverage detected