【3维视觉】mesh采样成sdf代码分析,sample_SDF_points

2023-10-23 23:10

本文主要是介绍【3维视觉】mesh采样成sdf代码分析,sample_SDF_points,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

sample_SDF_points的完整代码

gpu_id = '5'
source_dir = 'demo_data/input'
target_dir = 'demo_data/output'
all_classes = ["02691156","04090263"
]
num_samples_and_method = [(100000, 'uniformly'), (100000, 'near')]
################################################import os
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_id
from datetime import datetime
import numpy as np
import torch
from utils import *for c in all_classes:input_dir = os.path.join(source_dir, c)output_dir = os.path.join(target_dir, c)os.makedirs(output_dir, exist_ok=True)all_shapes = os.listdir(input_dir)all_shapes = [f.split('.')[0] for f in all_shapes]for i, shape_id in enumerate(all_shapes):print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), c, 'processing: %d/%d'%(i,len(all_shapes)))in_path = os.path.join(input_dir, shape_id+'.obj')out_path = os.path.join(output_dir, shape_id+'.npy')vertices, faces = load_obj(in_path)mesh = obj2nvc(vertices, faces).cuda()mesh_normals = face_normals(mesh)distrib = area_weighted_distribution(mesh, mesh_normals)xyz = sample_points(mesh, num_samples_and_method, mesh_normals, distrib)sd = points_mesh_signed_distance(xyz, mesh)xyz_sd = torch.cat([xyz, sd.unsqueeze(1)], dim=1)rand_idx = torch.randperm(xyz_sd.shape[0])xyz_sd = xyz_sd[rand_idx].cpu().numpy()np.save(out_path, xyz_sd)

导入obj读点面:vertices, faces = load_obj(in_path)

def load_obj(filename):"""Args:filename: str, path to .obj fileReturns:vertices: tensor(float), shape (num_vertices, 3)faces: tensor(long), shape (num_faces, 3)"""assert os.path.exists(filename), 'File \''+filename+'\' does not exist.'reader = tinyobjloader.ObjReader() # 构造tinyobjloader的ObjReader类config = tinyobjloader.ObjReaderConfig()config.triangulate = Truereader.ParseFromFile(filename, config) # 从文件filename中按配置config读objattrib = reader.GetAttrib()  # 得到逐点的属性vertices = torch.FloatTensor(attrib.vertices).reshape(-1, 3) # 得到n*3维的张量shapes = reader.GetShapes()faces = []for shape in shapes:faces += [idx.vertex_index for idx in shape.mesh.indices]faces = torch.LongTensor(faces).reshape(-1, 3)return vertices, faces

attrib = reader.GetAttrib()

返回的是attrib_t类型
其中attrib.vertices是将每个点的3个坐标依次排放在一个list中
比如有n个点,得到的attrib.vertices的维度就是3n
在这里插入图片描述

class attrib_t(__pybind11_builtins.pybind11_object):# no docdef numpy_vertices(self): # real signature unknown; restored from __doc__""" numpy_vertices(self: tinyobjloader.attrib_t) -> numpy.ndarray[float64] """passdef __init__(self): # real signature unknown; restored from __doc__""" __init__(self: tinyobjloader.attrib_t) -> None """passcolors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultnormals = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaulttexcoords = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultvertices = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

vertices = torch.FloatTensor(attrib.vertices).reshape(-1, 3)

torch.FloatTensor()

类型转换, 将list ,numpy转化为tensor,其中的每个数据是float类型

reshape(-1,3)

维度转换,将tensor转换3列的维度,(-1)表示转换后行的维度需要计算得到。
在这里插入图片描述

shapes = reader.GetShapes()

shapes的数据结构
在这里插入图片描述
shape.mesh.indices的数据结构
在这里插入图片描述

class shape_t(__pybind11_builtins.pybind11_object):# no docdef __init__(self): # real signature unknown; restored from __doc__""" __init__(self: tinyobjloader.shape_t) -> None """passlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultmesh = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultname = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultpoints = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

faces += [idx.vertex_index for idx in shape.mesh.indices]

得到的faces的维度为:301,656, 把每个面的三个点索引依次排放到list中
在这里插入图片描述

faces = torch.LongTensor(faces).reshape(-1, 3)

得到的faces的维度为:100,552x3,表示的就是有100552个面,每行代表组成这个面的三个顶点的索引

转换数据格式为N面-3点-xyz: mesh = obj2nvc(vertices, faces).cuda()

def obj2nvc(vertices, faces):"""Args:vertices: tensor(float), shape (num_vertices, 3)faces: tensor(long), shape (num_faces, 3)Returns:mesh: tensor(float), shape (num_faces, 3, 3), (num_faces, 3 vertices, xyz coordinates)"""mesh = vertices[faces.flatten()].reshape(faces.size()[0], 3, 3)return mesh.contiguous()

mesh = vertices[faces.flatten()].reshape(faces.size()[0], 3, 3)

得到的mesh的维度是100,552x3x3,即每个面对应的3个点,每一个点对应的3个坐标值
在这里插入图片描述

求每个面的法线:mesh_normals = face_normals(mesh)

def face_normals(mesh):"""Args:mesh: tensor(float), shape (num_faces, 3, 3)Returns:normals: tensor(float), shape (num_faces, 3)"""vec_a = mesh[:, 0] - mesh[:, 1]  # 每个三角形面的第0个顶点坐标-第1个顶点坐标=矢量10vec_b = mesh[:, 1] - mesh[:, 2]  # 每个三角形面的第1个顶点坐标-第2个顶点坐标=矢量21normals = torch.cross(vec_a, vec_b)  # 计算两个矢量的叉乘得到法线return normals

分析面的分布:distrib = area_weighted_distribution(mesh, mesh_normals)

def area_weighted_distribution(mesh, normals=None):"""Args:mesh: tensor(float), shape (num_faces, 3, 3)normals: tensor(float), shape (num_faces, 3)Returns:distrib: distribution"""if normals is None:normals = face_normals(mesh)areas = torch.norm(normals, p=2, dim=1) * 0.5areas /= torch.sum(areas) + 1e-10distrib = torch.distributions.Categorical(areas.view(-1))return distrib

torch.norm()

对输入张量input在给定维度dim上求p范数

def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None)

参考:
torch.norm()函数的用法

范数理解

重头戏1:xyz = sample_points(mesh, num_samples_and_method, mesh_normals, distrib)

num_samples_and_method = [(100000, 'uniformly'), (100000, 'near')]

从mesh模型上采样点

def sample_points(mesh, num_samples_and_method, normals=None, distrib=None):"""Args:mesh: tensor(float), shape (num_faces, 3, 3)num_samples_and_method: [tuple(int, str)]normals: tensor(float), shape (num_faces, 3)distrib: distributionReturns:samples: tensor(float), shape (num_samples, 3)"""if normals is None:normals = face_normals(mesh)if distrib is None:distrib = area_weighted_distribution(mesh, normals)samples = []for num_samples, method in num_samples_and_method:if method == 'uniformly':samples.append(sample_uniformly(mesh, num_samples))elif method == 'surface':samples.append(sample_on_surface(mesh, num_samples, normals, distrib)[0])elif method == 'near':samples.append(sample_near_surface(mesh, num_samples, normals, distrib))samples = torch.cat(samples, dim=0)return samples

均匀采样:sample_uniformly(mesh, num_samples)

def sample_uniformly(mesh, num_samples):"""sample uniformly in [-1,1] bounding volume.Args:mesh: tensor(float), shape (num_faces, 3, 3)num_samples: intReturns:samples: tensor(float), shape (num_samples, 3)"""samples = (torch.rand(num_samples, 3) - 0.5) * 1.1samples = samples.to(mesh.device)return samples

每个面上采样:sample_on_surface(mesh, num_samples, normals, distrib)

squeeze:压缩维度,
unsqueeze:膨胀维度,unsqueeze(-1)在最后一维增加一个维度

def sample_on_surface(mesh, num_samples, normals=None, distrib=None):"""Args:mesh: tensor(float), shape (num_faces, 3, 3)num_samples: intnormals: tensor(float), shape (num_faces, 3)distrib: distributionReturns:samples: tensor(float), shape (num_samples, 3)normals: tensor(float), shape (num_samples, 3)"""if normals is None:normals = face_normals(mesh)if distrib is None:distrib = area_weighted_distribution(mesh, normals)idx = distrib.sample([num_samples])selected_faces = mesh[idx]selected_normals = normals[idx]u = torch.sqrt(torch.rand(num_samples)).to(mesh.device).unsqueeze(-1)v = torch.rand(num_samples).to(mesh.device).unsqueeze(-1)samples = (1 - u) * selected_faces[:,0,:] + (u * (1 - v)) * selected_faces[:,1,:] + u * v * selected_faces[:,2,:]  # 每个面上采样了一个点return samples, selected_normals

sample_near_surface(mesh, num_samples, normals, distrib)

def sample_near_surface(mesh, num_samples, normals=None, distrib=None):"""Args:mesh: tensor(float), shape (num_faces, 3, 3)num_samples: intnormals: tensor(float), shape (num_faces, 3)distrib: distributionReturns:samples: tensor(float), shape (num_samples, 3)"""samples = sample_on_surface(mesh, num_samples, normals, distrib)[0] #  面上采样samples += torch.randn_like(samples) * 0.01 # 面上采样完后再对坐标进行一些偏移return samples

torch.randn为从标准正太分布(均值为0,方差为1)中随机选择的一组数

重头戏2:sd = points_mesh_signed_distance(xyz, mesh)

求采样点到mesh表面的距离

def points_mesh_signed_distance(points, mesh):"""Args:points: tensor(float), shape (num_points, 3)mesh: tensor(float), shape (num_faces, 3, 3)Returns:sd: tensor(float), shape (num_points,)"""sd = mesh2sdf.mesh2sdf_gpu(points, mesh)[0]  # nvidia实现的C++,gpu版本的mesh2sdfreturn sd

将坐标xyz和到表面距离sd拼接起来: xyz_sd = torch.cat([xyz, sd.unsqueeze(1)], dim=1)

sd.unsqueeze(1),比如原来
sd.shape 为 torch.Size([num_samples])
sd.unsqueeze(1).shape为 torch.Size([num_samples,1])

这篇关于【3维视觉】mesh采样成sdf代码分析,sample_SDF_points的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/271064

相关文章

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

python中Hash使用场景分析

《python中Hash使用场景分析》Python的hash()函数用于获取对象哈希值,常用于字典和集合,不可变类型可哈希,可变类型不可,常见算法包括除法、乘法、平方取中和随机数哈希,各有优缺点,需根... 目录python中的 Hash除法哈希算法乘法哈希算法平方取中法随机数哈希算法小结在Python中,

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Java Stream的distinct去重原理分析

《JavaStream的distinct去重原理分析》Javastream中的distinct方法用于去除流中的重复元素,它返回一个包含过滤后唯一元素的新流,该方法会根据元素的hashcode和eq... 目录一、distinct 的基础用法与核心特性二、distinct 的底层实现原理1. 顺序流中的去重

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.