欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > 读取日志并动态显示障碍物的轮廓点以及时间戳

读取日志并动态显示障碍物的轮廓点以及时间戳

2025/12/7 23:41:37 来源:https://blog.csdn.net/CCCrunner/article/details/140909638  浏览:    关键词:读取日志并动态显示障碍物的轮廓点以及时间戳
import re
from collections import defaultdict
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime# 文件路径
log_file_path = '/home/sany/Documents/xwechat_files/wxid_f0rg2f76s76t22_0b3d/msg/file/2024-08/2024-07-28,22:32:22_syzk-lidar.log'
# 设置时间范围
start_time = datetime.strptime('2024-07-28,22:36:43.000', '%Y-%m-%d,%H:%M:%S.%f')
end_time = datetime.strptime('2024-07-28,22:37:22.882', '%Y-%m-%d,%H:%M:%S.%f')# 正则表达式提取障碍物中心点和轮廓点数据
center_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-(back )?obj center_x ([\d.-]+) center_y ([\d.-]+) center z:[\d.-]+')
obj_size_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-(back )?obj size (\d+) cur idx (\d+)')
obstacle_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-obj_num:(\d+) x:([\d.-]+) y:([\d.-]+),')def extract_frame_data(log_file_path):frames = []obstacles = defaultdict(lambda: {'center': None, 'contours': [], 'cur_idx': None, 'back': False})try:with open(log_file_path, 'r') as file:for line in file:# 提取中心点center_match = center_pattern.search(line)if center_match:timestamp, back_flag, center_x, center_y = center_match.groups()center_x, center_y = float(center_x), float(center_y)if timestamp not in obstacles:obstacles[timestamp] = {'center': None, 'contours': [], 'cur_idx': None, 'back': 'back' in (back_flag or '')}obstacles[timestamp]['center'] = {'x': center_x, 'y': center_y}# 提取 obj size 和 cur idxsize_match = obj_size_pattern.search(line)if size_match:timestamp, back_flag, obj_size, cur_idx = size_match.groups()cur_idx = int(cur_idx)if timestamp not in obstacles:obstacles[timestamp] = {'center': None, 'contours': [], 'cur_idx': None, 'back': 'back' in (back_flag or '')}obstacles[timestamp]['obj_size'] = int(obj_size)obstacles[timestamp]['cur_idx'] = cur_idx# 提取轮廓点obstacle_match = obstacle_pattern.search(line)if obstacle_match:timestamp, obj_num, x, y = obstacle_match.groups()x, y = float(x), float(y)if timestamp not in obstacles:obstacles[timestamp] = {'center': None, 'contours': [], 'cur_idx': None, 'back': False}obstacles[timestamp]['contours'].append({'obj_num': int(obj_num), 'x': x, 'y': y})except FileNotFoundError:print(f"Error: The file {log_file_path} was not found.")except IOError:print(f"Error: An IOError occurred while reading the file {log_file_path}.")except ValueError as e:print(f"Error: ValueError occurred - {e}")# 整理数据for timestamp, data in obstacles.items():frame = {'timestamp': timestamp,'obstacles': []}if data['cur_idx'] is not None:frame['obstacles'].append({'No': data['cur_idx'],'center': data['center'],'contour_points_num': len(data['contours']),'contours': data['contours'],'back': data['back']})frames.append(frame)return frames# 获取障碍物数据并输出结果
frames = extract_frame_data(log_file_path)def process_frame_data(frames):processed_frames = []for frame in frames:processed_frame = {'timestamp': frame['timestamp'], 'obstacles': []}for obstacle in frame['obstacles']:contours = obstacle['contours']grouped_contours = []current_obj_num = Nonecurrent_contours = []for contour in contours:if contour['obj_num'] != current_obj_num:if current_contours:grouped_contours.append(current_contours)current_obj_num = contour['obj_num']current_contours = []current_contours.append(contour)if current_contours:grouped_contours.append(current_contours)processed_obstacle = {'No': obstacle['No'],'center': obstacle['center'],'contour_points_num': obstacle['contour_points_num'],'contours': grouped_contours,'back': obstacle['back']}processed_frame['obstacles'].append(processed_obstacle)processed_frames.append(processed_frame)return processed_framesdef update_plot(frame_data, ax):ax.clear()timestamp = frame_data['timestamp']for obstacle in frame_data['obstacles']:if obstacle['center']:ax.plot(obstacle['center']['x'], obstacle['center']['y'], 'ko')  # 画中心点for contour_group in obstacle['contours']:x = [c['x'] for c in contour_group] + [contour_group[0]['x']]  # 闭合轮廓y = [c['y'] for c in contour_group] + [contour_group[0]['y']]color = 'blue' if not obstacle['back'] else 'red'ax.plot(x, y, color=color, marker='o', linestyle='-', label='Front' if not obstacle['back'] else 'Back')ax.set_title(f'Timestamp: {timestamp}')ax.set_xlim(-20, 20)ax.set_ylim(-20, 60)def animate(i, data, ax):frame_data = data[i]update_plot(frame_data, ax)# 处理数据
processed_frames = process_frame_data(frames)# 筛选在时间范围内的帧数据
filtered_data = [frame for frame in processed_frames if start_time <= datetime.strptime(frame['timestamp'], '%Y-%m-%d,%H:%M:%S.%f') <= end_time]# 创建动画
fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, animate, frames=len(filtered_data), fargs=(filtered_data, ax), interval=500)plt.show()

读取数据格式如下

[Info]-[PointCloudHandle:48]:[2024-07-28,22:32:22.849]-front obj size 1
[Info]-[PointCloudHandle:51]:[2024-07-28,22:32:22.849]-obj size 1 cur idx 1
[Info]-[PointCloudHandle:53]:[2024-07-28,22:32:22.849]-obj center_x 8.769928 center_y 29.048122 center z:3.330284
[Info]-[PointCloudHandle:58]:[2024-07-28,22:32:22.849]-obj_num:4 x:8.19 y:28.77,
[Info]-[PointCloudHandle:58]:[2024-07-28,22:32:22.849]-obj_num:4 x:8.19 y:29.22,
[Info]-[PointCloudHandle:58]:[2024-07-28,22:32:22.849]-obj_num:4 x:9.33 y:29.22,
[Info]-[PointCloudHandle:58]:[2024-07-28,22:32:22.849]-obj_num:4 x:9.33 y:28.77,
[Info]-[PointCloudHandle:88]:[2024-07-28,22:32:22.882]-back obj size 1
[Info]-[PointCloudHandle:92]:[2024-07-28,22:32:22.882]-back obj size 1 cur idx 1
[Info]-[PointCloudHandle:93]:[2024-07-28,22:32:22.882]-back obj center_x -18.513947 center_y -4.861476 center z:1.304405
[Info]-[PointCloudHandle:98]:[2024-07-28,22:32:22.882]-obj_num:4 x:-19.07 y:-11.12,
[Info]-[PointCloudHandle:98]:[2024-07-28,22:32:22.882]-obj_num:4 x:-19.10 y:-0.91,
[Info]-[PointCloudHandle:98]:[2024-07-28,22:32:22.882]-obj_num:4 x:-17.92 y:-5.83,
[Info]-[PointCloudHandle:98]:[2024-07-28,22:32:22.882]-obj_num:4 x:-18.87 y:-9.13,

在这里插入图片描述

import re
import matplotlib.pyplot as plt# 假设日志文件名为 'log_file.txt'
log_file = '2024-07-28,22:32:22_syzk-lidar.log'# 正则表达式提取障碍物中心点和轮廓点数据
center_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-obj center_x ([\d.-]+) center_y ([\d.-]+) center z:[\d.-]+')
obj_size_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-obj size (\d+) cur idx (\d+)')
obstacle_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-obj_num:(\d+) x:([\d.-]+) y:([\d.-]+),')
obj_start_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-front obj size (\d+)');
obj_end_pattern = re.compile(r'\[Info\]-\[run:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-\[Lidar Front Cost Time (\d+)');# 读取并处理日志文件
log_entries = []  # 存储按时间戳分组的日志条目def parse_log(lines):"""解析日志文件内容,提取障碍物中心点和轮廓点数据。:param lines: 日志文件的每一行,以列表形式提供。:return: 包含障碍物数据的列表。"""obstacles = []current_obstacle = Nonefor line in lines:if 'cur idx' in line:if current_obstacle:obstacles.append(current_obstacle)current_obstacle = {'center': None, 'points': []}elif 'back obj center_x' in line:match = re.search(r'center_x (\S+) center_y (\S+)', line)if match:center_x, center_y = float(match.group(1)), float(match.group(2))current_obstacle['center'] = (center_x, center_y)elif 'obj_num' in line:match = re.search(r'x:(\S+) y:(\S+)', line)if match:point_x, point_y = match.group(1).replace(',', ''), match.group(2).replace(',', '')point_x, point_y = float(point_x), float(point_y)current_obstacle['points'].append((point_x, point_y))if current_obstacle:obstacles.append(current_obstacle)return obstaclesdef visualize_obstacles(obstacles):"""可视化障碍物。:param obstacles: 包含障碍物数据的列表。"""plt.figure(figsize=(10, 10))for obs in obstacles:# center = obs['center']points = obs['points']# 绘制中心点# plt.scatter(center[0], center[1], color='red', s=100)# 绘制轮廓点points_x = [p[0] for p in points]points_y = [p[1] for p in points]plt.scatter(points_x, points_y, color='blue', s=50)# 绘制轮廓线points_x.append(points_x[0])  # 闭合轮廓points_y.append(points_y[0])  # 闭合轮廓plt.plot(points_x, points_y, color='green', linewidth=2)plt.xlabel('X')plt.ylabel('Y')plt.legend()plt.title('Obstacles Visualization')plt.grid(True)plt.show()with open(log_file, 'r') as file:current_lines = []start_record = Falsefor line in file:front_obj_match = obj_start_pattern.search(line)if front_obj_match:start_record = Truetimestamp = front_obj_match.group(1)# 可以在这里初始化一个字典来存储当前时间戳的数据current_data = {'timestamp': timestamp, 'lines': []}current_lines.append(current_data)if start_record:current_lines[-1]['lines'].append(line.strip())  # 存储当前时间戳的行end_front_log = obj_end_pattern.search(line)if end_front_log and start_record:# 添加当前记录到总列表,并重置当前记录log_entries.append(current_lines)current_lines = []start_record = False# 打印按时间戳分组的日志条目
for entry_group in log_entries:for data in entry_group:print(f"Timestamp: {data['timestamp']}")obstacles = parse_log(data['lines'])print(obstacles)visualize_obstacles(obstacles)# for line in data['lines']:#     print(f"  {line}")

显示障碍物坐标版本

import re
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime# 假设日志文件名为 'log_file.txt'
log_file = '2024-07-28,22:32:22_syzk-lidar.log'# 正则表达式提取障碍物中心点和轮廓点数据
center_pattern = re.compile(r'obj center_x ([\d.-]+) center_y ([\d.-]+)')
obj_size_pattern = re.compile(r'obj size (\d+) cur idx (\d+)')
obstacle_pattern = re.compile(r'obj_num:(\d+) x:([\d.-]+) y:([\d.-]+)')
obj_start_pattern = re.compile(r'\[Info\]-\[PointCloudHandle:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-front obj size (\d+)')
obj_end_pattern = re.compile(r'\[Info\]-\[run:\d+\]:\[(\d{4}-\d{2}-\d{2},\d{2}:\d{2}:\d{2}\.\d+)\]-\[Lidar Front Cost Time (\d+)')# 时间范围设置(只有在 use_time_filter 为 True 时才会生效)
use_time_filter = True
start_time_str = '2024-07-28,22:32:22.000' 
end_time_str = '2024-07-28,23:00:00.000'# 将时间字符串转换为 datetime 对象
start_time = datetime.strptime(start_time_str, '%Y-%m-%d,%H:%M:%S.%f')
end_time = datetime.strptime(end_time_str, '%Y-%m-%d,%H:%M:%S.%f')# 读取并处理日志文件
log_entries = []  # 存储按时间戳分组的日志条目def parse_log(lines):"""解析日志文件内容,提取障碍物中心点和轮廓点数据。:param lines: 日志文件的每一行,以列表形式提供。:return: 包含障碍物数据的列表。"""obstacles = []current_obstacle = Nonefor line in lines:if 'cur idx' in line:if current_obstacle:obstacles.append(current_obstacle)current_obstacle = {'center': None, 'points': []}elif 'center_x' in line:match = center_pattern.search(line)if match:center_x, center_y = float(match.group(1)), float(match.group(2))current_obstacle['center'] = (center_x, center_y)elif 'obj_num' in line:match = obstacle_pattern.search(line)if match:point_x, point_y = match.group(2).replace(',', ''), match.group(3).replace(',', '')point_x, point_y = float(point_x), float(point_y)current_obstacle['points'].append((point_x, point_y))if current_obstacle:obstacles.append(current_obstacle)return obstaclesdef visualize_obstacles(obstacles, ax):"""可视化障碍物。:param obstacles: 包含障碍物数据的列表。:param ax: Matplotlib Axes 对象。"""for obs in obstacles:points = obs['points']center = obs['center']# 绘制中心点if center:ax.scatter(center[0], center[1], color='red', s=100, label='Center')ax.text(center[0], center[1], f'({center[0]}, {center[1]})', fontsize=8, color='red')# 绘制轮廓点points_x = [p[0] for p in points]points_y = [p[1] for p in points]ax.scatter(points_x, points_y, color='blue', s=50, label='Outline Points')# 绘制轮廓线points_x.append(points_x[0])  # 闭合轮廓points_y.append(points_y[0])  # 闭合轮廓for i in range(len(points_x) - 1):if points_y[i] < 0:ax.plot(points_x[i:i+2], points_y[i:i+2], color='yellow', linewidth=2)  # 黄色轮廓线else:ax.plot(points_x[i:i+2], points_y[i:i+2], color='green', linewidth=2)  # 绿色轮廓线ax.set_xlim(-35, 35)ax.set_ylim(-20, 80)ax.set_xlabel('X')ax.set_ylabel('Y')ax.grid(True)handles, labels = ax.get_legend_handles_labels()by_label = dict(zip(labels, handles))ax.legend(by_label.values(), by_label.keys())with open(log_file, 'r') as file:current_lines = []start_record = Falsefor line in file:front_obj_match = obj_start_pattern.search(line)if front_obj_match:timestamp_str = front_obj_match.group(1)timestamp = datetime.strptime(timestamp_str, '%Y-%m-%d,%H:%M:%S.%f')if not use_time_filter or (start_time <= timestamp <= end_time):start_record = Truecurrent_data = {'timestamp': timestamp_str, 'lines': []}current_lines.append(current_data)else:start_record = Falseif start_record:current_lines[-1]['lines'].append(line.strip())  # 存储当前时间戳的行end_front_log = obj_end_pattern.search(line)if end_front_log and start_record:timestamp_str = end_front_log.group(1)timestamp = datetime.strptime(timestamp_str, '%Y-%m-%d,%H:%M:%S.%f')if not use_time_filter or (start_time <= timestamp <= end_time):log_entries.append(current_lines)current_lines = []start_record = False# 创建动画
fig, ax = plt.subplots(figsize=(10, 10))def update(frame):ax.clear()timestamp = log_entries[frame][0]['timestamp']ax.set_title(f'Time: {timestamp}')obstacles = parse_log(log_entries[frame][0]['lines'])visualize_obstacles(obstacles, ax)ani = animation.FuncAnimation(fig, update, frames=len(log_entries), repeat=False, interval=350)
plt.show()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词