使用MATLAB读取.ply点云图
filename = 'C:\\Users\\13163\\Desktop\\3D_PointCloud\\PointCloud_2\\3D点云生成\\Group_1\\outputMesh.ply';
[vertices, faces, color] = readPly(filename);
plotPly(vertices, faces, color);
function [vertices, faces, color] = readPly(filename)
% 打开文件
fid = fopen(filename, 'r');
if fid == -1
error('Cannot open PLY file.');
end
% 跳过头部信息,读取直到遇到顶点数据
line = fgets(fid);
while true
line = fgets(fid);
if contains(line, 'end_header')
break;
end
end
% 读取顶点数量
line = fgets(fid);
tokens = strsplit(line);
numVertices = str2double(tokens{2});
% 读取面片数量(可选)
line = fgets(fid);
tokens = strsplit(line);
numFaces = str2double(tokens{2});
% 读取顶点数据
vertices = zeros(numVertices, 3);
color = zeros(numVertices, 3); % 如果 PLY 文件中包含颜色信息
for i = 1:numVertices
line = fgets(fid);
tokens = strsplit(strtrim(line));
vertices(i, :) = str2double(tokens(1:3));
if length(tokens) >= 6
color(i, :) = str2double(tokens(4:6)); % 如果文件有颜色信息
end
end
% 读取面片数据
faces = zeros(numFaces, 3);
for i = 1:numFaces
line = fgets(fid);
tokens = strsplit(strtrim(line));
faces(i, :) = str2double(tokens(2:end));
end
% 关闭文件
fclose(fid);
end
function plotPly(vertices, faces, color)
% 绘制点云
figure;
hold on;
scatter3(vertices(:, 1), vertices(:, 2), vertices(:, 3), 10, color, 'filled');
% 绘制面片
if ~isempty(faces)
trimesh(faces, vertices(:, 1), vertices(:, 2), vertices(:, 3), 'FaceColor', 'cyan', 'FaceAlpha', 0.3);
end
axis equal;
xlabel('X');
ylabel('Y');
zlabel('Z');
title('3D Point Cloud and Mesh');
grid on;
hold off;
end
报错
错误使用 fopen 找不到文件
filename = ‘“C:\Users\13163\Desktop\3D_PointCloud\PointCloud_2\3D点云生成\Group_1\outputMesh.ply”’; % 替换为你的 PLY 文件路径
[vertices, faces, color] = readPly(filename);
plotPly(vertices, faces, color);错误使用 fopen
找不到文件。确保文件存在且路径有效。
出错 untitled9>readPly (第 6 行)
fid = fopen(filename, ‘r’);
原因:Windows 路径分隔符是反斜杠 \,但在字符串中需要使用双反斜杠 \,或者使用正斜杠 /,因为 MATLAB 中反斜杠 \ 用作转义字符。
filename = 'C:\Users\13163\Desktop\3D_PointCloud\PointCloud_2\3D点云生成\Group_1\outputMesh.ply';
改成\即可。
filename = 'C:\\Users\\13163\\Desktop\\3D_PointCloud\\PointCloud_2\\3D点云生成\\Group_1\\outputMesh.ply';
无法运行,运行按钮变灰
第一次使用实时脚本,注意函数一定写在主函数后面,否则无法运行
读取ply文件
% 定义文件路径
filename = "C:\\Users\\13163\\Desktop\\3D_PointCloud\\PointCloud_2\\3D点云生成\\Group_1\\outputMesh.ply"; % 替换为你自己的文件路径
% 读取 PLY 点云文件
ptCloud = pcread(filename);
% 显示点云
pcshow(ptCloud);
title('3D Point Cloud Visualization');