def add_shapes(
    background: PIL.Image.Image,
    shape_img: PIL.Image.Image,
    shape_params,
) -> Tuple[List[Tuple[int, int, int, int, int]], PIL.Image.Image]:
    """Paste shapes onto background and return bboxes"""
    shape_bboxes: List[Tuple[int, int, int, int, int]] = []

    for i, shape_param in enumerate(shape_params):

        x = shape_param[-2]
        y = shape_param[-1]
        x1, y1, x2, y2 = shape_img.getbbox()
        bg_at_shape = background.crop((x1 + x, y1 + y, x2 + x, y2 + y))
        bg_at_shape.paste(shape_img, (0, 0), shape_img)
        background.paste(bg_at_shape, (x, y))
        # Slightly expand the bounding box in order to simulate variability with
        # the detection boxes. Always make the crop larger than needed because training
        # augmentations will only be able to crop down.
        dx = random.randint(0, int(0.1 * (x2 - x1)))
        dy = random.randint(0, int(0.1 * (y2 - y1)))
        x1 -= dx
        x2 += dx
        y1 -= dy
        y2 += dy

        background = background.crop((x1 + x, y1 + y, x2 + x, y2 + y))
        background = background.filter(ImageFilter.SMOOTH_MORE)
    return background.convert("RGB")
Example #2
0
def strip_image(image: PIL.Image.Image) -> PIL.Image.Image:
    """Remove white and black edges"""
    for x in range(image.width):
        for y in range(image.height):

            r, g, b, _ = image.getpixel((x, y))

            if r > 247 and g > 247 and b > 247:
                image.putpixel((x, y), (0, 0, 0, 0))

    image = image.crop(image.getbbox())

    return image