Python三維網(wǎng)格體素化實(shí)例
Python三維網(wǎng)格體素化
本文主要是實(shí)現(xiàn)將一個(gè)網(wǎng)格模型體素化,實(shí)現(xiàn)不同分辨率的體素化效果,并且可視化輸出為obj文件!
首先利用trimesh對mesh進(jìn)行采樣,然后根據(jù)采樣點(diǎn)得到各個(gè)體素點(diǎn)的占有值。
效果
通過調(diào)整分辨率以及采樣率(當(dāng)分辨率變高時(shí)建議適量提高采樣率)得到以下的效果!

代碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Matthieu Zins
"""
import trimesh
import numpy as np
import os
import argparse
"""
====== Voxelize the surface of a mesh ======
"""
def create_if_needed(folder):
if not os.path.isdir(folder):
os.mkdir(folder)
parser = argparse.ArgumentParser(description='Pass object name')
parser.add_argument('input_mesh', type=str)
parser.add_argument('--output_folder', type=str, default="")
parser.add_argument('--resolution', type=int, nargs=3, default=[50, 50, 50],
help="resolution_X resolution_Y resolution_Z")
parser.add_argument('--sampling', type=int, default="100000",
help="number of points sampled on the mesh")
args = parser.parse_args()
input_mesh_filename = args.input_mesh
object_name = os.path.splitext(os.path.basename(input_mesh_filename))[0]
output_folder = args.output_folder
if len(output_folder) == 0: output_folder = object_name
RES_X, RES_Y, RES_Z = args.resolution
sample_points_count = args.sampling
create_if_needed(output_folder)
mesh = trimesh.exchange.load.load(input_mesh_filename)
# Uniform Points Sampling
pts, _ = trimesh.sample.sample_surface_even(mesh, sample_points_count )
# Save sample points
sampled_points_mesh = trimesh.Trimesh(vertices=pts)
sampled_points_mesh.export(os.path.join(output_folder, object_name + "_resampled_points.ply"))
# Adjust the grid origin and voxels size
origin = pts.min(axis=0)
dimensions = pts.max(axis=0) - pts.min(axis=0)
scales = np.divide(dimensions, np.array([RES_X-1, RES_Y-1, RES_Z-1]))
scale = np.max(scales)
# Voxelize
pts -= origin
pts /= scale
pts_int = np.round(pts).astype(int)
grid = np.zeros((RES_X, RES_Y, RES_Z), dtype=int)
gooRES_X = np.where(np.logical_and(pts_int[:, 0] >= 0, pts_int[:, 0] < RES_X))[0]
gooRES_Y = np.where(np.logical_and(pts_int[:, 1] >= 0, pts_int[:, 1] < RES_Y))[0]
gooRES_Z = np.where(np.logical_and(pts_int[:, 2] >= 0, pts_int[:, 2] < RES_Z))[0]
goods = np.intersect1d(np.intersect1d(gooRES_X, gooRES_Y), gooRES_Z)
pts_int = pts_int[goods, :]
grid[pts_int[:, 0], pts_int[:, 1], pts_int[:, 2]] = 1
# Save voxels
voxel_pts = np.array([[-0.5, 0.5, -0.5],
[0.5, 0.5, -0.5],
[0.5, 0.5, 0.5],
[-0.5, 0.5, 0.5],
[-0.5, -0.5, -0.5],
[0.5, -0.5, -0.5],
[0.5, -0.5, 0.5],
[-0.5, -0.5, 0.5]])
voxel_faces = np.array([[0, 1, 2, 3],
[1, 5, 6, 2],
[5, 4, 7, 6],
[4, 0, 3, 7],
[0, 4, 5, 1],
[7, 3, 2, 6]])
def get_voxel(i, j, k):
global voxel_pts, voxel_faces
v = np.array([i, j, k], dtype=float) * scale
v += origin
points = voxel_pts * scale + v
return points, voxel_faces.copy()
points = []
faces = []
fi = 0
for i in range(RES_X):
for j in range(RES_Y):
for k in range(RES_Z):
if grid[i, j, k]:
p, f = get_voxel(i, j, k)
points.append(p)
f += fi
faces.append(f)
fi += 8
points = np.vstack(points)
faces = np.vstack(faces)
# Write obj mesh with quad faces
with open(os.path.join(output_folder, object_name + "_voxels.obj"), "w") as fout:
for p in points:fout.write("v " + " ".join(map(str, p)) + "\n")
for f in faces+1:fout.write("f " + " ".join(map(str, f)) + "\n")
print(object_name, "done.")
運(yùn)行:
Dependencies
- numpy
- trimesh
## Usage python voxelize_surface.py example/chair.obj --output_folder output --resolution 30 30 30 --sampling 10000
The optional parameters are:
- output_folder (string): folder where the result is saved
- resolution (list): the resolution of the grid
[res_x, res_y, res_z] - sampling (int): number of points sampled on the mesh surface before voxelization
- 注:輸入的類型可以時(shí)obj也可以是off以及ply格式!
注意:
若出現(xiàn)如下情況,可將采樣點(diǎn)數(shù)(sampling)提高!
出現(xiàn)此種情況的原因是采樣間隔太大,而體素尺寸太小(分辨太高),所以導(dǎo)致在有些體素的占有值進(jìn)行判斷的時(shí)候出現(xiàn)錯(cuò)誤。
所以也可以通過降低分辨率來改善此種情況!

Reference:
聲明:本文的代碼并非原創(chuàng),來自GitHub中zinsmatt的Surface_Voxels一作!若有侵權(quán)請聯(lián)系撤文!
https://github.com/zinsmatt/Surface_Voxels
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
sklearn線性邏輯回歸和非線性邏輯回歸的實(shí)現(xiàn)
這篇文章主要介紹了sklearn線性邏輯回歸和非線性邏輯回歸的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
詳解Django+Uwsgi+Nginx 實(shí)現(xiàn)生產(chǎn)環(huán)境部署
這篇文章主要介紹了詳解Django+Uwsgi+Nginx 實(shí)現(xiàn)生產(chǎn)環(huán)境部署,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11
pandas DataFrame行或列的刪除方法的實(shí)現(xiàn)示例
這篇文章主要介紹了pandas DataFrame行或列的刪除方法的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Python字符串和字典相關(guān)操作的實(shí)例詳解
這篇文章主要介紹了Python字符串和字典相關(guān)操作的實(shí)例詳解的相關(guān)資料,這里提供實(shí)例幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-09-09
python計(jì)算機(jī)視覺opencv矩形輪廓頂點(diǎn)位置確定
這篇文章主要為大家介紹了python計(jì)算機(jī)視覺opencv矩形輪廓頂點(diǎn)位置確定,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

