Код: Выделить всё
import cv2
import base64
import requests
import time
# Define API details
API_KEY = "*********" # Replace with your actual API key
DATASET_SLUG = "bowl-starting" # Replace with your dataset slug
VERSION_NUMBER = "3" # Replace with your version number
API_URL = f"https://classify.roboflow.com/:{DATASET_SLUG}/{VERSION_NUMBER}?api_key={API_KEY}"
# Path to the video
video_path = r"/content/afridi.mp4"
# Initialize video capture
cap = cv2.VideoCapture(video_path)
# Get video properties
fps = int(cap.get(cv2.CAP_PROP_FPS)) # Frames per second
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # Total frames
duration = frame_count / fps # Duration of the video in seconds
# Initialize variables
timestamps = [] # List to store timestamps
frame_number = 0 # Current frame number
# Process every nth frame (for speedup)
frame_skip = 5 # Skip every 5 frames (adjust as needed)
# Process the video frame by frame
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break # Break if no more frames
# Skip frames to speed up processing
if frame_number % frame_skip != 0:
frame_number += 1
continue
# Resize the frame to 224x224
resized_frame = cv2.resize(frame, (224, 224))
# Encode the resized frame as a JPEG in memory
retval, buffer = cv2.imencode('.jpg', resized_frame)
img_str = base64.b64encode(buffer).decode('utf-8') # Convert to base64 string
# Prepare the API request payload
payload = {"image": img_str}
# Debugging: Log before making the request
print(f"Processing frame {frame_number}... Sending API request")
start_time = time.time()
try:
# Run inference on the frame (send POST request to Roboflow)
response = requests.post(API_URL, json=payload, timeout=10) # Add timeout to prevent indefinite waiting
response.raise_for_status() # Raise an error for HTTP error codes
elapsed_time = time.time() - start_time
# Debugging: Log response time
print(f"API responded in {elapsed_time:.2f} seconds")
# Parse response
response_data = response.json()
# Check for predictions
predictions = response_data.get('predictions', [])
for prediction in predictions:
if prediction['class'] == "Bowl Starting": # Replace with your actual class name
timestamp = frame_number / fps # Calculate timestamp in seconds
timestamps.append(timestamp)
break # No need to process further predictions for this frame
except requests.exceptions.RequestException as e:
# Handle API errors or timeouts
print(f"Error with API request: {e}")
# Increment the frame number
frame_number += 1
# Release the video capture
cap.release()
# Print the collected timestamps
print("Timestamps for 'Bowl Starting':", timestamps)
Что я пробовал:
- Проверил формат конечной точки API.
- Убедился, что изображение правильно закодировано как строка base64.
- Пропробовал разные методы отправки изображения (например, отправка как файл вместо base64).
- Скорректированы таймауты и обработка ошибок.
- Есть ли ошибка при отправке изображения в API Roboflow?
- Существует ли потенциальная проблема с обработкой видеокадров или изменение размера?
- Существуют ли какие-либо рекомендации по отправке данных изображения для вывода Roboflow при обработке видео?
Подробнее здесь: https://stackoverflow.com/questions/792 ... eo-process
Мобильная версия