Using a ros subscriber together with python object oriented programming

May I ask that why I have an error message “Traceback (most recent call last):
File “”, line 81, in
depthCentre = init.showDepth_analysis()
File “”, line 39, in showDepth_analysis
depth_image = bridge.imgmsg_to_cv2(self.showDepth, “passthrough”)
File “/opt/ros/kinetic/lib/python2.7/dist-packages/cv_bridge/”, line 163, in imgmsg_to_cv2
dtype, n_channels = self.encoding_to_dtype_with_channels(img_msg.encoding)
AttributeError: ‘NoneType’ object has no attribute ‘encoding’”

The code related is:
class MyDistance:
def init(self):
self.showDepth = None
self.depthImage_sub = rospy.Subscriber("/camera/aligned_depth_to_color/image_raw",Image, self.showDepth_callback, queue_size=1, buff_size=2**24)
def showDepth_callback(self,data):
self.showDepth = data
def showDepth_analysis(self): depth_image = bridge.imgmsg_to_cv2(self.showDepth, “passthrough”)
Thank you for reading this post, and I really unable to identify the mistake in the program, any help is appreciated

Hi @zhangmingcheng28,

The problem was that the image message is None (null), which is why you have the error:

AttributeError: ‘NoneType’ object has no attribute ‘encoding’”

Since it appears the image is coming from a subscriber, then it could mean the subscriber is not working for some reason(s):

  • For one, I see that you did not call rospy.spin(). Could you add that as the last line of def init(self).
  • Also, is the topic name correct?

Finally, please tell us the course are you taking and the unit are you on.

Thank you for the help in the question. I am currently not enrolled in any course yet, but I normally will go into the section of the courses that I think is helpful to my project and study that specific chapter only. I have a deadline to meet, so I don’t really have time to go through entire course. (My subscription allow me to access all the courses available).
Thank you again for the help.

1 Like