ros订阅图片python_ROS与Python入门教程-CompressedImage类型的订阅器和发布器

2023-05-16

ROS与Python入门教程-CompressedImage类型的订阅器和发布器

说明

这一节介绍订阅包含sensor_msgs::CompressedImage的主题,转换CompressedImage为numpy.ndarray,从而做检测和标记,再发布为CompressedImage类型的主题。

实现

在beginner_tutorials/scripts目录,新建subscriber_publisher_CompressedImage.py

$ roscd beginner_tutorials/scripts/

$ touch subscriber_publisher_CompressedImage.py

$ chmod +x subscriber_publisher_CompressedImage.py

$ rosed beginner_tutorials subscriber_publisher_CompressedImage.py

手工输入如下完整示例代码:(忽略注释部分)

#!/usr/bin/env python

"""OpenCV feature detectors with ros CompressedImage Topics in python.

This example subscribes to a ros topic containing sensor_msgs

CompressedImage. It converts the CompressedImage into a numpy.ndarray,

then detects and marks features in that image. It finally displays

and publishes the new image - again as CompressedImage topic.

"""

__author__ = 'Simon Haller '

__version__= '0.1'

__license__ = 'BSD'

# Python libs

import sys, time

# numpy and scipy

import numpy as np

from scipy.ndimage import filters

# OpenCV

import cv2

# Ros libraries

import roslib

import rospy

# Ros Messages

from sensor_msgs.msg import CompressedImage

# We do not use cv_bridge it does not support CompressedImage in python

# from cv_bridge import CvBridge, CvBridgeError

VERBOSE=False

class image_feature:

def __init__(self):

'''Initialize ros publisher, ros subscriber'''

# topic where we publish

self.image_pub = rospy.Publisher("/output/image_raw/compressed",

CompressedImage, queue_size = 10)

# self.bridge = CvBridge()

# subscribed Topic

self.subscriber = rospy.Subscriber("/camera/image/compressed",

CompressedImage, self.callback)

if VERBOSE :

print "subscribed to /camera/image/compressed"

def callback(self, ros_data):

'''Callback function of subscribed topic.

Here images get converted and features detected'''

if VERBOSE :

print 'received image of type: "%s"' % ros_data.format

#### direct conversion to CV2 ####

np_arr = np.fromstring(ros_data.data, np.uint8)

image_np = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)

#### Feature detectors using CV2 ####

# "","Grid","Pyramid" +

# "FAST","GFTT","HARRIS","MSER","ORB","SIFT","STAR","SURF"

method = "GridFAST"

feat_det = cv2.FeatureDetector_create(method)

time1 = time.time()

# convert np image to grayscale

featPoints = feat_det.detect(

cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY))

time2 = time.time()

if VERBOSE :

print '%s detector found: %s points in: %s sec.'%(method,

len(featPoints),time2-time1)

for featpoint in featPoints:

x,y = featpoint.pt

cv2.circle(image_np,(int(x),int(y)), 3, (0,0,255), -1)

cv2.imshow('cv_img', image_np)

cv2.waitKey(2)

#### Create CompressedIamge ####

msg = CompressedImage()

msg.header.stamp = rospy.Time.now()

msg.format = "jpeg"

msg.data = np.array(cv2.imencode('.jpg', image_np)[1]).tostring()

# Publish new image

self.image_pub.publish(msg)

#self.subscriber.unregister()

def main(args):

'''Initializes and cleanup ros node'''

ic = image_feature()

rospy.init_node('image_feature', anonymous=True)

try:

rospy.spin()

except KeyboardInterrupt:

print "Shutting down ROS Image feature detector module"

cv2.destroyAllWindows()

if __name__ == '__main__':

main(sys.argv)

代码分析:

代码:

# Python libs

import sys, time

# numpy and scipy

import numpy as np

from scipy.ndimage import filters

# OpenCV

import cv2

# Ros libraries

import roslib

import rospy

# Ros Messages

from sensor_msgs.msg import CompressedImage

分析:

导入所需的库,Python相关库,OpenCV相关库,ROS相关库,ROS相关消息

Time用于测量特征检测的时间

NumPy、SciPy和CV2用来实现处理转换,显示和特征检测

ROS消息需要来自sensor_msgs的CompressedImage

代码:VERBOSE = False

分析:如果设置为true,你会得到一些额外的信息打印到命令行(特征检测方法,检测点的数量,时间)

代码:

class image_feature:

def __init__(self):

...

def callback(self, ros_data):

分析:定义类,一个构造函数用于实例化,一个callback函数用于处理压缩的图片数据。

代码:The __init__ method

分析:发布主题/output/image_raw/compressed,订阅主题并用回调函数处理/camera/image/compressed,都传递CompressedImage的图片数据。

代码:

np_arr = np.fromstring(ros_data.data, np.uint8)

image_np = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)

分析:转换压缩图片数据为cv2的图片数据。这里先转换成numpy数组,再转换成CV2的图片(numpy.ndarray)

代码:

#### Feature detectors using CV2 ####

# "","Grid","Pyramid" +

# "FAST","GFTT","HARRIS","MSER","ORB","SIFT","STAR","SURF"

method = "GridFAST"

feat_det = cv2.FeatureDetector_create(method)

time1 = time.time()

分析:

第一行选择特征检测方法

第二行创建特征检测

第三行获取时间

代码:

# convert np image to grayscale

featPoints = feat_det.detect(cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY))

time2 = time.time()

if VERBOSE :

print '%s detector found: %s featpoints in: %s sec.' %(method,

len(featPoints),time2-time1)

分析:

cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY) 转换图像成灰度图

feat_det.detect( 获取特征点

第二行,记录时间点

第三行,VERBOSE 为真,输出相关信息。

代码:

for featpoint in featPoints:

x,y = featpoint.pt

cv2.circle(image_np,(int(x),int(y)), 3, (0,0,255), -1)

cv2.imshow('cv_img', image_np)

cv2.waitKey(2)

分析:在图片上画圆标注出特征点

代码:

#### Create CompressedIamge ####

msg = CompressedImage()

msg.header.stamp = rospy.Time.now()

msg.format = "jpeg"

msg.data = np.array(cv2.imencode('.jpg', image_np)[1]).tostring()

分析:

创建要发布的图片信息。

三个变量内容:header,format,data. data是cv2的图片转换成np.array,再输出成字符串。

代码:

# Publish new image

self.image_pub.publish(msg)

分析:最后是发布主题

测试节点

启动roscore

$ roscore

启动usbcam摄像头,使用ros by example的程序例子启动摄像头。

$ rosrun rbx1_vision usb_cam.launch

启动节点

$ rosrun beginner_tutorials subscriber_publisher_CompressedImage.py

效果:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ros订阅图片python_ROS与Python入门教程-CompressedImage类型的订阅器和发布器 的相关文章

  • 打不开磁盘...或它所依赖的某个快照磁盘

    这主要是非正常关虚拟机造成的 xff0c 具体原因如下 xff1a 虚拟机为了防止有多虚拟机共用一个虚拟磁盘 xff08 就是后 缀为 vmdk那个文件 xff09 造成数据的丢失和性能的削弱 xff0c 每次启动虚拟机时会给每个虚拟磁盘加
  • shiro-cas------自定义登录页面

    我的自定义登录页 xff08 需要登录页面的 xff0c 推荐给你们一个登陆页面地址 xff09 我的项目结构 xff1a 学习过程参考官方文档https apereo github io cas 5 3 x installation Us
  • docker安装nacos

    这里我们安装单机nacos集群 Nacos的单节点模式 standalone xff0c 配置的数据是默认存储到内嵌的数据库derby中 如果我们要搭建集群的话 xff0c 数据需要共享 xff0c 此时内嵌数据库无法满足 xff0c 需要
  • Java从控制端输入一个未知长度的数组

    String str 61 sc next toString String arr 61 str split 34 34 int b 61 new int arr length for int j 61 0 j lt b length j
  • win10 安装db2 10.1 并使用DBserver连接db2数据库

    系统 xff1a win10 64 专业版 db2下载 xff1a 链接 xff1a https pan baidu com s 1IiAUdRUTIDcGAew7WbVTHQ 提取码 xff1a wzpg dbServer 链接 xff1
  • win10 安装 cognos 10.2.0

    安装包链接 xff1a 链接 xff1a https pan baidu com s 1z yMlvjd1fMHXOv gbCc8A 提取码 xff1a jcfd 这里我安装到d盘cognos下 bi svr 32b 10 2 win ml
  • CentOS 7的安装

    访问其官网 xff0c https www centos org xff0c 点击Get CentOS Now xff0c 点击alternative downloads xff0c 点击CentOS 7列表中的x86 64 xff0c 点
  • PowerDesigner16.5汉化破解版安装教程(含安装文件、汉化包、破解文件)

    一 软件安装 1 下载安装包 xff08 包含安装文件 汉化包 破解文件 xff09 xff0c 下载链接在文章最后 xff0c 失效请留言 2 下载后文件内容如下 3 进入安装文件中双击安装文件等待初始化完成后选择next 4 继续下一步
  • 数据库设计——评论回复功能

    1 概述 评论功能已经成为APP和网站开发中的必备功能 本文主要介绍评论功能的数据库设计 评论功能最主要的是发表评论和回复评论 xff08 删除功能在后台 xff09 评论功能的拓展功能体现有以下几方面 xff1a xff08 1 xff0
  • 问答社区竞品分析——知乎与悟空的较量

    1 产品定位 知乎 精英化 知乎的产品定位是知识分享性的社区平台 xff0c 面向各行业精英人群和广大网友 属于知乎大V的精英人群在此发表自己的见解 xff0c 寻找精神上的认同和物质上的奖励 而广大网友在此获得感兴趣的知识或作为娱乐消遣的
  • VirtualBox搭建CenterOS7-Docker,实现IntelliJ IDEA部署Springboot Docker镜像

    服务器安装 Docker 首选安装在Linux系统上 xff0c xff08 有钱的大佬可以直接在阿里云买服务器 xff0c 可以省略这个步骤 xff09 开始为了偷懒在 win7上安装了DockerToolbox xff08 win10安
  • 757计算机电子元件,飞行员的好帮手 波音757的发动机指示与机组报警系统简介...

    原标题 xff1a 飞行员的好帮手 波音757的发动机指示与机组报警系统简介 陈光 文 在以往的飞机中 需要驾驶员监测的发动机参数均是利用驾驶舱仪表板上的电子 机械仪表来显示的 再用一些声 光告警装置在飞机 发动机的某些系统与元件出现故障或
  • linux crontab 每隔10秒执行一次

    linux下定时执行任务的方法 在LINUX中你应该先输入crontab e xff0c 然后就会有个vi编辑界面 xff0c 再输入0 3 1 clearigame2内容到里面 wq 保存退出 在LINUX中 xff0c 周期执行的任务一
  • 生命的轨迹会沿着期望的方向走去

    生命的轨迹会沿着期望的方向走去 平凡的世界 飘 巴黎圣母院 我的苦难我的大学 活着 幸福了吗 痛并快乐着 大学期间 xff1a 狼图腾 我的大学 高尔基 读大学该读什么 霍乱时期的爱情 百年孤独 断舍离 穆斯林的葬礼 宋庆龄传 西班牙旅游日
  • MySQL [Err] 1241 - Operand should contain 1 column(s)

    Operand should contain 1 column s 翻译过来就是 xff1a 操作数应包含一列 xff1b 错误原因 往往是我们多出一列操作数 xff0c 或者给的参数格式不正确 xff1b 解决方法 xff1a Demo1
  • docker-compose开机自启动设置

    前提 需要设置docker开机自启动 xff1a systemctl enable docker docker compose开机自启动两种方式 第一种方式 主要步骤如下 xff1a xff08 1 xff09 创建docker compo
  • NFS使用详解之三.NFS传输速度优化

    十 nfs的传输速度优化 如果按 mount o nolock 192 168 1 220 假设为宿主机ip mnt nfs mnt nfs t 来mount xff0c 传输速度可能很慢 xff0c 只有几K到几十K左右 xff0c 所以
  • Auto-created primary key used when not defining a primary key

    When you define a model in Django without specifying a primary key Django will automatically create a primary key for yo
  • linux ed命令的使用

    ed 编辑器是 Linux 操作系统下最简单的文本编辑器 它是以行为单位对文件进行编辑的编辑器 xff0c 而不像 MS DOS 系统下的 edit 那样是以整个屏幕框架为单位对文件进行编辑的 因此 xff0c 如果你已经习惯了使用 edi
  • type=AAAA: Host found but no data record of requested type

    I 39 m using Postfix When I try to send an email to a local domain I receive the following error Host or domain name not

随机推荐