Provide me a high quality streamlit python code through which I can add high quality…
- User
Provide me a high quality streamlit python code through which I can add high quality random moving fire particles to an uploaded video
- Assistant
Provide me a high quality streamlit python code through which I can add high quality random moving fire particles to an uploaded video
Sure! Below is a Streamlit app written in Python that allows you to upload a video and adds high-quality random moving fire particles to it. The app processes the video frame by frame, overlays fire particles at random positions, and creates a new video with these effects.
To achieve high-quality fire effects, we'll use pre-rendered fire particle images with transparency (alpha channel). We'll randomly position and animate these particles across the frames to simulate realistic fire movement.
Here's the complete code along with detailed instructions:
import streamlit as st
import cv2
import numpy as np
import tempfile
import os
from random import randint, uniform
from PIL import Image
# Title of the app
st.title('🔥 Add Fire Particles to Your Video 🔥')
# File uploader allowing only common video file types
uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov", "mkv"])
# If a file is uploaded
if uploaded_file is not None:
# Save the uploaded file temporarily
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(uploaded_file.read())
# Open the temporary file with OpenCV
cap = cv2.VideoCapture(tfile.name)
# Check if video opened successfully
if not cap.isOpened():
st.error("Error opening video file")
else:
# Video properties
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
st.write(f"**Video Properties:** {width}x{height}px at {fps} FPS")
# Load fire particle images (you can add multiple images for variety)
# Ensure these images are in the same directory as this script
fire_images = []
fire_image_files = ['fire_particle1.png', 'fire_particle2.png', 'fire_particle3.png'] # Add your fire images here
for img_file in fire_image_files:
if os.path.isfile(img_file):
img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
if img is not None and img.shape[2] == 4: # Check for alpha channel
fire_images.append(img)
else:
st.error(f"Image {img_file} is not valid or doesn't have an alpha channel.")
else:
st.warning(f"Image file {img_file} not found.")
if len(fire_images) == 0:
st.error("No valid fire particle images found. Please ensure you have fire particle PNG images with transparency in the script directory.")
else:
# Create a temporary file to save the output video
tfile_output = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
# VideoWriter to write the output video
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(tfile_output.name, fourcc, fps, (width, height))
# Number of particles
num_particles = 30 # You can adjust this number
# Initialize particle properties
particles = []
for _ in range(num_particles):
fire_img = fire_images[randint(0, len(fire_images) - 1)]
scale = uniform(0.3, 1.0)
fire_resized = cv2.resize(fire_img, (0, 0), fx=scale, fy=scale)
x = randint(0, width - fire_resized.shape[1])
y = randint(int(height * 0.7), height - fire_resized.shape[0])
vx = uniform(-0.5, 0.5)
vy = uniform(-2.0, -0.5)
particles.append({
'img': fire_resized,
'x': x,
'y': y,
'vx': vx,
'vy': vy
})
frame_number = 0
progress_bar = st.progress(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Convert frame to BGRA
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
# Update and draw particles
for p in particles:
p['x'] += p['vx']
p['y'] += p['vy']
# Reset particle if it moves off-screen
if p['y'] < -p['img'].shape[0] or p['x'] < -p['img'].shape[1] or p['x'] > width:
fire_img = fire_images[randint(0, len(fire_images) - 1)]
scale = uniform(0.3, 1.0)
fire_resized = cv2.resize(fire_img, (0, 0), fx=scale, fy=scale)
p['img'] = fire_resized
p['x'] = randint(0, width - fire_resized.shape[1])
p['y'] = randint(int(height * 0.7), height - fire_resized.shape[0])
p['vx'] = uniform(-0.5, 0.5)
p['vy'] = uniform(-2.0, -0.5)
# Overlay the particle image onto the frame
overlay_particle(frame, p['img'], int(p['x']), int(p['y']))
# Convert frame back to BGR
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
# Write frame to output video
out.write(frame_bgr)
# Update progress bar
frame_number += 1
progress = frame_number / frame_count
progress_bar.progress(min(progress, 1.0))
# Release resources
cap.release()
out.release()
st.success("Video processing complete!")
st.video(tfile_output.name)
# Provide a download button
with open(tfile_output.name, 'rb') as f:
st.download_button('Download Processed Video', f, file_name='output_with_fire.mp4', mime='video/mp4')
# Cleanup temporary files
os.unlink(tfile.name)
os.unlink(tfile_output.name)
# Function to overlay particle image onto a frame
def overlay_particle(frame, particle_img, x, y):
"""
Overlays a particle image onto the frame at position (x, y).
The particle image must have an alpha channel.
"""
# Frame dimensions
h, w = frame.shape[:2]
# Particle image dimensions
h_p, w_p = particle_img.shape[:2]
# Check if the particle is out of frame bounds
if x >= w or y >= h or x + w_p <= 0 or y + h_p <= 0:
return # Particle is completely off-frame
# Compute the area of overlap
x_start = max(x, 0)
y_start = max(y, 0)
x_end = min(x + w_p, w)
y_end = min(y + h_p, h)
# Corresponding positions on the particle image
p_x_start = x_start - x
p_y_start = y_start - y
p_x_end = p_x_start + (x_end - x_start)
p_y_end = p_y_start + (y_end - y_start)
# Extract regions
roi = frame[y_start:y_end, x_start:x_end]
particle_roi = particle_img[p_y_start:p_y_end, p_x_start:p_x_end]
# Separate channels
particle_rgb = particle_roi[..., :3]
alpha = particle_roi[..., 3:] / 255.0 # Normalize alpha channel
# Blend the particle with the frame
roi[..., :3] = (1.0 - alpha) * roi[..., :3] + alpha * particle_rgb
# Place the blended region back into the frame
frame[y_start:y_end, x_start:x_end] = roi
fire_particle1.png, fire_particle2.png, etc.).Make sure you have the necessary Python packages installed. Run the following command in your terminal or command prompt:
pip install streamlit opencv-python numpy Pillow
app.py.app.py is located.streamlit run app.py
num_particles variable to add more or fewer fire particles.vx and vy in the particle initialization to change the speed and direction of particle movement.scale variable range in the particle initialization to make particles larger or smaller.If you don't have fire particle images, here are steps to create simple ones:
Using Image Editing Software:
Free Resources Online:
By following these steps, you should be able to add high-quality random moving fire particles to any uploaded video using the Streamlit app. Enjoy creating fiery effects in your videos! 🔥
Not yet included in a published release.