需求
- 读取包含pcd文件的文件夹路径
- 依次显示pcd点云
代码
#! /usr/bin/env python
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: Open3dShowPcd
# Author: yunhgu
# Date: 2021/12/22 9:07
# Description:
# -------------------------------------------------------------------------------
from pathlib import Path
import numpy as np
import open3d as o3d
from traceback import format_exc
class PtVis:
def __init__(self, name='空格进入下一帧 Z退回上一帧', width=1024, height=768, pcd_files_path=""):
self.pcd_files_path = pcd_files_path
self.pcd_files_list = []
self.index = 0
self.pcd = None
self.vis = None
self.name = name
self.width = width
self.height = height
self.axis_pcd = o3d.geometry.TriangleMesh().create_coordinate_frame()
self.init_pcd_files_list()
def init_setting(self):
opt = self.vis.get_render_option()
# 设置背景颜色和点大小
opt.background_color = np.asarray([0, 0, 0])
opt.point_size = 2
def show_pcd(self):
# 绘制open3d坐标系
self.vis = o3d.visualization.VisualizerWithKeyCallback()
self.vis.create_window(window_name=f"{Path(self.pcd_files_list[0]).name} {self.name}", width=self.width,
height=self.height)
# 修改显示
self.init_setting()
# 初始化显示pcd第一帧
self.pcd = o3d.io.read_point_cloud(self.pcd_files_list[0])
self.vis.add_geometry(self.pcd)
self.vis.add_geometry(self.axis_pcd)
# 设置键盘响应事件
self.vis.register_key_callback(90, lambda temp: self.last())
self.vis.register_key_callback(32, lambda temp: self.next())
self.vis.run()
def next(self):
if 0 <= self.index < len(self.pcd_files_list) - 1:
self.index += 1
self.update(self.index)
def last(self):
if 0 < self.index <= len(self.pcd_files_list) - 1:
self.index -= 1
self.update(self.index)
def init_pcd_files_list(self):
for file in Path(self.pcd_files_path).rglob("*.pcd"):
self.pcd_files_list.append(str(file))
self.pcd_files_list = sorted(self.pcd_files_list, key=lambda p: Path(p).stem)
def update(self, index):
new_pcd_file = self.pcd_files_list[index]
self.vis.create_window(window_name=f"{Path(new_pcd_file).name} {self.name}", width=self.width,
height=self.height)
self.pcd = o3d.io.read_point_cloud(new_pcd_file)
self.vis.clear_geometries() # 清空vis点云
self.vis.add_geometry(self.pcd) # 增加vis中的点云
self.vis.add_geometry(self.axis_pcd)
self.vis.poll_events()
self.vis.update_renderer()
def close(self):
self.vis.destroy_window()
if __name__ == '__main__':
pt = None
try:
pcd_file_path = input("请输入要展示的pcd文件夹:").strip("\"")
# pcd_file_path = r"C:\Users\pc\Desktop\docker\output\result"
pt = PtVis(pcd_files_path=pcd_file_path)
print(f"{pcd_file_path}共有PCD个数:{len(pt.pcd_files_list)}")
pt.show_pcd()
except Exception as e:
print(f"运行出错请联系开发人员:{format_exc}{e}")
finally:
pt.close()
展示示例