1. 问题描述
最近尝试将目标检测模型集成到ROS上,运行环境为Ubuntu 16.04 + ROS Kinetic
目标检测模块写成了一个node,监听其他node发送过来的图像信息,对接收的图像进行目标检测。测试代码如下所示:
class DetectorNode(object):
def __init__(self):
# detection model parameters can be received from server
root_dir = '/home/yq/catkin_ws/src/object_detection/scripts'
definition_file = osp.join(root_dir, 'deploy.prototxt')
binary_file = osp.join(root_dir, 'frcnn_xian_iter_30000.caffemodel')
model_name = 'vgg-9s-600-rpn-base'
img_size = [480, 640] # [rows, cols]
# initialize object detector
self.detector = Detector(definition_file, binary_file, model_name, img_size, gpu_id=1)
rospy.init_node('listener', anonymous=True)
self._bridge = CvBridge()
self.sub_img = rospy.Subscriber('chatter', Image, self.rgb_callback, queue_size=1)
rospy.spin()
def rgb_callback(self, data):
try:
cv_img = self._bridge.imgmsg_to_cv2(data)
obj_detect, process_img = self.detector.detect(cv_img, is_show=1)
cv2.imshow('result', process_img)
cv2.waitKey(1000)
except CvBridgeError as e:
print(e)
其中在初始化目标检测类Detector的代码中设置了caffe使用第一块卡运行。
但是实际rosrun该节点的时候,一直检测不到有任何卡被该程序占用,同时一张图的检测时间需要十几秒。这显然说明当前node是在CPU上运行。
2. 解决方案
google的结果解释为:Detector初始化函数和rgb_callback函数使用的是不同的进程,只有执行初始化的那个进程可以使用GPU,callback的进程,因为没有声明,默认使用的是CPU。
暂时的解决方案是在rgb_callback函数当中也加上如下语句
caffe.set_mode_gpu()
caffe.set_device(gpu_id)