0
$\begingroup$

I'm developing a live object detection app using Streamlit and the YOLOv8 model. The app runs smoothly with real-time inference on my local machine. However, when I deploy it to Hugging Face Spaces, only the first and last frames of the video appear on the client side.

Here is what I did

import streamlit as st
import cv2
import tempfile
import os
from ultralytics import YOLO

model_pk = YOLO('models/model_pk.pt')

# Initialize session state
if 'started' not in st.session_state:
    st.session_state.started = False

st.title("Video Streamer")

if not st.session_state.started:
    uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov", "mkv"])

    if uploaded_file is not None:
        # Save the uploaded video to a temporary file
        tfile = tempfile.NamedTemporaryFile(delete=False)
        tfile.write(uploaded_file.read())
        video_path = tfile.name

        # Stream the video
        st.video(video_path)

        if st.button("Start Streaming"):
            st.session_state.video_path = video_path
            st.session_state.started = True
else:
    video_path = st.session_state.video_path
    # OpenCV video capture
    cap = cv2.VideoCapture(video_path)
    stframe = st.empty()

    while cap.isOpened():
        ret, frame = cap.read()
        frame = cv2.resize(frame, (640, 640))

        height, width, _ = frame.shape

        results_pk = model_pk(frame, conf=0.5)

        annotated_frame = results_pk[0].plot()

        annotated_frame = cv2.resize(annotated_frame, (height, width))

        if not ret:
            break

        stframe.image(annotated_frame, channels="BGR")

    cap.release()
    os.remove(video_path)
    st.session_state.started = False

I would appreciate any help in resolving this issue.

$\endgroup$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.