Spaces:
Sleeping
Sleeping
import os | |
import streamlit as st | |
import cv2 | |
import numpy as np | |
from ultralytics import YOLO | |
from PIL import Image | |
import tempfile | |
# Directly set the path for the model | |
MODEL_PATH = 'best.pt' | |
# Initialize YOLO model with custom trained weights | |
model = YOLO(MODEL_PATH) | |
def detect_rhino_image(image): | |
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) | |
results = model(image)[0] | |
for box in results.boxes.data.tolist(): | |
x1, y1, x2, y2, score, class_id = box | |
if score > 0.5: | |
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 4) | |
cv2.putText(image, results.names[int(class_id)].upper(), (int(x1), int(y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 1.3, (0, 255, 0), 3, cv2.LINE_AA) | |
return image | |
def detect_rhino_video(video_file): | |
cap = cv2.VideoCapture(video_file.name) | |
ret, frame = cap.read() | |
H, W, _ = frame.shape | |
out = cv2.VideoWriter(video_file.name + '_output.mp4', cv2.VideoWriter_fourcc(*'MP4V'), int(cap.get(cv2.CAP_PROP_FPS)), (W, H)) | |
while ret: | |
results = model(frame)[0] | |
for box in results.boxes.data.tolist(): | |
x1, y1, x2, y2, score, class_id = box | |
if score > 0.5: | |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 4) | |
cv2.putText(frame, results.names[int(class_id)].upper(), (int(x1), int(y1 - 10)), cv2.FONT_HERSHEY_SIMPLEX, 1.3, (0, 255, 0), 3, cv2.LINE_AA) | |
out.write(frame) | |
ret, frame = cap.read() | |
cap.release() | |
out.release() | |
cv2.destroyAllWindows() | |
return video_file.name + '_output.mp4' | |
st.title('Rhinoceros Detection App') | |
st.write("Upload an image or video of rhinoceroses for detection.") | |
file = st.file_uploader("Choose a file...", type=["jpg", "jpeg", "png", "mp4"]) | |
if file is not None: | |
if file.type.split('/')[0] == 'image': | |
image = Image.open(file) | |
st.image(detect_rhino_image(image), caption='Processed Image', use_column_width=True) | |
elif file.type.split('/')[0] == 'video': | |
tfile = tempfile.NamedTemporaryFile(delete=False) | |
tfile.write(file.read()) | |
processed_video = detect_rhino_video(tfile) | |
st.video(processed_video) |