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 40 41 42 |
import cv2 import mediapipe as mp import numpy as np mp_selfie_segmentation = mp.solutions.selfie_segmentation segment = mp_selfie_segmentation.SelfieSegmentation(model_selection=1) cap = cv2.VideoCapture("video.mp4") width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter("output_green_bg.mp4", fourcc, fps, (width, height)) # Solid background color (BGR format) — green bg_color = (0, 255, 0) while cap.isOpened(): success, frame = cap.read() if not success: break rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) result = segment.process(rgb_frame) mask = result.segmentation_mask condition = mask > 0.5 condition = np.stack((condition,) * 3, axis=-1) # Create a solid color background solid_bg = np.zeros(frame.shape, dtype=np.uint8) solid_bg[:] = bg_color # Combine using the mask output_frame = np.where(condition, frame, solid_bg) out.write(output_frame) cap.release() out.release() print("✅ Video saved as 'output_green_bg.mp4'") |