Reputation: 1
I'm trying to build a mesh for a two-argument function (point data cloud) and save it as .ply file using Python.
Input: Million data points in 3D space (x,y,z) where z can be considered as a value of a math function z=f(x,y)
Desired output: .PLY file containing the mesh.
For the step 2 I have the following function:
def savePoly(filename, arrayOfXYZ):
xyz = np.array(arrayOfXYZ)
x_points = xyz[:, 0]
y_points = xyz[:, 1]
z_points = xyz[:, 2]
# Write header of .ply file
fid = open(filename, 'wb')
fid.write(bytes('ply\n', 'utf-8'))
fid.write(bytes('format binary_little_endian 1.0\n', 'utf-8'))
fid.write(bytes('element vertex %d\n' % x_points.shape[0], 'utf-8'))
fid.write(bytes('property float x\n', 'utf-8'))
fid.write(bytes('property float y\n', 'utf-8'))
fid.write(bytes('property float z\n', 'utf-8'))
fid.write(bytes('property uchar red\n', 'utf-8'))
fid.write(bytes('property uchar green\n', 'utf-8'))
fid.write(bytes('property uchar blue\n', 'utf-8'))
fid.write(bytes('end_header\n', 'utf-8'))
rgb_points = np.ones(x_points.shape).astype(np.uint8) * 255
# Write 3D points to .ply file
for i in range(x_points.shape[0]):
fid.write(bytearray(struct.pack("fffccc",
x_points[i],
y_points[i],
z_points[i],
rgb_points[i].tobytes(),
rgb_points[i].tobytes(),
rgb_points[i].tobytes()
)))
fid.close()
print(fid)
But that one only saves vertices, and no surface.
The following code saves triangles to .ply but I'm not sure what is tris how to build the triangles first:
"""
plyfun
@author:wronk
Write surface to a .ply (Stanford 3D mesh file) in a way that preserves
vertex order in the MNE sense. Extendable for colors or other vertex/face properties.
.ply format: https://en.wikipedia.org/wiki/PLY_(file_format)
"""
import mne
import numpy as np
from os import path as op
import os
from os import environ
def write_surf2ply(rr, tris, save_path):
out_file = open(save_path, 'w')
head_strs = ['ply\n', 'format ascii 1.0\n']
ele_1 = ['element vertex ' + str(len(rr)) + '\n',
'property float x\n',
'property float y\n',
'property float z\n']
ele_2 = ['element face ' + str(len(tris)) + '\n',
'property list uchar int vertex_index\n']
tail_strs = ['end_header\n']
# Write Header
out_file.writelines(head_strs)
out_file.writelines(ele_1)
out_file.writelines(ele_2)
out_file.writelines(tail_strs)
##############
# Write output
##############
# First, write vertex positions
for vert in rr:
out_file.write(str(vert[0]) + ' ')
out_file.write(str(vert[1]) + ' ')
out_file.write(str(vert[2]) + '\n')
# Second, write faces using vertex indices
for face in tris:
out_file.write(str(3) + ' ')
out_file.write(str(face[0]) + ' ')
out_file.write(str(face[1]) + ' ')
out_file.write(str(face[2]) + '\n')
out_file.close()
if __name__ == '__main__':
struct_dir = op.join(environ['SUBJECTS_DIR'])
subject = 'AKCLEE_139'
surf_fname = op.join(struct_dir, subject, 'surf', 'lh.pial')
save_path = op.join('/media/Toshiba/Blender/Brains', subject,
'lh.pial_reindex.ply')
rr, tris = mne.read_surface(surf_fname)
write_surf2ply(rr, tris, save_path)
For the step 1:
The following article generates mesh but (a) it is a general-purpose point data cloud, while z=f(x,y) is enough here, (b) it assumes there is an array of normals in the input: https://towardsdatascience.com/5-step-guide-to-generate-3d-meshes-from-point-clouds-with-python-36bad397d8ba which is still need to be built.
So in summary:
Is there a simple way to build a mesh using Python for a huge point cloud data, where z coordinate is a function of (x,y), and export this mesh to a .ply file?
Upvotes: 0
Views: 489
Reputation: 1
Solution:
import numpy as np
import scipy.spatial
import pandas as pd
df = pd.read_csv("data.csv")
print(df.columns)
x = df['column 0']
y = df['column 1']
z = df['column z values']
x0 = x[0]
y0 = y[0]
z0 = z[0]
pointslist = []
for i in range(len(x)):
xi = (x[i] - x0) / 100
yi = (y[i] - y0) / 4
zi = (z[i] - z0) / 8
pointslist.append([xi, yi, zi]) # array of triplets
xyz = np.array(pointslist)
# xyz = np.random.random((12, 3)) # arbitrary 3D data set
# xyz = np.array([[0, 0,1], [0, 1,1], [1, 0.5,0], [1, 0,0]]) # smaller data set for testing
# print(data)
mesh = scipy.spatial.Delaunay(xyz[:, :2]) # take the first two dimensions
# print(mesh.points)
# print(mesh.convex_hull)
# print(mesh.vertex_to_simplex)
#
# x = xyz[:, 0]
# y = xyz[:, 1]
# z = xyz[:, 2]
writeSurface2PLY(xyz, mesh.simplices, "output.ply")
def writeSurface2PLY(vertices, meshanglesAsVertexIndices, save_path):
out_file = open(save_path, 'w')
head_strs = ['ply\n', 'format ascii 1.0\n']
ele_1 = ['element vertex ' + str(len(vertices)) + '\n',
'property float x\n',
'property float y\n',
'property float z\n']
ele_2 = ['element face ' + str(len(meshanglesAsVertexIndices)) + '\n',
'property list uchar int vertex_index\n']
tail_strs = ['end_header\n']
# Write Header
out_file.writelines(head_strs)
out_file.writelines(ele_1)
out_file.writelines(ele_2)
out_file.writelines(tail_strs)
##############
# Write output
##############
# First, write vertex positions
for vert in vertices:
out_file.write(str(vert[0]) + ' ')
out_file.write(str(vert[1]) + ' ')
out_file.write(str(vert[2]) + '\n')
# Second, write faces using vertex indices
for face in meshanglesAsVertexIndices:
out_file.write(str(3) + ' ')
out_file.write(str(face[0]) + ' ')
out_file.write(str(face[1]) + ' ')
out_file.write(str(face[2]) + '\n')
out_file.close()
Upvotes: 0