Search code examples
opencvkinectrosdepth

Get Depth image in grayscale in ROS with imgmsg_to_cv2 [python]


I am using Kinect v1 and I want to get the depth image in greyscale mode from the channel "/camera/depth_registered/image" in ROS. As I found here, I can do it by using the function imgmsg_to_cv2. The default desired_encoding for my depth messages is "32FC1", which I keep. The problem is that when I use the cv2.imshow() function to show it, I get the image in binary... When I do the same for the RGB image everything is being shown just fine...

Any help appreciated!


Solution

  • So after all, I found a solution, which you can see here:

    def Depthcallback(self,msg_depth): # TODO still too noisy!
    try:
      # The depth image is a single-channel float32 image
      # the values is the distance in mm in z axis
      cv_image = self.bridge.imgmsg_to_cv2(msg_depth, "32FC1")
      # Convert the depth image to a Numpy array since most cv2 functions
      # require Numpy arrays.
      cv_image_array = np.array(cv_image, dtype = np.dtype('f8'))
      # Normalize the depth image to fall between 0 (black) and 1 (white)
      # http://docs.ros.org/electric/api/rosbag_video/html/bag__to__video_8cpp_source.html lines 95-125
      cv_image_norm = cv2.normalize(cv_image_array, cv_image_array, 0, 1, cv2.NORM_MINMAX)
      # Resize to the desired size
      cv_image_resized = cv2.resize(cv_image_norm, self.desired_shape, interpolation = cv2.INTER_CUBIC)
      self.depthimg = cv_image_resized
      cv2.imshow("Image from my node", self.depthimg)
      cv2.waitKey(1)
    except CvBridgeError as e:
      print(e)
    

    However, the result is not that perfect as the one I get from the image_view node of ROS, but it is still pretty acceptable!