Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from ultralytics import YOLO
|
| 6 |
+
from ultralytics.utils.plotting import Annotator, colors
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
|
| 9 |
+
track_history = defaultdict(lambda: [])
|
| 10 |
+
model = YOLO("last_1.pt")
|
| 11 |
+
names = model.model.names
|
| 12 |
+
|
| 13 |
+
# Function to perform object tracking
|
| 14 |
+
def perform_object_tracking(video_path):
|
| 15 |
+
cap = cv2.VideoCapture(video_path)
|
| 16 |
+
assert cap.isOpened(), "Error reading video file"
|
| 17 |
+
|
| 18 |
+
while cap.isOpened():
|
| 19 |
+
success, frame = cap.read()
|
| 20 |
+
if success:
|
| 21 |
+
results = model.track(frame, persist=True, verbose=False)
|
| 22 |
+
boxes = results[0].boxes.xyxy.cpu()
|
| 23 |
+
|
| 24 |
+
if results[0].boxes.id is not None:
|
| 25 |
+
clss = results[0].boxes.cls.cpu().tolist()
|
| 26 |
+
track_ids = results[0].boxes.id.int().cpu().tolist()
|
| 27 |
+
|
| 28 |
+
annotator = Annotator(frame, line_width=2)
|
| 29 |
+
|
| 30 |
+
for box, cls, track_id in zip(boxes, clss, track_ids):
|
| 31 |
+
annotator.box_label(box, color=colors(int(cls), True), label=names[int(cls)])
|
| 32 |
+
|
| 33 |
+
track = track_history[track_id]
|
| 34 |
+
track.append((int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)))
|
| 35 |
+
|
| 36 |
+
if len(track) > 30:
|
| 37 |
+
track.pop(0)
|
| 38 |
+
|
| 39 |
+
points = np.array(track, dtype=np.int32).reshape((-1, 1, 2))
|
| 40 |
+
cv2.circle(frame, (track[-1]), 7, colors(int(cls), True), -1)
|
| 41 |
+
cv2.polylines(frame, [points], isClosed=False, color=colors(int(cls), True), thickness=2)
|
| 42 |
+
|
| 43 |
+
# Display the frame with tracking annotations
|
| 44 |
+
st.image(frame, channels="BGR")
|
| 45 |
+
|
| 46 |
+
else:
|
| 47 |
+
break
|
| 48 |
+
|
| 49 |
+
# Release video capture
|
| 50 |
+
cap.release()
|
| 51 |
+
|
| 52 |
+
# Streamlit app
|
| 53 |
+
def main():
|
| 54 |
+
st.title("Object Tracking with Streamlit")
|
| 55 |
+
|
| 56 |
+
uploaded_file = st.file_uploader("Upload a video file", type=["mp4"])
|
| 57 |
+
|
| 58 |
+
if uploaded_file is not None:
|
| 59 |
+
video_path = f"uploaded_video.{uploaded_file.name.split('.')[-1]}"
|
| 60 |
+
with open(video_path, "wb") as f:
|
| 61 |
+
f.write(uploaded_file.read())
|
| 62 |
+
|
| 63 |
+
perform_object_tracking(video_path)
|
| 64 |
+
|
| 65 |
+
if __name__ == "__main__":
|
| 66 |
+
main()
|