2

我创建了一个 ROS 包,其中有一些 python 脚本。python脚本基于torch模块(它是pytorch模型的推理代码)。当我尝试运行我的脚本时,它给了我一个错误:
ImportError: No module named torch

为了安装 ROS,我使用 了 ROS wiki 的说明。为了验证我的安装,我遵循了 ROS(一个简单的发布者和订阅者)的示例代码,它运行良好。我的系统信息是:

python:3.6.9
torch:1.1.0
torchvision:0.3.0
操作系统内核:Linux 4.15.0-74-通用
操作系统发行版:Ubuntu 18.04.3

我想导入以下库:

import torch
from cv_bridge import CvBridge
import cv2
import os
import numpy as np
from torch.autograd import Variable
from torchvision import transforms
import torch.nn.functional as F
import torch._utils
import time
from PIL import Image 

我的 CMake 文件如下:

cmake_minimum_required(VERSION 2.8.3)
project(inference_pytorch)

## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)

set(Torch_DIR ".local/lib/python3.6/site-packages/torch/share/cmake/Torch")

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  cv_bridge
)
find_package(Torch REQUIRED)
find_package(OpenCV 3 REQUIRED)
## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)

###################################
## catkin specific configuration ##
###################################
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES inference_pytorch
#  CATKIN_DEPENDS roscpp rospy std_msgs
#  DEPENDS system_lib
)

###########
## Build ##
###########

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
  ${catkin_INCLUDE_DIRS}
  ${OPENCV_INCLUDE_DIRS}
  ${Torch_INSTALL_INCLUDE}
  ${Torch_DIR}
)

#############
## Install ##
#############

# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html

install(PROGRAMS
   scripts/inference_test.py
   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
 )

 catkin_install_python(PROGRAMS scripts/inference_test.py
                      DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})

link_directories(
  ${Torch_INSTALL_LIB}
)

现在,我应该如何编辑 CMAKE 文件以将提到的库添加到我的 ROS 包中?

4

1 回答 1

1

最后,我发现安装的 ROS 可以使用 python2,所以我用 pip2 安装了 torch。另外,在 cmake 文件中设置火炬路径。现在它起作用了!

于 2020-02-24T08:07:32.250 回答