Spaces:
Running
Running
Upload remove_bg_script.py
Browse files- remove_bg_script.py +114 -0
remove_bg_script.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
pip install torch accelerate opencv-python pillow numpy timm kornia prettytable typing scikit-image transformers>=4.39.1 gradio==4.44.1 gradio_imageslider loadimg>=0.1.1 "httpx[socks]" moviepy==1.0.3
|
3 |
+
|
4 |
+
huggingface-cli download \
|
5 |
+
--repo-type dataset svjack/video-dataset-Lily-Bikini-organized \
|
6 |
+
--local-dir video-dataset-Lily-Bikini-organized
|
7 |
+
|
8 |
+
python remove_bg_script.py video-dataset-Lily-Bikini-organized video-dataset-Lily-Bikini-rm-background-organized --copy_others
|
9 |
+
'''
|
10 |
+
|
11 |
+
from PIL import Image, ImageChops
|
12 |
+
import torch
|
13 |
+
from torchvision import transforms
|
14 |
+
from transformers import AutoModelForImageSegmentation
|
15 |
+
from moviepy.editor import VideoFileClip, ImageSequenceClip
|
16 |
+
import numpy as np
|
17 |
+
from tqdm import tqdm
|
18 |
+
from uuid import uuid1
|
19 |
+
import os
|
20 |
+
import shutil
|
21 |
+
import argparse
|
22 |
+
|
23 |
+
# Load the model
|
24 |
+
model = AutoModelForImageSegmentation.from_pretrained('briaai/RMBG-2.0', trust_remote_code=True)
|
25 |
+
torch.set_float32_matmul_precision('high') # Set precision
|
26 |
+
model.to('cuda')
|
27 |
+
model.eval()
|
28 |
+
|
29 |
+
# Data settings
|
30 |
+
image_size = (1024, 1024)
|
31 |
+
transform_image = transforms.Compose([
|
32 |
+
transforms.Resize(image_size),
|
33 |
+
transforms.ToTensor(),
|
34 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
35 |
+
])
|
36 |
+
|
37 |
+
def remove_background(image):
|
38 |
+
"""Remove background from a single image."""
|
39 |
+
input_images = transform_image(image).unsqueeze(0).to('cuda')
|
40 |
+
|
41 |
+
# Prediction
|
42 |
+
with torch.no_grad():
|
43 |
+
preds = model(input_images)[-1].sigmoid().cpu()
|
44 |
+
pred = preds[0].squeeze()
|
45 |
+
|
46 |
+
# Convert the prediction to a mask
|
47 |
+
mask = (pred * 255).byte() # Convert to 0-255 range
|
48 |
+
mask_pil = transforms.ToPILImage()(mask).convert("L")
|
49 |
+
mask_resized = mask_pil.resize(image.size, Image.LANCZOS)
|
50 |
+
|
51 |
+
# Apply the mask to the image
|
52 |
+
image.putalpha(mask_resized)
|
53 |
+
|
54 |
+
return image, mask_resized
|
55 |
+
|
56 |
+
def process_video(input_video_path, output_video_path):
|
57 |
+
"""Process a video to remove the background from each frame."""
|
58 |
+
# Load the video
|
59 |
+
video_clip = VideoFileClip(input_video_path)
|
60 |
+
|
61 |
+
# Process each frame
|
62 |
+
frames = []
|
63 |
+
for frame in tqdm(video_clip.iter_frames()):
|
64 |
+
frame_pil = Image.fromarray(frame)
|
65 |
+
frame_no_bg, mask_resized = remove_background(frame_pil)
|
66 |
+
path = "{}.png".format(uuid1())
|
67 |
+
frame_no_bg.save(path)
|
68 |
+
frame_no_bg = Image.open(path).convert("RGBA")
|
69 |
+
os.remove(path)
|
70 |
+
|
71 |
+
# Convert mask_resized to RGBA mode
|
72 |
+
mask_resized_rgba = mask_resized.convert("RGBA")
|
73 |
+
|
74 |
+
# Apply the mask using ImageChops.multiply
|
75 |
+
output = ImageChops.multiply(frame_no_bg, mask_resized_rgba)
|
76 |
+
output_np = np.array(output)
|
77 |
+
frames.append(output_np)
|
78 |
+
|
79 |
+
# Save the processed frames as a new video
|
80 |
+
processed_clip = ImageSequenceClip(frames, fps=video_clip.fps)
|
81 |
+
processed_clip.write_videofile(output_video_path, codec='libx264', ffmpeg_params=['-pix_fmt', 'yuva420p'])
|
82 |
+
|
83 |
+
def copy_non_video_files(input_path, output_path):
|
84 |
+
"""Copy non-video files and directories from input path to output path."""
|
85 |
+
for item in os.listdir(input_path):
|
86 |
+
item_path = os.path.join(input_path, item)
|
87 |
+
if not item.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
|
88 |
+
dest_path = os.path.join(output_path, item)
|
89 |
+
if os.path.isdir(item_path):
|
90 |
+
shutil.copytree(item_path, dest_path)
|
91 |
+
else:
|
92 |
+
shutil.copy2(item_path, dest_path)
|
93 |
+
|
94 |
+
def main(input_path, output_path, copy_others=False):
|
95 |
+
if not os.path.exists(output_path):
|
96 |
+
os.makedirs(output_path)
|
97 |
+
|
98 |
+
if copy_others:
|
99 |
+
copy_non_video_files(input_path, output_path)
|
100 |
+
|
101 |
+
for video_name in os.listdir(input_path):
|
102 |
+
if video_name.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
|
103 |
+
input_video_path = os.path.join(input_path, video_name)
|
104 |
+
output_video_path = os.path.join(output_path, video_name)
|
105 |
+
process_video(input_video_path, output_video_path)
|
106 |
+
|
107 |
+
if __name__ == "__main__":
|
108 |
+
parser = argparse.ArgumentParser(description="Process videos to remove background.")
|
109 |
+
parser.add_argument("input_path", type=str, help="Path to the input directory containing videos.")
|
110 |
+
parser.add_argument("output_path", type=str, help="Path to the output directory for processed videos.")
|
111 |
+
parser.add_argument("--copy_others", action="store_true", help="Copy non-video files and directories from input to output.")
|
112 |
+
|
113 |
+
args = parser.parse_args()
|
114 |
+
main(args.input_path, args.output_path, args.copy_others)
|