| from typing import Tuple | |
| import PIL | |
| from PIL.Image import Image as PILImage | |
| def get_background_dominant_color(img: PILImage, mask: PILImage) -> tuple: | |
| negative_img = img.copy() | |
| negative_mask = PIL.ImageOps.invert(mask) | |
| negative_img.putalpha(negative_mask) | |
| negative_img = negative_img.resize((1, 1)) | |
| r, g, b, a = negative_img.getpixel((0, 0)) | |
| return r, g, b, 255 | |
| def apply_background_color(img: PILImage, color: Tuple[int, int, int, int]) -> PILImage: | |
| r, g, b, a = color | |
| colored_image = PIL.Image.new("RGBA", img.size, (r, g, b, a)) | |
| colored_image.paste(img, mask=img) | |
| return colored_image | |
| def make_flatten_background(img, mask): | |
| img = PIL.Image.open(img) | |
| mask = PIL.Image.open(mask) | |
| color = get_background_dominant_color(img, mask) | |
| return apply_background_color(img, color) | |