def set_alpha()

in broadcast-monitoring/scripts/generate-logo-images.py [0:0]


def set_alpha(img, sentinel_rgb=None, opacity=None, random_state=None):
    if random_state is None:
        random_state = np.random.default_rng()

    if len(opacity) == 1:
        opacity = opacity[0]
    else:
        mino, maxo = opacity
        opacity = random_state.choice(np.arange(mino, maxo + (.99 * OPACITY_RANGE_STEP), OPACITY_RANGE_STEP))

    # if not specified, take the color of the first pixel as the background color
    # to replace with full transparency
    if sentinel_rgb is None:
        sentinel_rgb = img[0, 0, :3]

    alpha_channel = int(opacity * 255)

    # Make into Numpy array of RGB and get dimensions
    RGB = img[:, :, :3]
    h, w = RGB.shape[:2]

    # Add an alpha channel, with specified opacity
    RGBA = np.dstack((RGB, np.zeros((h, w), dtype=np.uint8) + alpha_channel))

    # Make mask of black pixels - mask is True where image is black
    m_black = (RGBA[:, :, 0:3] == sentinel_rgb).all(2)
    m_alpha = (img[:, :, 3] == 0)

    # Make all pixels matched by mask into transparent ones
    RGBA[m_black] = (0, 0, 0, 0)
    RGBA[m_alpha] = (0, 0, 0, 0)

    # Convert Numnpy array back to PIL Image and save
    return RGBA