I have a loop that is displaying a video frame by frame.
My issue is, I was expecting the images to display frame by frame…like flipping through a set of index cards; however, I’m getting the frames to display underneath each other one by one in a cascading fashion (if that makes sense).
Is there a way I can close an image in my streamlit app?
Here is my code
cap = cv2.VideoCapture('/content/video.mp4')
while cap.isOpened():
ret, image = cap.read()
st.image(Image.open(image), width=1200)
Thank you for describing the expected and actual behavior, and providing a code snippet!
I would recommend using st.empty() to create a container for the image outside the while loop. In the while loop, call the .image() function on the container to draw the image, instead of st.image().
For every iteration i of the while loop, image_i-1 will be replaced by image_i:
import streamlit as st
import cv2
import time
cap = cv2.VideoCapture("/content/video.mp4")
# Create a single-element container
image_container = st.empty()
while cap.isOpened():
ret, frame = cap.read()
if ret:
# Display the frame in the container and
# Replace contents of the container with next frame on the next iteration
image_container.image(frame, width=800)
time.sleep(0.05) # Optional delay
else:
break
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.