-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhardcoded_bridge.py
More file actions
30 lines (27 loc) · 1.38 KB
/
hardcoded_bridge.py
File metadata and controls
30 lines (27 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3.9
import sys
import numpy as np
import rospy
from sensor_msgs.msg import Image
def imgmsg_to_cv2(img_msg):
if img_msg.encoding != "rgb8":
rospy.logerr("This Coral detect node has been hardcoded to the 'rgb8' encoding. Come change the code if you're actually trying to implement a new camera")
dtype = np.dtype("uint8") # Hardcode to 8 bits...
dtype = dtype.newbyteorder('>' if img_msg.is_bigendian else '<')
image_opencv = np.ndarray(shape=(img_msg.height, img_msg.width, 3), # and three channels of data. Since OpenCV works with bgr natively, we don't need to reorder the channels.
dtype=dtype, buffer=img_msg.data)
image_opencv = np.array([image_opencv[:,:,2], image_opencv[:,:,1], image_opencv[:,:,0]])
image_opencv = np.moveaxis(image_opencv, 0, -1)
# If the byt order is different between the message and the system.
if img_msg.is_bigendian == (sys.byteorder == 'little'):
image_opencv = image_opencv.byteswap().newbyteorder()
return image_opencv
def cv2_to_imgmsg(cv_image):
img_msg = Image()
img_msg.height = cv_image.shape[0]
img_msg.width = cv_image.shape[1]
img_msg.encoding = "rgb8"
img_msg.is_bigendian = 0
img_msg.data = cv_image.tostring()
img_msg.step = len(img_msg.data) // img_msg.height # That double line is actually integer division, not a comment
return img_msg