app.py
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 31 32 33 34 35 36 37 38 39 |
from rembg import remove from PIL import Image import numpy as np import cv2 # Paths input_image_path = "1.jpg" # Your input image background_image_path = "bg.jpg" # Your custom background image output_image_path = "output.png" # Final output image # Load and remove background input_image = Image.open(input_image_path).convert("RGBA") removed_bg_image = remove(input_image) # Convert to NumPy array foreground = np.array(removed_bg_image) # Get dimensions of the foreground height, width = foreground.shape[:2] # Load and resize background background = cv2.imread(background_image_path) if background is None: raise Exception("Background image not found.") background = cv2.cvtColor(background, cv2.COLOR_BGR2RGB) background = cv2.resize(background, (width, height)) # Add alpha channel to background if missing if background.shape[2] == 3: background = np.dstack([background, np.full((height, width), 255, dtype=np.uint8)]) # Composite: replace transparent areas with background alpha = foreground[:, :, 3:] / 255.0 combined = foreground[:, :, :3] * alpha + background[:, :, :3] * (1 - alpha) combined = combined.astype(np.uint8) # Save the result Image.fromarray(combined).save(output_image_path) print("Custom background applied and saved as:", output_image_path) |