ОШИБКА: TypeError: невозможно преобразовать тензор типа устройства cuda:0 в numpy. Используйте Tensor.cpu(), чтобы сначаPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 ОШИБКА: TypeError: невозможно преобразовать тензор типа устройства cuda:0 в numpy. Используйте Tensor.cpu(), чтобы снача

Сообщение Anonymous »

Я использую алгоритм машинного обучения для обнаружения конусов на видео и сопоставления их с трехмерным миром.

Код хорошо обнаруживает конусы, но когда я пытаюсь использовать карту глубины для построения трехмерный мир, я получаю эту ошибку:

TypeError: невозможно преобразовать тензор типа устройства cuda:0 в numpy. Используйте Tensor.cpu(), чтобы сначала скопировать тензор в память хоста.

Я уже вызываю .cpu() там, где, как мне кажется, мне следует быть, поэтому я здесь немного запутался.

Любая помощь приветствуется!
import cv2
import torch
import numpy as np
from torchvision.transforms import Compose, Resize, ToTensor, Normalize
from PIL import Image
from ultralytics import YOLO
import os
import pyvista as pv

# Load the YOLOv8 model
def load_yolov8_model():
print("Loading YOLOv8 model...")
model = YOLO("yolov8n.pt") # Replace with the path to your trained YOLOv8 model
print("YOLOv8 model loaded.")
return model

# Process the frame for cone detection using YOLOv8
def detect_cones(frame, model):
# Convert frame to RGB (YOLO expects RGB images)
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Perform detection
results = model(frame_rgb)

# Parse the results (you can access the results in a variety of formats)
cones = results[0].boxes.xywh # Bounding box coordinates (center_x, center_y, width, height)
confidences = results[0].boxes.conf # Confidence scores for detections
classes = results[0].boxes.cls # Class IDs for each detected object

print(f"Detected {len(cones)} cones in frame.")

return cones, confidences, classes

# Generate 3D positions for each cone based on depth map and frame
def generate_cone_positions(depth_map, frame, cones):

print("Generating cone positions...")

# Original frame dimensions
frame_height, frame_width = frame.shape[:2]

# Depth map dimensions
depth_height, depth_width = depth_map.shape[:2]

# Calculate scaling factors between frame and depth map
scale_x = depth_width / frame_width
scale_y = depth_height / frame_height

cone_positions_3d = []

# Field of view (adjust according to your camera)
fov_x = 60 # Horizontal FOV in degrees
fov_y = 60 # Vertical FOV in degrees

# Focal lengths
fx = frame_width / (2 * np.tan(np.radians(fov_x / 2)))
fy = frame_height / (2 * np.tan(np.radians(fov_y / 2)))

for cone in cones:
x_center, y_center, w, h = cone

# Scale cone coordinates to match depth map resolution
x_center_depth = int(x_center * scale_x)
y_center_depth = int(y_center * scale_y)

# Ensure indices are within bounds
if 0

Подробнее здесь: https://stackoverflow.com/questions/792 ... use-tensor
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»