在Threejs导入显示点云数据

本文介绍如何在Threejs项目中将PLY点云数据转换为JSON格式,并利用Points方法进行显示。通过C++和jsoncpp库将PLY文件转换,然后在Web端使用同步的Ajax调用JSON文件,最后在Threejs中呈现点云效果。

在Threejs导入并显示点云数据

最近在项目中遇到需求,需要在web端显示点云数据。将我的实现步骤介绍在这里供大家参考。我使用的是threejs开源库,最终实现

1. 数据格式

原本是点云数据是ply格式的。在threejs中有ply导入的loader,经过简略的阅读和学习。我只找到了它加载mesh文件的支持函数,对于点云没有找到相关的支持。于是我就考虑使用对html来说更容易读取的json格式存储和导入点云数据。

值得一提的是,json文件占用空间会更大,如果有时间我也希望可以使用一些二进制的存储方式,但是在这里只是为了实现,暂时不考虑太多效率方面的问题。

于是我使用C++,先将ply文件转写成json文件。

1.1 jsoncpp

C++上使用的是jsoncpp,但是cmakelist配置遇到了一点问题。最后综合了许多回答。加载了头文件之后,我自己在电脑中找到了静态库文件加载到了项目中。可能不是很优美,但是可以完美的运行和使用了。

find_package(PkgConfig REQUIRED)
pkg_check_modules(JSONCPP jsoncpp)

include_directories(
${JSONCPP_INCLUDE_DIRS}
)

target_link_libraries(example 
  /usr/local/lib/libjsoncpp.a
)

1.2 C++重写文件

我使用了下面的函数读取并重写了json文件。

void Ulocalization::LoadPlyAndSaveJson(const std::string& load_path, const std::string& save_path)
{
    std::cout << std::endl << "[TO JSON]  Load fused down sampled point cloud and save to . " << std::endl;
   
    std::vector<PlyPoint> plypointT = ReadPly(load_path);
    std::cout << "   There are " << plypointT.size() << " points." << std::endl;

    Json::Value root;
    Json::Value vertex;
    Json::Value color;
    constexpr bool shouldUseOldWay = false;
    root["descrition"] = "vertex and color, each is a 3 element vector";
    root["name"] = "spring square";
    root["size"] = plypointT.size();
    
    for(size_t i=0, iend=plypointT.size(); i<iend;i++)
    {
        float xpt = plypointT[i].x;
        float ypt = plypointT[i].y;
        float zpt = plypointT[i].z;
        int rcolor = plypointT[i].r;
        int gcolor = plypointT[i].g;
        int bcolor = plypointT[i].b;
        vertex.append(xpt);
        vertex.append(ypt);
        vertex.append(zpt);
        color.append(rcolor);
        color.append(gcolor);
        color.append(bcolor);
    }

    root["vertex"] = vertex;
    root["color"] = color;

    std::ofstream ofs;
    ofs.open(save_path);
    ofs << root.toStyledString();
    ofs.close();

    std::cout << "   Saved to " << save_path << std::endl << std::endl;
}

2. JSON的读取

在html中读取json我使用的是下面的这个库,在网上可以找到一些相关的使用方法。

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

它主要有两种调用方法,一个是通过 “.getJSON (jsonFile, function(data){…})” 。

var x,y,z,r,g,b;
var jsonFile = "../resources/fused_downsampled.json";
			
//var particlesX = new Array(200);
//var particles = new Array(200);
// see more https://blog.youkuaiyun.com/weixin_39823527/article/details/80392839
// we cannot use this mehtod, we need synchronous method, otherwise the json file will load fail.
//$.getJSON (jsonFile, function(data){
//	var index = 0;
    //	$.each(data.vertex, function(i,item){
    			//		if (i%3 == 0) x = parseInt(item*10);
			//		else if (i%3 == 1) y = parseInt(item*10);
			//		else if (i%3 == 2) {
			//			z = parseInt(item*10);
			//			var particle = new THREE.Vector3(x, y, z);
			//			particlesX[index] = x;
			//			particles[index] = particle;
			//			index = index + 1;
			//		}
			//		if(index > 199) return false;
  			//	});
			//	console.log("load done!");
			//});

但是上面的是异步的调用方式。为了方便我使用的是".ajax({…})"提供的同步调用。

$.ajax({
         type: "get",
         url: jsonFile,
         dataType: "json",
         async: false,
         success: function(data){
             var index = 0;
			 console.log("start load!");
             console.log("data point size :", data.size);
			 for(var i = 0; i < data.size; i++){
				  if (i%3 == 2) {
						x = -data.vertex[i-2]*10;
					    y = -data.vertex[i-1]*10;
						z = data.vertex[i]*10;
						r = data.color[i-2]/255;
						g = data.color[i-1]/255;
						b = data.color[i]/255;
						var particle = new THREE.Vector3(x, y, z);
						geometry.vertices.push(particle);
						geometry.colors.push(new THREE.Color(r,g,b));
					}
  				}
				console.log("load done!");	
                }
});

3. 使用threejs中的Points

threejs中提供了Points方法以加载和显示点云数据。我们使用它来显示点云。

var cloud;
cloud = new THREE.Points(geometry, material);
scene.add(cloud);

最终的效果如下所示,也可以访问网页最终实现。值得一提的是,我使用github来发布,但是github上有文件大小的限制(25m),json的文件又相对比较大,所以我对点云做了降采样处理,然后才成功完成。
在这里插入图片描述

### 如何在 Three.js 中处理点云数据 #### 创建点云的基础流程 在 Three.js 中,`THREE.Points` 类被用来表示点云。为了创建并渲染点云,通常需要以下几个核心组件:几何体 (`THREE.BufferGeometry`) 和材质 (`THREE.PointsMaterial`)。 以下是具体实现过程: 1. **定义几何体** 使用 `THREE.BufferGeometry` 来存储点的位置信息。可以通过设置顶点数组来指定每个点的空间位置[^3]。 2. **配置材质** 利用 `THREE.PointsMaterial` 定义点的外观特性,比如颜色、透明度以及尺寸衰减效果等[^2]。 3. **组合成点云对象** 将上述几何体与材质传递给 `THREE.Points` 实例化一个点云对象,并将其添加至场景中。 下面是一个完整的示例代码展示如何构建基本的点云结构: ```javascript // 导入必要的模块 (如果使用 ES6 模块方式) import * as THREE from 'three'; // 初始化场景、相机和渲染器 const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // 设置几何体 - 随机生成一些点作为点云的数据源 const geometry = new THREE.BufferGeometry(); const pointsArray = []; for (let i = 0; i < 1000; i++) { const x = Math.random() * 20 - 10; const y = Math.random() * 20 - 10; const z = Math.random() * 20 - 10; pointsArray.push(x, y, z); // 存储三维坐标 } const positions = new Float32Array(pointsArray); geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); // 设置材质 - 自定义点的颜色及其他属性 const material = new THREE.PointsMaterial({ color: 0xffffff, size: 0.1, transparent: true, opacity: 0.8, depthTest: false }); // 创建 Points 对象并将它加入到场景里 const pointCloud = new THREE.Points(geometry, material); scene.add(pointCloud); camera.position.z = 5; function animate() { requestAnimationFrame(animate); // 动态更新点云中的某些参数(可选) pointCloud.rotation.x += 0.01; pointCloud.rotation.y += 0.01; renderer.render(scene, camera); } animate(); ``` 此脚本展示了怎样通过随机分布的方式生成一组点形成简单的点云模型。此外还加入了旋转动画让视觉呈现更加生动有趣。 #### 进阶技巧 对于更复杂的点云应用场合可以考虑如下几点优化措施: - 调整视口大小响应窗口变化事件。 - 增加光照条件改善显示质量。 - 加载外部文件形式导入实际采集得到的真实世界扫描数据集代替手动模拟出来的简单形状。 ---
评论 6
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值