File size: 869 Bytes
aa1c1e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import cv2
import numpy as np
from PIL import Image


def save_mask_as_png(image, mask, path):
    """
    Save the masked region of the image as a transparent PNG.

    :param image: Original BGR image (NumPy array)
    :param mask: 2D NumPy boolean array (True = object region)
    :param path: Output file path (.png)
    """
    # Step 1: Apply the mask to the image (set background to black)
    bgr = image.copy()
    bgr[~mask] = 0

    # Step 2: Create alpha channel (0 = transparent, 255 = opaque)
    alpha = np.where(mask, 255, 0).astype(np.uint8)

    # Step 3: Merge BGR + Alpha → BGRA
    bgra = cv2.merge((*cv2.split(bgr), alpha))

    # Step 4: Convert BGRA → RGBA for proper color rendering in PIL
    rgba = cv2.cvtColor(bgra, cv2.COLOR_BGRA2RGBA)

    # Step 5: Save the image with transparency using Pillow
    Image.fromarray(rgba).save(path)