Skip to content

Commit b736046

Browse files
committed
feat: support compressed imgs in ros2->b64 conversion
1 parent 49a56bb commit b736046

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/rai_core/rai/communication/ros2/api/conversion.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,20 +92,28 @@ def convert_ros_img_to_cv2mat(msg: sensor_msgs.msg.Image) -> cv2.typing.MatLike:
9292
return cv_image
9393

9494

95-
def convert_ros_img_to_base64(msg: sensor_msgs.msg.Image) -> str:
95+
def convert_ros_img_to_base64(
96+
msg: sensor_msgs.msg.Image | sensor_msgs.msg.CompressedImage,
97+
) -> str:
9698
bridge = CvBridge()
97-
cv_image = cast(cv2.Mat, bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")) # type: ignore
99+
msg_type = type(msg)
100+
if msg_type == sensor_msgs.msg.Image:
101+
cv_image = bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")
102+
elif msg_type == sensor_msgs.msg.CompressedImage:
103+
cv_image = bridge.compressed_imgmsg_to_cv2(msg, desired_encoding="passthrough")
104+
else:
105+
raise ValueError(f"Unsupported message type: {msg_type}")
106+
98107
if cv_image.shape[-1] == 4:
99108
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGRA2RGB)
100109
return base64.b64encode(bytes(cv2.imencode(".png", cv_image)[1])).decode(
101110
"utf-8"
102111
)
103112
elif cv_image.shape[-1] == 1:
104-
cv_image = cv2.cvtColor(cv_image, cv2.GRAY2RGB)
113+
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_GRAY2RGB)
105114
return base64.b64encode(bytes(cv2.imencode(".png", cv_image)[1])).decode(
106115
"utf-8"
107116
)
108-
109117
else:
110118
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
111119
image_data = cv2.imencode(".png", cv_image)[1].tostring() # type: ignore

0 commit comments

Comments
 (0)