import cv2 import numpy as np import os # Paths (change these to your actual file paths) image_path = "car.jpg" # Original car image mask_path = "car_mask.png" # Segmented mask image output_path = "car_transparent.png" # Output image # Load images car_image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) # Read original image mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # Read mask in grayscale # Ensure both images are the same size if car_image.shape[:2] != mask.shape[:2]: mask = cv2.resize(mask, (car_image.shape[1], car_image.shape[0])) # Normalize mask to be binary (0 for background, 255 for car) _, binary_mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY) # Create an alpha channel where car is visible (255) and background is transparent (0) alpha_channel = binary_mask.copy() # Convert original image to RGBA (add alpha channel) rgba_image = cv2.cvtColor(car_image, cv2.COLOR_BGR2BGRA) rgba_image[:, :, 3] = alpha_channel # Assign alpha channel # Save the output as a transparent PNG cv2.imwrite(output_path, rgba_image) print(f"✅ Transparent image saved at: {output_path}")