Spaces:
Running
Running
Upload 3 files
Browse filesLive Bg Removal
Files changed (3)
- app.pyAdded+67
- live_webcam_background_replace.pyAdded+53
- requirement.txtAdded+6
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import streamlit as st
import cv2
import numpy as np
from PIL import Image
from rembg import remove
import tempfile
import os
st.set_page_config(page_title="Live Background Replacer", layout="centered")
st.title("🎥 Live Webcam Background Remover")
st.write("Upload a background image and click 'Start Camera' to apply the effect live.")
# Upload background image
bg_file = st.file_uploader("Upload Background Image", type=["jpg", "jpeg", "png"])
if bg_file:
# bg_image = Image.open(bg_file).convert("RGBA")
# bg_temp_path = os.path.join(tempfile.gettempdir(), "background.jpg")
# bg_image.save(bg_temp_path)
bg_image = Image.open(bg_file).convert("RGBA")
bg_rgb = bg_image.convert("RGB") # Convert to RGB to avoid JPEG transparency error
bg_temp_path = os.path.join(tempfile.gettempdir(), "background.jpg")
bg_rgb.save(bg_temp_path)
if st.button("▶️ Start Camera with Effect"):
st.success("Launching webcam window. Press 'q' to quit or 's' to save a snapshot.")
cap = cv2.VideoCapture(0)
print("Webcam started. Press 's' to save image, 'q' to quit.")
while True:
ret, frame = cap.read()
if not ret:
break
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(frame_rgb).convert("RGBA")
try:
no_bg = remove(pil_image)
except Exception as e:
print("Background removal failed:", e)
continue
# Use uploaded background
bg_image = Image.open(bg_temp_path).convert("RGBA")
bg_resized = bg_image.resize(no_bg.size)
# Composite image
final = Image.alpha_composite(bg_resized, no_bg)
final_bgr = cv2.cvtColor(np.array(final), cv2.COLOR_RGBA2BGR)
# Show side-by-side
frame_resized = cv2.resize(frame, final_bgr.shape[:2][::-1])
combined = np.hstack((frame_resized, final_bgr))
cv2.imshow("Original (Left) | Stylized (Right)", combined)
key = cv2.waitKey(1)
if key == ord('q'):
break
elif key == ord('s'):
filename = "snapshot_result.jpg"
cv2.imwrite(filename, final_bgr)
print(f"✅ Snapshot saved as {filename}")
cap.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import cv2import numpy as npfrom PIL import Imagefrom rembg import remove
# Load new background imagebg_path = 'background.jpg' # <-- Replace with your background imagebg_image = Image.open(bg_path).convert("RGBA")
# Open webcamcap = cv2.VideoCapture(0)
print("Press 's' to save a snapshot, or 'q' to quit.")
while True: ret, frame = cap.read() if not ret: break
# Convert frame to PIL for rembg frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(frame_rgb).convert("RGBA")
# Apply background removal try: no_bg = remove(pil_image) except Exception as e: print("Background removal failed:", e) continue
# Resize background to match webcam frame resized_bg = bg_image.resize(no_bg.size)
# Composite foreground over new background final = Image.alpha_composite(resized_bg, no_bg) final_bgr = cv2.cvtColor(np.array(final), cv2.COLOR_RGBA2BGR)
# Show both frames side by side frame_resized = cv2.resize(frame, final_bgr.shape[:2][::-1]) combined = np.hstack((frame_resized, final_bgr))
cv2.imshow("Live - Original (Left) | Stylized (Right)", combined)
key = cv2.waitKey(1) if key == ord('q'): break elif key == ord('s'): filename = "snapshot_result.jpg" cv2.imwrite(filename, final_bgr) print(f"✅ Snapshot saved as {filename}")
cap.release()cv2.destroyAllWindows()123456streamlit==1.35.0
opencv-python==4.10.0.82
Pillow==10.0.1
rembg==2.0.67
numpy==1.26.4
onnxruntimeapp.pyAdded+67
live_webcam_background_replace.pyAdded+53
requirement.txtAdded+6