0
$\begingroup$

Rosanswers logo

I wrote a basic node that reads an image from a local folder and publishes it. However, the topic is empty, i can not display the image when i use the image viewer. The cv2 image is being loaded correctly because i can display it with cv2.imshow function so the problem is the way i convert it to imgmsg.

I am not sure if this line works as it should:

image_message = self.bridge.cv2_to_imgmsg(cv_image, "passthrough")

The whole node is as simple as this:

class image_publisher:
 def __init__(self):
  self.image_pub = rospy.Publisher("image_topic",Image)
  cv_image = cv2.imread('/Pictures/image.png',0)
  self.bridge = CvBridge()
  image_message = self.bridge.cv2_to_imgmsg(cv_image, "passthrough")
  self.image_pub.publish(image_message)

Originally posted by rosberrypi on ROS Answers with karma: 75 on 2019-07-04

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

As PeteBlackerThe3rd suggested you're publishing the image in your init method right after the publisher is created. Here is an example class that works for your case:

import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
import time


class ImagePublisher(object):

  def __init__(self):
    self.node_rate = 1

    self.image_pub = rospy.Publisher("image_topic", Image)
    cv_image = cv2.imread('/Pictures/image.png',0)
    self.bridge = CvBridge()

    try:
      self.image_message = self.bridge.cv2_to_imgmsg(cv_image, "passthrough")
    except CvBridgeError as e:
      print(e)

    time.sleep(5)
    self.image_pub.publish(self.image_message)

  def doSmth(self):
    rospy.loginfo('its working!')
    # self.image_pub.publish(self.image_message)

  def run(self):
    loop = rospy.Rate(self.node_rate)
    while not rospy.is_shutdown():
      self.doSmth()
      loop.sleep()

If you want to publish the image only once then use the time.sleep() in your init . Otherwise if you want to publish on some rate then uncomment the publish line in doSmth().

EDIT: WIth image_view I am encountering conversion errors due to encoding/color formats. In my case it is trying to convert image from '8UC3' to 'bgr8' so I had to change this line:

self.image_message = self.bridge.cv2_to_imgmsg(cv_image, encoding="bgr8")

Now I can see the image using:

rosrun image_view image_view image:=/image_topic

Anyway the initial problem you had was still related to publishing the image in your init method right after the publisher is create.
Also note that if you are publishing it only once as in your example, make sure to run image_view before you run your node.


Originally posted by pavel92 with karma: 1655 on 2019-07-08

This answer was ACCEPTED on the original site

Post score: 1

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.