Spaces:
Sleeping
Sleeping
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) | |