需要在anaconda 環(huán)境下進行安裝,推薦使用。
創(chuàng)新互聯(lián)建站是一家集網(wǎng)站建設,玉州企業(yè)網(wǎng)站建設,玉州品牌網(wǎng)站建設,網(wǎng)站定制,玉州網(wǎng)站建設報價,網(wǎng)絡營銷,網(wǎng)絡優(yōu)化,玉州網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
進入anaconda環(huán)境下,運行如下命令,可能會報超時錯誤,跟你網(wǎng)絡有關系。需要你修改hosts來訪問github。
pip install --extra-index-url https://rospypi.github.io/simple/ rosbag
pip install roslz4 --extra-index-url https://rospypi.github.io/simple/
安裝成功后,測試
cv_bridge下載(源代碼https://github.com/ros-perception/vision_opencv):https://codeload.github.com/ros-perception/vision_opencv/zip/refs/heads/noetic
下載完成后cd至cv_bridge文件夾,然后cmd打開命令行窗口:
python setup.py install
安裝成功后測試
whl包
https://files.cnblogs.com/files/yunhgu/rosbag_cv_bridge.zip
這個比較簡單直接使用pip就可以了
pip install sensor_msgs --extra-index-url https://rospypi.github.io/simple/
實際使用過程中遇到了一個問題,在解析圖片信息的時候
from cv_bridge.boost.cv_bridge_boost import cvtColor2
上面這個導入報了錯
No module named 'cv_bridge.boost'
解決方法:
下載這個
https://github.com/rospypi/simple/raw/any/cv-bridge/cv_bridge-1.13.0.post0-py2.py3-none-any.whl
然后進入anconda界面
pip install cv_bridge-1.13.0.post0-py2.py3-none-any.whl
從信息得出可能是版本的問題。
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: parse_bag
# Author: yunhgu
# Date: 2022/1/10 11:01
# Description:
# -------------------------------------------------------------------------------
import copy
import struct
from pathlib import Path
from traceback import format_exc
import cv2
import numpy as np
import rosbag
import sensor_msgs.point_cloud2 as pc2
from cv_bridge import CvBridge
PCD_ASCII_TEMPLATE = """VERSION 0.7
FIELDS x y z intensity
SIZE 4 4 4 2
TYPE F F F U
COUNT 1 1 1 1
WIDTH {}
HEIGHT 1
VIEWPOINT 0 0 0 1 0 0 0
POINTS {}
DATA ascii
"""
PCD_BINARY_TEMPLATE = """VERSION 0.7
FIELDS x y z intensity
SIZE 4 4 4 4
TYPE F F F F
COUNT 1 1 1 1
WIDTH {}
HEIGHT 1
VIEWPOINT 0 0 0 1 0 0 0
POINTS {}
DATA binary
"""
class BagExtractor:
def __init__(self, bag_folder, dst_folder):
self.bag_folder = Path(bag_folder)
self.dst_folder = Path(dst_folder)
self.bridge = CvBridge()
def extract_pcd_img(self, pcd_topic_list: list, img_topic_list: list):
"""
:param pcd_topic_list: 點云文件topic名字列表
:param img_topic_list: 圖片文件topic名字列表
:return:
"""
for bag_file in self.bag_folder.rglob("*.bag"):
output_file = self.dst_folder.joinpath(bag_file.relative_to(self.bag_folder))
output_folder = output_file.parent.joinpath(f"{output_file.stem}")
output_folder.mkdir(parents=True, exist_ok=True)
with rosbag.Bag(bag_file, 'r') as bag:
info = bag.get_type_and_topic_info()
print(info.topics)
pcd_number = self.get_pcd_img_number(info, pcd_topic_list)
img_number = self.get_pcd_img_number(info, img_topic_list)
print(f"解析{bag_file.name} pcd總數(shù):{pcd_number} 圖片總數(shù):{img_number}")
for topic, msg, t in bag.read_messages():
time_str = "%.9f" % msg.header.stamp.to_sec()
if topic in pcd_topic_list: # 點云的topic
pcd_path = output_folder.joinpath(f"{time_str}.pcd")
# self.to_pcd_ascii(pcd_path, msg)
self.to_pcd_binary(pcd_path, msg)
print(f"Extract pcd file {time_str}.pcd")
if topic in img_topic_list: # 圖片的topic
img_path = output_folder.joinpath(f"{time_str}.png")
self.to_img(img_path, msg)
print(f"Extract img file {time_str}.png")
@classmethod
def get_pcd_img_number(cls, info, topic_list):
try:
for topic in topic_list:
topic_ob = info.topics.get(topic, None)
if topic_ob:
return topic_ob.message_count
return 0
except Exception as e:
print(f"獲取pcd|img幀數(shù)出錯:{e}")
return 0
@classmethod
def to_pcd_ascii(cls, pcd_path, msg):
with open(pcd_path, 'w') as f:
points_data = np.array(list(pc2.read_points(msg)))
lidar = list(np.delete(points_data, np.where(np.isnan(points_data))[0], axis=0))
header = copy.deepcopy(PCD_ASCII_TEMPLATE).format(len(lidar), len(lidar))
f.write(header)
for pi in lidar:
f.write(' '.join([str(i) for i in pi]) + '\n')
@classmethod
def to_pcd_binary(cls, pcd_path, msg):
with open(pcd_path, 'wb') as f:
points_data = np.array(list(pc2.read_points(msg)))
lidar = list(np.delete(points_data, np.where(np.isnan(points_data))[0], axis=0))
header = copy.deepcopy(PCD_BINARY_TEMPLATE).format(len(lidar), len(lidar))
f.write(header.encode())
for pi in lidar:
h = struct.pack('ffff', pi[0], pi[1], pi[2], pi[3])
f.write(h)
def to_img(self, img_path, msg):
try:
# cv_image = self.bridge.compressed_imgmsg_to_cv2(msg)
cv_image = self.bridge.imgmsg_to_cv2(msg)
cv2.imencode('.png', cv_image)[1].tofile(str(img_path))
except Exception as e:
print(f"生成圖片失敗:{e}")
if __name__ == '__main__':
try:
bag_path = r'C:\Users\pc\Desktop\bag測試數(shù)據(jù)\data' # bag文件路徑
dst_path = r'C:\Users\pc\Desktop\bag測試數(shù)據(jù)\result' # 結果路徑
extractor = BagExtractor(bag_path, dst_path)
extractor.extract_pcd_img(pcd_topic_list=['/rslidar_points', '/zvision_lidar_points'],
img_topic_list=['/usb_cam/image_raw', '/zed2/zed_node/left/image_rect_color'])
except Exception as ee:
print(f"運行失敗,無法解決請連續(xù)開發(fā)人員!{format_exc()}{ee}")
https://rospypi.github.io/simple