Nekshay commited on
Commit
74f052c
·
verified ·
1 Parent(s): 98e86c7

Create Car_Transperance_bg.py

Browse files
Files changed (1) hide show
  1. Car_Transperance_bg.py +31 -0
Car_Transperance_bg.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+
5
+ # Paths (change these to your actual file paths)
6
+ image_path = "car.jpg" # Original car image
7
+ mask_path = "car_mask.png" # Segmented mask image
8
+ output_path = "car_transparent.png" # Output image
9
+
10
+ # Load images
11
+ car_image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) # Read original image
12
+ mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # Read mask in grayscale
13
+
14
+ # Ensure both images are the same size
15
+ if car_image.shape[:2] != mask.shape[:2]:
16
+ mask = cv2.resize(mask, (car_image.shape[1], car_image.shape[0]))
17
+
18
+ # Normalize mask to be binary (0 for background, 255 for car)
19
+ _, binary_mask = cv2.threshold(mask, 128, 255, cv2.THRESH_BINARY)
20
+
21
+ # Create an alpha channel where car is visible (255) and background is transparent (0)
22
+ alpha_channel = binary_mask.copy()
23
+
24
+ # Convert original image to RGBA (add alpha channel)
25
+ rgba_image = cv2.cvtColor(car_image, cv2.COLOR_BGR2BGRA)
26
+ rgba_image[:, :, 3] = alpha_channel # Assign alpha channel
27
+
28
+ # Save the output as a transparent PNG
29
+ cv2.imwrite(output_path, rgba_image)
30
+
31
+ print(f"✅ Transparent image saved at: {output_path}")