Created
July 5, 2022 15:33
-
-
Save robgon-art/2576ac7f3850b20b09e2f29c807997fd to your computer and use it in GitHub Desktop.
Change the aspect ratio of an image by repeating edge pixels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pil_image = Image.open("test.png").convert('RGB') | |
result = Image.new(pil_image.mode, (w_target, h_target)) | |
pad_x = (w_target-w_source)//2 | |
result.paste(pil_image, (pad_x, 0)) | |
sample = 8 | |
left_side = pil_image.crop((0, 0, sample, h_source)) | |
left_side = left_side.resize((1, h_source//2), Image.BILINEAR) | |
left_side = left_side.resize((pad_x, h_source), Image.BILINEAR) | |
result.paste(left_side, (0, 0)) | |
right_side = pil_image.crop((w_source-sample, 0, w_source, h_source)) | |
right_side = right_side.resize((1, h_source//2), Image.BILINEAR) | |
right_side = right_side.resize((w_source-pad_x, h_source), Image.BILINEAR) | |
result.paste(right_side, (w_target-pad_x, 0)) | |
image_np = np.array(result, dtype=np.float32) | |
overlap = 32 | |
alpha = np.arange(0, 1, 1.0/overlap, dtype=np.float32) | |
alpha = np.tile(alpha, [3, h_target, 1]) | |
alpha = alpha.transpose(1, 2, 0) | |
left_np = np.array(left_side.resize((overlap, h_target)), dtype=np.float32) | |
right_np = np.array(right_side.resize((overlap, h_target)), dtype=np.float32) | |
image_np[:,pad_x:pad_x+overlap,:] = image_np[:,pad_x:pad_x+overlap,:] * alpha \ | |
+ left_np * (1-alpha) | |
image_np[:,-pad_x-overlap:-pad_x,:] = image_np[:,-pad_x-overlap:-pad_x,:] * (1- alpha) \ | |
+ right_np * alpha | |
pil_image_out = Image.fromarray(image_np.astype(np.uint8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment