Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445462 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586import cv2from ultralytics import YOLOimport streamlit as stfrom tempfile import NamedTemporaryFile# Load YOLOv8 modelmodel = YOLO("yolov8n.pt")# Streamlit UIst.title("🔍 YOLOv8 Object Detection on Video")# Upload video fileuploaded_file = st.file_uploader("Upload Video", type=["mp4", "avi", "mov"])if uploaded_file is not None:# Save the uploaded video to a temporary filetemp_input_file = NamedTemporaryFile(delete=False)temp_input_file.write(uploaded_file.read())temp_input_file.flush()# Display the uploaded videost.video(temp_input_file.name)# Define the output video file pathtemp_output_file = NamedTemporaryFile(delete=False, suffix='.mp4')# Open the input video filecap = cv2.VideoCapture(temp_input_file.name)# Check if the video was opened successfullyif not cap.isOpened():st.error("Error: Could not open video file.")else:# Get video propertiesframe_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))fps = cap.get(cv2.CAP_PROP_FPS)# Define codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for .mp4 filesout = cv2.VideoWriter(temp_output_file.name, fourcc, fps, (frame_width, frame_height))# Process the video frame by framewhile cap.isOpened():ret, frame = cap.read()if not ret:2 unmodified lines# Perform object detectionresults = model(frame)# Access detection resultsif results:for result in results:boxes = result.boxes # Access boxes attributefor box in boxes:x1, y1, x2, y2 = map(int, box.xyxy[0])conf = box.conf[0]cls = box.cls[0]label = f'{model.names[int(cls)]} {conf:.2f}'# Draw bounding boxes on the framecv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)# Write the frame with bounding boxes to the output videoout.write(frame)# Release resourcescap.release()out.release()cv2.destroyAllWindows()st.success("Video processing complete!")# Display the processed video in the browserst.video(temp_output_file.name)# Provide a download link for the processed videowith open(temp_output_file.name, 'rb') as file:btn = st.download_button(label="Download Processed Video",data=file,file_name="processed_video.mp4",mime="video/mp4")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748492 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586import streamlit as stimport cv2import numpy as npfrom ultralytics import YOLOfrom tempfile import NamedTemporaryFileimport os# Initialize YOLOv8 modelmodel = YOLO("yolov8n.pt")# Streamlit app title and creator informationst.markdown("Created by: [Engr. Hamesh Raj](https://www.linkedin.com/in/datascientisthameshraj/)")st.title("🎥 YOLOv8 Object Detection on Videos")# Sidebar for video uploadst.sidebar.header("Upload Video")uploaded_video = st.sidebar.file_uploader("Choose a video...", type=["mp4", "mov", "avi", "mkv"])if uploaded_video is not None:# Save the uploaded video to a temporary filetemp_video = NamedTemporaryFile(delete=False)temp_video.write(uploaded_video.read())video_path = temp_video.name# Display the uploaded videost.sidebar.video(uploaded_video)# Submit button to process the videoif st.sidebar.button("Submit"):st.subheader("Processing Video...")# Open the video filecap = cv2.VideoCapture(video_path)frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))fps = cap.get(cv2.CAP_PROP_FPS)# Create a temporary file to save the output videotemp_output_video = NamedTemporaryFile(delete=False, suffix='.mp4')output_video_path = temp_output_video.name# Define codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))# Process each frame of the videowhile cap.isOpened():ret, frame = cap.read()if not ret:2 unmodified lines# Perform object detectionresults = model(frame)# Draw bounding boxes on the framefor result in results:for box in result.boxes:x1, y1, x2, y2 = map(int, box.xyxy[0])conf = box.conf[0]cls = box.cls[0]label = f'{model.names[int(cls)]} {conf:.2f}'cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)out.write(frame)cap.release()out.release()# Display the processed videost.subheader("Processed Video")st.video(output_video_path)# Download button for the processed videowith open(output_video_path, "rb") as file:st.download_button(label="Download Processed Video",data=file,file_name="processed_video.mp4",mime="video/mp4")# Clean up temporary filesos.remove(video_path)os.remove(output_video_path)
app.py+49-49