You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

283 lines
10 KiB

2 years ago
  1. # Example 7
  2. In this example, we will review the [image_view](http://wiki.ros.org/image_view?distro=melodic) ROS package and a Python script that captures an image from the [RealSense camera](https://www.intelrealsense.com/depth-camera-d435i/).
  3. <p align="center">
  4. <img src="https://raw.githubusercontent.com/hello-robot/stretch_tutorials/main/images/camera_image.jpeg"/>
  5. <img src="https://raw.githubusercontent.com/hello-robot/stretch_tutorials/main/images/camera_image_edge_detection.jpeg"/>
  6. </p>
  7. BBegin by checking out the [feature/upright_camera_view](https://github.com/hello-robot/stretch_ros/tree/feature/upright_camera_view) branch in the [stretch_ros](https://github.com/hello-robot/stretch_ros) repository. The configuration of the camera results in the images being displayed sideways. Thus, this branch publishes a new topic that rotates the raw image upright.
  8. ```bash
  9. cd ~/catkin_ws/src/stretch_ros/stretch_core
  10. git checkout feature/upright_camera_view
  11. ```
  12. Then run the stretch driver launch file.
  13. ```bash
  14. # Terminal 1
  15. roslaunch stretch_core stretch_driver.launch
  16. ```
  17. To activate the [RealSense camera](https://www.intelrealsense.com/depth-camera-d435i/) and publish topics to be visualized, run the following launch file in a new terminal.
  18. ```bash
  19. # Terminal 2
  20. roslaunch stretch_core d435i_low_resolution.launch
  21. ```
  22. Within this tutorial package, there is an RViz config file with the topics for perception already in the Display tree. You can visualize these topics and the robot model by running the command below in a new terminal.
  23. ```bash
  24. # Terminal 3
  25. rosrun rviz rviz -d /home/hello-robot/catkin_ws/src/stretch_tutorials/rviz/perception_example.rviz
  26. ```
  27. ## Capture Image with image_view
  28. There are a couple of methods to save an image using the [image_view](http://wiki.ros.org/image_view) package.
  29. **OPTION 1:** Use the `image_view` node to open a simple image viewer for ROS *sensor_msgs/image* topics.
  30. ```bash
  31. # Terminal 4
  32. rosrun image_view image_view image:=/camera/color/image_raw_upright_view
  33. ```
  34. Then you can save the current image by right-clicking on the display window. By deafult, images will be saved as frame000.jpg, frame000.jpg, etc. Note, that the image will be saved to the terminal's current work directory.
  35. **OPTION 2:** Use the `image_saver` node to save an image to the terminals current work directory.
  36. ```bash
  37. # Terminal 4
  38. rosrun image_view image_saver image:=/camera/color/image_raw_upright_view
  39. ```
  40. ## Capture Image with Python Script
  41. In this section, you can use a Python node to capture an image from the [RealSense camera](https://www.intelrealsense.com/depth-camera-d435i/). Execute the [capture_image.py](https://github.com/hello-robot/stretch_tutorials/blob/main/src/capture_image.py) node to save a .jpeg image of the image topic */camera/color/image_raw_upright_view*.
  42. ```bash
  43. # Terminal 4
  44. cd ~/catkin_ws/src/stretch_tutorials/src
  45. python capture_image.py
  46. ```
  47. An image named **camera_image.jpeg** is saved in the **stored_data** folder in this package.
  48. ### The Code
  49. ```python
  50. #!/usr/bin/env python
  51. import rospy
  52. import sys
  53. import os
  54. import cv2
  55. from sensor_msgs.msg import Image
  56. from cv_bridge import CvBridge, CvBridgeError
  57. class CaptureImage:
  58. """
  59. A class that converts a subscribed ROS image to a OpenCV image and saves
  60. the captured image to a predefined directory.
  61. """
  62. def __init__(self):
  63. """
  64. A function that initializes a CvBridge class, subscriber, and save path.
  65. :param self: The self reference.
  66. """
  67. self.bridge = CvBridge()
  68. self.sub = rospy.Subscriber('/camera/color/image_raw', Image, self.callback, queue_size=1)
  69. self.save_path = '/home/hello-robot/catkin_ws/src/stretch_tutorials/stored_data'
  70. def callback(self, msg):
  71. """
  72. A callback function that converts the ROS image to a CV2 image and stores the
  73. image.
  74. :param self: The self reference.
  75. :param msg: The ROS image message type.
  76. """
  77. try:
  78. image = self.bridge.imgmsg_to_cv2(msg, 'bgr8')
  79. except CvBridgeError, e:
  80. rospy.logwarn('CV Bridge error: {0}'.format(e))
  81. file_name = 'camera_image.jpeg'
  82. completeName = os.path.join(self.save_path, file_name)
  83. cv2.imwrite(completeName, image)
  84. rospy.signal_shutdown("done")
  85. sys.exit(0)
  86. if __name__ == '__main__':
  87. rospy.init_node('capture_image', argv=sys.argv)
  88. CaptureImage()
  89. rospy.spin()
  90. ```
  91. ### The Code Explained
  92. Now let's break the code down.
  93. ```python
  94. #!/usr/bin/env python
  95. ```
  96. Every Python ROS [Node](http://wiki.ros.org/Nodes) will have this declaration at the top. The first line makes sure your script is executed as a Python script.
  97. ```python
  98. import rospy
  99. import sys
  100. import os
  101. import cv2
  102. ```
  103. You need to import `rospy` if you are writing a ROS [Node](http://wiki.ros.org/Nodes). There are functions from sys, os, and cv2 that are required within this code. cv2 is a library of Python functions that implements computer vision algorithms. Further information about cv2 can be found here: [OpenCV Python](https://www.geeksforgeeks.org/opencv-python-tutorial/).
  104. ```python
  105. from sensor_msgs.msg import Image
  106. from cv_bridge import CvBridge, CvBridgeError
  107. ```
  108. The `sensor_msgs.msg` is imported so that we can subscribe to ROS `Image` messages. Import [CvBridge](http://wiki.ros.org/cv_bridge) to convert between ROS `Image` messages and OpenCV images.
  109. ```python
  110. def __init__(self):
  111. """
  112. A function that initializes a CvBridge class, subscriber, and save path.
  113. :param self: The self reference.
  114. """
  115. self.bridge = CvBridge()
  116. self.sub = rospy.Subscriber('/camera/color/image_raw', Image, self.callback, queue_size=1)
  117. self.save_path = '/home/hello-robot/catkin_ws/src/stretch_tutorials/stored_data'
  118. ```
  119. Initialize the CvBridge class, the subscriber, and the directory of where the captured image will be stored.
  120. ```python
  121. def callback(self, msg):
  122. """
  123. A callback function that converts the ROS image to a cv2 image and stores the
  124. image.
  125. :param self: The self reference.
  126. :param msg: The ROS image message type.
  127. """
  128. try:
  129. image = self.bridge.imgmsg_to_cv2(msg, 'bgr8')
  130. except CvBridgeError as e:
  131. rospy.logwarn('CV Bridge error: {0}'.format(e))
  132. ```
  133. Try to convert the ROS Image message to a cv2 Image message using the `imgmsg_to_cv2()` function.
  134. ```python
  135. file_name = 'camera_image.jpeg'
  136. completeName = os.path.join(self.save_path, file_name)
  137. cv2.imwrite(completeName, image)
  138. ```
  139. Join the directory and file name using the `path.join()` function. Then use the `imwrite()` function to save the image.
  140. ```python
  141. rospy.signal_shutdown("done")
  142. sys.exit(0)
  143. ```
  144. The first line of code initiates a clean shutdown of ROS. The second line of code exits the Python interpreter.
  145. ```python
  146. rospy.init_node('capture_image', argv=sys.argv)
  147. CaptureImage()
  148. ```
  149. The next line, `rospy.init_node(NAME, ...)`, is very important as it tells rospy the name of your node -- until rospy has this information, it cannot start communicating with the ROS Master. **NOTE:** the name must be a base name, i.e. it cannot contain any slashes "/".
  150. Instantiate the `CaptureImage()` class.
  151. ```python
  152. rospy.spin()
  153. ```
  154. Give control to ROS. This will allow the callback to be called whenever new messages come in. If we don't put this line in, then the node will not work, and ROS will not process any messages.
  155. ## Edge Detection
  156. In this section, we highlight a node that utilizes the [Canny Edge filter](https://www.geeksforgeeks.org/python-opencv-canny-function/) algorithm to detect the edges from an image and convert it back as a ROS image to be visualized in RViz. Begin by running the following commands.
  157. ```bash
  158. # Terminal 4
  159. cd ~/catkin_ws/src/stretch_tutorials/src
  160. python edge_detection.py
  161. ```
  162. The node will publish a new Image topic named */image_edge_detection*. This can be visualized in RViz and a gif is provided below for reference.
  163. <p align="center">
  164. <img src="https://raw.githubusercontent.com/hello-robot/stretch_tutorials/main/images/camera_image_edge_detection.gif"/>
  165. </p>
  166. ### The Code
  167. ```python
  168. #!/usr/bin/env python
  169. import rospy
  170. import sys
  171. import os
  172. import cv2
  173. from sensor_msgs.msg import Image
  174. from cv_bridge import CvBridge, CvBridgeError
  175. class EdgeDetection:
  176. """
  177. A class that converts a subscribed ROS image to a OpenCV image and saves
  178. the captured image to a predefined directory.
  179. """
  180. def __init__(self):
  181. """
  182. A function that initializes a CvBridge class, subscriber, and other
  183. parameter values.
  184. :param self: The self reference.
  185. """
  186. self.bridge = CvBridge()
  187. self.sub = rospy.Subscriber('/camera/color/image_raw', Image, self.callback, queue_size=1)
  188. self.pub = rospy.Publisher('/image_edge_detection', Image, queue_size=1)
  189. self.save_path = '/home/hello-robot/catkin_ws/src/stretch_tutorials/stored_data'
  190. self.lower_thres = 100
  191. self.upper_thres = 200
  192. rospy.loginfo("Publishing the CV2 Image. Use RViz to visualize.")
  193. def callback(self, msg):
  194. """
  195. A callback function that converts the ROS image to a CV2 image and goes
  196. through the Canny Edge filter in OpenCV for edge detection. Then publishes
  197. that filtered image to be visualized in RViz.
  198. :param self: The self reference.
  199. :param msg: The ROS image message type.
  200. """
  201. try:
  202. image = self.bridge.imgmsg_to_cv2(msg, 'bgr8')
  203. except CvBridgeError as e:
  204. rospy.logwarn('CV Bridge error: {0}'.format(e))
  205. image = cv2.Canny(image, self.lower_thres, self.upper_thres)
  206. image_msg = self.bridge.cv2_to_imgmsg(image, 'passthrough')
  207. image_msg.header = msg.header
  208. self.pub.publish(image_msg)
  209. if __name__ == '__main__':
  210. rospy.init_node('edge_detection', argv=sys.argv)
  211. EdgeDetection()
  212. rospy.spin()
  213. ```
  214. ### The Code Explained
  215. Since that there are similarities in the capture image node, we will only breakdown the different components of the edge detection node.
  216. ```python
  217. self.lower_thres = 100
  218. self.upper_thres = 200
  219. ```
  220. Define lower and upper bounds of the Hysteresis Thresholds.
  221. ```python
  222. image = cv2.Canny(image, self.lower_thres, self.upper_thres)
  223. ```
  224. Run the Canny Edge function to detect edges from the cv2 image.
  225. ```python
  226. image_msg = self.bridge.cv2_to_imgmsg(image, 'passthrough')
  227. ```
  228. Convert the cv2 image back to a ROS image so it can be published.
  229. ```python
  230. image_msg.header = msg.header
  231. self.pub.publish(image_msg)
  232. ```
  233. Publish the ROS image with the same header as the subscribed ROS message.