引言
本文主要以做座標點爲例。
我們知道python對數據的處理主要是以numpy的形式
一般三維空間座標的矩陣在python中爲
[[x1, y1, z1],
[x2, y2, z2],
...
...
...
[xn, yn, zn]]
然後可以通過工具包繪製三維散點圖,如下
總歸python只是一個數據處理工具,npy格式的數據並不能被專門的3D處理軟件讀取。因此我們需要將點雲數據寫入3D文件中,本文將介紹其中一種——ply
一、ply格式模型介紹
文件說明,有助於數據提取時的理解。這一部分借鑑3D基本知識PLY格式
參考:PLY格式介紹與讀取
PLY是一種電腦檔案格式,全名爲多邊形檔案(Polygon File Format)或 斯坦福三角形檔案(Stanford Triangle
Format)。格式組成:
頭:聲明數據格式,規定和點和麪片的數據內容
點:點的數據內容(座標x,y,z 顏色r,g,b等)
線:線的數據內容(組成線的點序號索引,顏色等)
面片:面片的數據內容(組成面的點序號索引,顏色等)
舉例:
ply
format ascii 1.0
//數據保存格式,三類
//format ascii 1.0
//format binary_little_endian 1.0
//format binary_big_endian 1.0
element vertex 8 //元素:頂點 個數爲8
property float x
property float y
property float z //頂點格式:依次爲x,yz座標
element edge 6 //元素:邊 6條
property int vertex1
property int vertex2
property uchar red
property uchar green
property uchar blue //邊存儲格式爲: 頂點id 1,2,顏色r,g,b
end_header //頭,以end_header結束
0.194585 0.0202505 -0.654565
0.393574 0.0181872 -0.634588
0.196413 0.220227 -0.652125
0.174584 0.0180056 -0.455581
0.811062 -0.0294865 -0.551833
0.991697 -0.0650619 -0.473697
0.845413 0.167279 -0.541659
0.73238 -0.0252545 -0.368009 //點內容,8個頂點(x,y,z)座標
0 1 255 0 0
0 2 0 255 0
0 3 0 0 255
4 5 255 0 0
4 6 0 255 0
4 7 0 0 255 //6條邊,(id1,id2,r,g,b)
二、代碼
import numpy as np
# Function to create point cloud file
def create_output(vertices, colors, filename):
colors = colors.reshape(-1, 3)
vertices = np.hstack([vertices.reshape(-1, 3), colors])
np.savetxt(filename, vertices, fmt='%f %f %f %d %d %d') # 必須先寫入,然後利用write()在頭部插入ply header
ply_header = '''ply
format ascii 1.0
element vertex %(vert_num)d
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
end_header
\n
'''
with open(filename, 'r+') as f:
old = f.read()
f.seek(0)
f.write(ply_header % dict(vert_num=len(vertices)))
f.write(old)
if __name__ == '__main__':
# Define name for output file
output_file = 'Andre_Agassi_0015.ply'
a = np.load("Andre_Agassi_0015.npy")
b = np.float32(a)
# 43867是我的點雲的數量,用的時候記得改成自己的
one = np.ones((43867,3))
one = np.float32(one)*255
# points_3D = np.array([[1,2,3],[3,4,5]]) # 得到的3D點(x,y,z),即2個空間點
# colors = np.array([[0, 255, 255], [0, 255, 255]]) #給每個點添加rgb
# Generate point cloud
print("\n Creating the output file... \n")
# create_output(points_3D, colors, output_file)
create_output(b, one, output_file)
最終三維座標就保存在ply中了
代碼中的color是每個座標點對應的紋理色彩,可自行設置
用meshlab打開我們生成的ply的效果如下: