API文档
本页自动汇总 sindre 库主要模块的全部 API,支持自动文档与交互查询。
LMDB模块API
Reader
用于读取包含张量(numpy.ndarray
)数据集的对象。
这些张量是通过使用MessagePack从Lightning Memory-Mapped Database (LMDB)中读取的。
__getitem__(key)
使用get_sample()
从data_db
返回样本。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
int/slice类型的值 |
required |
Returns:
Type | Description |
---|---|
list
|
对应索引对象 |
__init__(dirpath, multiprocessing=False)
初始化
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
包含LMDB的目录路径。 |
required | |
multiprocessing
|
是否开启多进程读取。 |
False
|
__len__()
Returns:
Type | Description |
---|---|
int
|
返回数据集中的样本数量。 |
close()
Returns:
Type | Description |
---|---|
关闭环境。使打开的任何迭代器、游标和事务无效。 |
get_data_key_info()
Returns:
Type | Description |
---|---|
set
|
获取元数据库所有键 |
get_data_keys(i=0)
返回第i个样本在data_db
中的所有键的列表。
如果所有样本包含相同的键,则只需要检查第一个样本,因此默认值为i=0
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
索引 |
0
|
Returns:
Type | Description |
---|---|
list
|
list类型对象 |
get_data_specification(i)
返回第i个样本的所有数据对象的规范。
规范包括形状和数据类型。这假设每个数据对象都是numpy.ndarray
。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
索引 |
required |
Returns:
Type | Description |
---|---|
dict
|
数据字典 |
get_data_value(i, key)
返回第i个样本对应于输入键的值。
该值从data_db
中检索。
因为每个样本都存储在一个msgpack中,所以在返回值之前,我们需要先读取整个msgpack。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
索引 |
required |
key
|
str
|
该索引的键 |
required |
Returns:
Type | Description |
---|---|
对应的值 |
get_meta_key_info()
Returns:
Type | Description |
---|---|
set
|
获取元数据库所有键 |
get_meta_str(key)
将输入键对应的值作为字符串返回。
该值从meta_db
中检索。
Args:
key: 字符串或字节字符串
Returns:
Type | Description |
---|---|
str
|
str,输入键对应的值 |
get_sample(i)
从data_db
返回第i个样本。
Args:
i: 索引
Returns:
Type | Description |
---|---|
dict
|
字典类型对象 |
get_samples(i, size)
返回从i
到i + size
的所有连续样本。
Notes
假设:
* 从i
到i + size
的每个样本具有相同的键集。
* 样本中的所有数据对象都是numpy.ndarray
类型。
* 与同一个键关联的值具有相同的张量形状和数据类型。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
int, 开始索引 |
required |
size
|
int
|
int, 索引长度 |
required |
Returns:
Type | Description |
---|---|
list
|
所有样本组成的list |
ReaderList
组合多个LMDB数据库进行统一读取的类,提供序列协议的接口
该类用于将多个LMDB数据库合并为一个逻辑数据集,支持通过索引访问和获取长度。 内部维护数据库索引映射表和真实索引映射表,实现跨数据库的透明访问。
Attributes:
Name | Type | Description |
---|---|---|
db_list |
List[Reader]
|
存储打开的LMDB数据库实例列表 |
db_mapping |
List[int]
|
索引到数据库索引的映射表,每个元素表示对应索引数据所在的数据库下标 |
real_idx_mapping |
List[int]
|
索引到数据库内真实索引的映射表,每个元素表示数据在对应数据库中的原始索引 |
__del__()
析构函数,自动调用close方法释放资源
注意:不保证析构函数会被及时调用,建议显式调用close()
__getitem__(idx)
通过索引获取数据条目
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
数据条目在组合数据集中的逻辑索引 |
required |
Returns:
Name | Type | Description |
---|---|---|
object |
对应位置的数据条目,具体类型取决于LMDB存储的数据格式 |
Raises:
Type | Description |
---|---|
IndexError
|
当索引超出组合数据集范围时抛出 |
__init__(db_path_list, multiprocessing=True)
初始化组合数据库读取器
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db_path_list
|
List[str]
|
LMDB数据库文件路径列表,按顺序加载每个数据库 |
required |
__len__()
获取组合数据集的总条目数
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
所有LMDB数据库的条目数之和 |
close()
关闭所有打开的LMDB数据库连接
该方法应在使用完毕后显式调用,确保资源正确释放
ReaderSSD
针对SSD优化的LMDB数据库读取器,支持高效随机访问
该类针对SSD存储特性优化,每次读取时动态打开数据库连接, 适合需要高并发随机访问的场景,可充分利用SSD的IOPS性能。
Attributes:
Name | Type | Description |
---|---|---|
db_len |
int
|
数据库条目总数 |
db_path |
str
|
LMDB数据库文件路径 |
multiprocessing |
bool
|
是否启用多进程模式 |
__getitem__(idx)
通过索引获取单个数据条目
每次调用时动态打开数据库连接,读取完成后立即关闭。 适合随机访问模式,特别是在SSD存储上。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
数据条目索引 |
required |
Returns:
Name | Type | Description |
---|---|---|
object |
object
|
索引对应的数据条目 |
Raises:
Type | Description |
---|---|
IndexError
|
当索引超出有效范围时抛出 |
__init__(db_path, multiprocessing=False)
初始化SSD优化的LMDB读取器
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db_path
|
str
|
LMDB数据库文件路径 |
required |
multiprocessing
|
bool
|
是否启用多进程支持。 启用后将允许在多个进程中同时打开数据库连接。默认为False。 |
False
|
__len__()
获取数据库的总条目数
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
数据库中的条目总数 |
get_batch(indices)
批量获取多个数据条目
优化的批量读取接口,在一个数据库连接中读取多个条目, 减少频繁打开/关闭连接的开销。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indices
|
list[int]
|
数据条目索引列表 |
required |
Returns:
Type | Description |
---|---|
list[object]: 索引对应的数据条目列表 |
Raises:
Type | Description |
---|---|
IndexError
|
当任何索引超出有效范围时抛出 |
ReaderSSDList
组合多个SSD优化的LMDB数据库进行统一读取的类,提供序列协议的接口
该类用于将多个SSD优化的LMDB数据库合并为一个逻辑数据集,支持通过索引访问和获取长度。 内部维护数据库索引映射表和真实索引映射表,实现跨数据库的透明访问,同时保持SSD优化特性。
Attributes:
Name | Type | Description |
---|---|---|
db_path_list |
List[str]
|
LMDB数据库文件路径列表 |
db_mapping |
List[int]
|
索引到数据库索引的映射表,每个元素表示对应索引数据所在的数据库下标 |
real_idx_mapping |
List[int]
|
索引到数据库内真实索引的映射表,每个元素表示数据在对应数据库中的原始索引 |
multiprocessing |
bool
|
是否启用多进程模式 |
__getitem__(idx)
通过索引获取数据条目
Parameters:
Name | Type | Description | Default |
---|---|---|---|
idx
|
int
|
数据条目在组合数据集中的逻辑索引 |
required |
Returns:
Name | Type | Description |
---|---|---|
object |
对应位置的数据条目,具体类型取决于LMDB存储的数据格式 |
Raises:
Type | Description |
---|---|
IndexError
|
当索引超出组合数据集范围时抛出 |
__init__(db_path_list, multiprocessing=False)
初始化组合SSD优化数据库读取器
Parameters:
Name | Type | Description | Default |
---|---|---|---|
db_path_list
|
List[str]
|
LMDB数据库文件路径列表,按顺序加载每个数据库 |
required |
multiprocessing
|
bool
|
是否启用多进程支持。默认为False。 |
False
|
__len__()
获取组合数据集的总条目数
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
所有LMDB数据库的条目数之和 |
get_batch(indices)
批量获取多个数据条目
对同一数据库中的索引进行分组,然后使用对应数据库的get_batch方法批量读取, 减少频繁打开/关闭连接的开销。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indices
|
list[int]
|
数据条目索引列表 |
required |
Returns:
Type | Description |
---|---|
list[object]: 索引对应的数据条目列表 |
Raises:
Type | Description |
---|---|
IndexError
|
当任何索引超出有效范围时抛出 |
Writer
用于将数据集的对象 ('numpy.ndarray') 写入闪电内存映射数据库 (LMDB),并带有MessagePack压缩。 Note:
db = sindre.lmdb.Writer(dirpath=r'datasets/lmdb', map_size_limit=1024*100,ram_gb_limit=3.0)
db.set_meta_str("描述信息", "xxxx")
data = {xx:np.array(xxx)} # 尽量占用ram_gb_limit内存
gb_required = db.check_sample_size(data) # 计算数据占用内存(GB)
db.put_samples(data) # 一次性写入,注意gb_required<ram_gb_limit限制
db.close()
__init__(dirpath, map_size_limit, multiprocessing=False)
初始化
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
str
|
应该写入LMDB的目录的路径。 |
required |
map_size_limit
|
int
|
LMDB的map大小,单位为MB。必须足够大以捕获打算存储在LMDB中所有数据。 |
required |
multiprocessing
|
bool
|
是否开启多进程。 |
False
|
change_db_value(key, value, safe_model=True)
修改键值
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
int
|
键 |
required |
value
|
dict
|
内容 |
required |
safe_model
|
bool
|
安全模式,如果开启,则修改会提示; |
True
|
change_value(num_id, samples)
通过指定索引,修改内容 Args: num_id: 索引 samples: 内容
Returns:
check_db_stats()
检查lmdb是继续写,还是新写
check_sample_size(samples)
检测sample字典的大小
Parameters:
Name | Type | Description | Default |
---|---|---|---|
samples
|
_type_
|
字典类型数据 |
required |
Return
gb_required : 字典大小(GB)
close()
关闭环境。
在关闭之前,将样本数写入meta_db
,使所有打开的迭代器、游标和事务无效。
put_samples(samples)
将传入内容的键和值放入data_db
LMDB中。
Notes
函数假设所有值的第一个轴表示样本数。因此,单个样本必须在numpy.newaxis
之前。
作为Python字典:
put_samples({'key1': value1, 'key2': value2, ...})
Parameters:
Name | Type | Description | Default |
---|---|---|---|
samples
|
dict
|
由字符串和numpy数组组成 |
required |
set_meta_str(key, string)
将输入的字符串写入meta_db
中的输入键。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
string or bytestring |
required | |
string
|
str
|
string |
required |
MergeLmdb(target_dir, source_dirs, map_size_limit, multiprocessing=False)
将多个源LMDB数据库合并到目标数据库
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_dir
|
str
|
目标LMDB路径 |
required |
source_dirs
|
list
|
源LMDB路径列表 |
required |
map_size_limit
|
int
|
目标LMDB的map大小限制(MB) |
required |
multiprocessing
|
bool
|
是否启用多进程模式 |
False
|
Example
# 合并示例
MergeLmdb(
target_dir="merged.db",
source_dirs=["db1", "db2"],
map_size_limit=1024 # 1GB
)
SplitLmdb(source_dir, target_dirs, map_size_limit, multiprocessing=False)
将源LMDB数据库均匀拆分到多个目标数据库
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source_dir
|
str
|
源LMDB路径 |
required |
target_dirs
|
list
|
目标LMDB路径列表 |
required |
map_size_limit
|
int
|
每个目标LMDB的map大小限制(MB) |
required |
multiprocessing
|
bool
|
是否启用多进程模式 |
False
|
Example
SplitLmdb(
source_dir="large.db",
target_dirs=[f"split_{i}.db" for i in range(4)],
map_size_limit=256
)
fix_lmdb_windows_size(dirpath)
修复lmdb在windows系统上创建大小异常问题(windows上lmdb没法实时变化大小);
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dirpath
|
str
|
lmdb目录路径 |
required |
Returns:
parallel_write(output_dir, file_list, process, map_size_limit, num_processes, multiprocessing=False, temp_root='./tmp', cleanup_temp=True)
多进程处理JSON文件并写入LMDB
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_dir
|
str
|
最终输出LMDB路径 |
required |
file_list
|
list
|
文件路径列表 |
required |
process
|
callable
|
数据处理函数 |
required |
map_size_limit
|
int
|
总LMDB的map大小限制(MB) |
required |
num_processes
|
int
|
进程数量 |
required |
multiprocessing
|
bool
|
是否启用多进程模式 |
False
|
temp_root
|
str
|
临时目录根路径(默认./tmp,尽量写在SSD,方便快速转换 |
'./tmp'
|
cleanup_temp
|
bool
|
是否清理临时目录(默认True) |
True
|
Example
def process(json_file):
with open(json_file,"r") as f:
data = json.loads(f.read())
id=data["id_patient"]
jaw = data["jaw"]
labels = data["labels"]
mesh = vedo.load( json_file.replace(".json",".obj"))
vertices = mesh.vertices
faces = mesh.cells
out = {
'mesh_faces':faces,
'mesh_vertices':vertices,
'vertex_labels':labels,
"jaw":jaw,
}
return out
if __name__ == '__main__':
json_file_list = glob.glob("./*/*/*.json")
print(len(json_file_list))
sindre.lmdb.parallel_write(
output_dir=dirpath,
file_list=json_file_list[:16],
process=process,
map_size_limit=map_size_limit,
num_processes=8,
temp_root="./processing_temp",
cleanup_temp=False
)
check_filesystem_is_ext4(current_path)
检测硬盘是否为ext4
Parameters:
Name | Type | Description | Default |
---|---|---|---|
current_path
|
str
|
需要检测的磁盘路径 |
required |
Returns:
Name | Type | Description |
---|---|---|
True |
bool
|
当前为ext4磁盘,支持自适应容量分配 |
False |
bool
|
当前不是ext4磁盘,不支持自适应容量分配 |
decode_data(obj)
解码一个序列化的数据对象。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Python 字典 一个描述序列化数据对象的字典。 |
required |
decode_str(obj, encoding='utf-8', errors='strict')
将输入字节对象解码为字符串。
Parameters
obj : byte object
encoding : string
Default is utf-8
.
errors : string
指定应如何处理编码错误。默认为 strict
.
encode_data(obj)
返回一个字典,该字典包含对输入数据对象进行编码后的信息。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
数据对象 如果传入的数据对象既不是字符串也不是普通的 NumPy 数组, 则该对象将按原样返回。 |
required |
encode_str(string, encoding='utf-8', errors='strict')
返回输入字符串的编码字节对象。
Parameters
string : string
encoding : string
Default is utf-8
.
errors : string
指定应如何处理编码错误。默认为 strict
.
三维算法API
@path :sindre_package -> tools.py
@IDE :PyCharm
@Author :sindre
@Email :yx@mviai.com
@Date :2024/6/17 15:38
@Version: V0.1
@License: (C)Copyright 2021-2023 , UP3D
@Reference:
@History:
- 2024/6/17 :
(一)本代码的质量保证期(简称“质保期”)为上线内 1个月,质保期内乙方对所代码实行包修改服务。
(二)本代码提供三包服务(包阅读、包编译、包运行)不包熟
(三)本代码所有解释权归权归神兽所有,禁止未开光盲目上线
(四)请严格按照保养手册对代码进行保养,本代码特点:
i. 运行在风电、水电的机器上
ii. 机器机头朝东,比较喜欢太阳的照射
iii. 集成此代码的人员,应拒绝黄赌毒,容易诱发本代码性能越来越弱
声明:未履行将视为自主放弃质保期,本人不承担对此产生的一切法律后果
如有问题,热线: 114
A_Star
__init__(vertices, faces)
使用A*算法在三维三角网格中寻找最短路径
参数: vertices: numpy数组,形状为(N,3),表示顶点坐标 faces: numpy数组,形状为(M,3),表示三角形面的顶点索引
build_adjacency(faces)
构建顶点的邻接表
run(start_idx, end_idx, vertex_weights=None)
使用A*算法在三维三角网格中寻找最短路径
参数: start_idx: 起始顶点的索引 end_idx: 目标顶点的索引 vertex_weights: 可选,形状为(N,),顶点权重数组,默认为None
返回: path: 列表,表示从起点到终点的顶点索引路径,若不可达返回None
BestKFinder
__init__(points, labels)
初始化类,接收点云网格数据和对应的标签
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
ndarray
|
点云数据,形状为 (N, 3) |
required |
labels
|
ndarray
|
点云标签,形状为 (N,) |
required |
calculate_boundary_points(k)
计算边界点 :param k: 最近邻点的数量 :return: 边界点的标签数组
evaluate_boundary_points(bd_labels)
评估边界点的分布合理性 这里简单使用边界点的数量占比作为评估指标 :param bd_labels: 边界点的标签数组 :return: 评估得分
find_best_k(k_values)
找出最佳的最近邻点大小
:param k_values: 待测试的最近邻点大小列表 :return: 最佳的最近邻点大小
FlyByGenerator
从3D网格模型生成多视角2D图像的渲染器
支持从不同视角渲染3D网格,生成包含法线、深度等特征的2D图像, 并提供像素到顶点的映射功能,用于后续网格顶点标签的生成。
__init__(vertices, faces, resolution=224, use_z=False, split_z=False, rescale_features=False)
初始化渲染器
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
ndarray
|
网格顶点数组,形状为 (N, 3) |
required |
faces
|
ndarray
|
网格面数组,形状为 (M, 3) 或 (M, 4),表示三角形或四边形面 |
required |
resolution
|
int
|
输出图像的分辨率,默认为224×224 |
224
|
use_z
|
bool
|
是否启用深度缓冲(z-buffer) |
False
|
split_z
|
bool
|
是否将深度作为独立通道输出 |
False
|
rescale_features
|
bool
|
是否将特征值归一化到[-1, 1]或[0, 1] |
False
|
cleanup()
清理资源
get_mesh_labels(view_labels, pixel_mappings)
从多个视角的标签图像生成网格顶点标签
Parameters:
Name | Type | Description | Default |
---|---|---|---|
view_labels
|
List[ndarray]
|
每个视角的标签图像列表 |
required |
pixel_mappings
|
List[Dict]
|
每个视角的像素到顶点映射列表 |
required |
Returns:
Type | Description |
---|---|
ndarray
|
网格顶点标签数组 |
get_pixel2point(view_index)
获取指定视角的像素到顶点映射(简化版本)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
view_index
|
int
|
视角索引 |
required |
Returns:
Type | Description |
---|---|
Dict[Tuple[int, int], int]
|
像素坐标到顶点索引的映射字典 |
render_views()
渲染所有视角的图像
Returns:
Type | Description |
---|---|
ndarray
|
渲染图像数组,形状为(num_views, height, width, channels) |
set_sphere_sampling(method, param, radius=4.0, turns=4)
设置球体采样点方法
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
采样方法,"subdivision"或"spiral" |
required |
param
|
int
|
细分级别(用于subdivision)或点数(用于spiral) |
required |
radius
|
float
|
采样球半径 |
4.0
|
turns
|
int
|
螺旋方法的旋转圈数 |
4
|
GraphCutRefiner
__init__(vertices, faces, vertex_labels, smooth_factor=None, temperature=None, keep_label=True)
基于顶点的图切优化器
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
array - like
|
顶点坐标数组,形状为 (n_vertices, 3)。 |
required |
faces
|
array - like
|
面片索引数组,形状为 (n_faces, 3)。 |
required |
vertex_labels
|
array - like
|
顶点初始标签数组,形状为 (n_vertices,)。 |
required |
smooth_factor
|
float
|
平滑强度系数,越大边界越平滑。默认值为 None,此时会自动计算。范围通常在 0.1 到 0.6 之间。 |
None
|
temperature
|
float
|
温度参数,越大标签越平滑,处理速度越快。默认值为 None,此时会自动计算。典型值范围在 50 到 500 之间,会随网格复杂度自动调整。 |
None
|
keep_label
|
bool
|
是否保持优化前后标签类别一致性,默认值为 True。 |
True
|
refine_labels()
执行标签优化 :return: 优化后的顶点标签数组 (n_vertices,)
LabelUpsampler
__init__(classifier_type='gbdt', knn_params={'n_neighbors': 3}, gbdt_params={'n_estimators': 100, 'max_depth': 5})
标签上采样,用于将简化后的标签映射回原始网格/点云
Parameters:
Name | Type | Description | Default |
---|---|---|---|
classifier_type
|
str, optional (default='gbdt') 分类器类型,支持 'knn', 'gbdt', 'hgbdt', 'rfc' |
'gbdt'
|
|
knn_params
|
dict, optional KNN分类器参数,默认 {'n_neighbors': 3} |
{'n_neighbors': 3}
|
|
gbdt_params
|
dict, optional GBDT/HGBDT/RFC分类器参数,默认 {'n_estimators': 100, 'max_depth': 5} |
{'n_estimators': 100, 'max_depth': 5}
|
fit(train_features, train_labels)
训练模型: 建议: 点云: 按照[x,y,z,nx,ny,nz,cv] # 顶点坐标+顶点法线+曲率+其他特征 网格: 按照[bx,by,bz,fnx,fny,fny] # 面片重心坐标+面片法线+其他特征
predict(query_features)
预测标签,输入特征应与训练特征一一对应;
MeshRandomWalks
__init__(vertices, faces, face_normals=None)
随机游走分割网格
参考:https://www.cnblogs.com/shushen/p/5144823.html
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
顶点坐标数组,形状为(N, 3) |
required | |
faces
|
面片索引数组,形状为(M, 3) |
required | |
face_normals
|
可选的面法线数组,形状为(M, 3) |
None
|
Note:
```python
# 加载并预处理网格
mesh = vedo.load(r"upper_jaws.ply")
mesh.compute_normals()
# 创建分割器实例
segmenter = MeshRandomWalks(
vertices=mesh.points,
faces=mesh.faces(),
face_normals=mesh.celldata["Normals"]
)
head = [1063,3571,1501,8143]
tail = [7293,3940,8021]
# 执行分割
labels, unmarked = segmenter.segment(
foreground_seeds=head,
background_seeds=tail
)
p1 = vedo.Points(mesh.points[head],r=20,c="red")
p2 = vedo.Points(mesh.points[tail],r=20,c="blue")
# 可视化结果
mesh.pointdata["labels"] = labels
mesh.cmap("jet", "labels")
vedo.show([mesh,p1,p2], axes=1, viewup='z').close()
```
segment(foreground_seeds, background_seeds, vertex_weights=None)
执行网格分割
参数
foreground_seeds: 前景种子点索引列表 background_seeds: 背景种子点索引列表 vertex_weights: 可选的顶点权重矩阵(稀疏矩阵)
返回
labels: 顶点标签数组 (0: 背景,1: 前景) unmarked: 未标记顶点的布尔掩码
NpEncoder
Bases: JSONEncoder
Notes
将numpy类型编码成json格式
UnifiedLabelRefiner
__init__(vertices, faces, labels, class_num, smooth_factor=None, temperature=None)
统一多标签优化器,支持顶点/面片概率输入
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
ndarray
|
顶点坐标数组,形状 (Nv, 3) |
required |
faces
|
ndarray
|
面片索引数组,形状 (Nf, 3) |
required |
labels
|
ndarray
|
初始标签,可以是类别索引(一维)(n,) 或概率矩阵,形状为: - 顶点模式:(Nv, class_num) - 面片模式:(Nf, class_num) |
required |
class_num
|
int
|
总类别数量(必须等于labels.shape[1]) |
required |
smooth_factor
|
float
|
边权缩放因子,默认自动计算 |
None
|
temperature
|
float
|
标签软化温度(None表示不软化) |
None
|
refine()
执行优化并返回优化后的标签索引
add_base(vd_mesh, value_z=-20, close_base=True, return_strips=False)
给网格边界z方向添加底座
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vd_mesh
|
_type_
|
vedo.mesh |
required |
value_z
|
int
|
底座长度. Defaults to -20. |
-20
|
close_base
|
bool
|
底座是否闭合. Defaults to True. |
True
|
return_strips
|
bool
|
是否返回添加的网格. Defaults to False. |
False
|
Returns:
Name | Type | Description |
---|---|---|
_type_ |
添加底座的网格 |
angle_axis_np(angle, axis)
计算绕给定轴旋转指定角度的旋转矩阵。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle
|
float
|
旋转角度(弧度)。 |
required |
axis
|
ndarray
|
旋转轴,形状为 (3,) 的 numpy 数组。 |
required |
Returns:
Type | Description |
---|---|
np.array: 3x3 的旋转矩阵,数据类型为 np.float32。 |
apply_transform(vertices, transform)
对4*4矩阵进行应用
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
array
|
顶点 |
required |
transform
|
array
|
4*4 矩阵 |
required |
Returns:
Type | Description |
---|---|
array
|
变换后的顶点 |
array2voxel(voxel_array)
将固定大小的三维数组转换为 voxel_grid_index 数组。
该函数接收一个形状为 (voxel_size, voxel_size, voxel_size) 的三维数组,
找出其中值为 1 的元素的索引,将这些索引组合成一个形状为 (N, 3) 的数组,
类似于从 open3d 的 o3d.voxel_grid.get_voxels () 方法获取的结果。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
voxel_array
|
ndarray
|
形状为 (voxel_size, voxel_size, voxel_size) 的三维数组,数组中值为 1 的位置代表对应的体素网格索引。 |
required |
Returns:
numpy.ndarray: 形状为 (N, 3) 的数组,表示三维空间中每个体素的网格索引,类似于从 o3d.voxel_grid.get_voxels () 方法获取的结果。
Example:
```python
# 获取 grid_index_array
voxel_list = voxel_grid.get_voxels()
grid_index_array = list(map(lambda x: x.grid_index, voxel_list))
grid_index_array = np.array(grid_index_array)
voxel_grid_array = voxel2array(grid_index_array, voxel_size=32)
grid_index_array = array2voxel(voxel_grid_array)
pointcloud_array = grid_index_array # 0.03125 是体素大小
pc = o3d.geometry.PointCloud()
pc.points = o3d.utility.Vector3dVector(pointcloud_array)
o3d_voxel = o3d.geometry.VoxelGrid.create_from_point_cloud(pc, voxel_size=0.05)
o3d.visualization.draw_geometries([pcd, cc, o3d_voxel])
```
collision_depth(mesh1, mesh2)
计算两个网格间的碰撞深度或最小间隔距离。
使用VTK的带符号距离算法检测碰撞状态: - 正值:两网格分离,返回值为最近距离 - 零值:表面恰好接触 - 负值:发生穿透,返回值为最大穿透深度(绝对值)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh1
|
Mesh
|
第一个网格对象,需包含顶点数据 |
required |
mesh2
|
Mesh
|
第二个网格对象,需包含顶点数据 |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
带符号的距离值,符号表示碰撞状态,绝对值表示距离量级 |
Raises:
Type | Description |
---|---|
RuntimeError
|
当VTK计算管道出现错误时抛出 |
Notes
- 当输入网格顶点数>1000时会产生性能警告
- 返回float('inf')表示计算异常或无限远距离
color_mapping(value, vmin=-1, vmax=1)
将向量映射为颜色,遵从vcg映射标准
compute_curvature_by_igl(v, f, max_curvature=False)
用igl计算平均曲率并归一化
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
顶点; |
required | |
f
|
面片: |
required | |
max_curvature
|
返回最大曲率 |
False
|
Returns:
Type | Description |
---|---|
|
Notes
pd1 : #v by 3 maximal curvature direction for each vertex pd2 : #v by 3 minimal curvature direction for each vertex pv1 : #v by 1 maximal curvature value for each vertex pv2 : #v by 1 minimal curvature value for each vertex
compute_curvature_by_meshlab(ms)
使用 MeshLab 计算网格的曲率和顶点颜色。
该函数接收一个顶点矩阵和一个面矩阵作为输入,创建一个 MeshLab 的 MeshSet 对象, 并将输入的顶点和面添加到 MeshSet 中。然后,计算每个顶点的主曲率方向, 最后获取顶点颜色矩阵和顶点曲率数组。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ms
|
pymeshlab格式mesh; |
required |
Returns:
Type | Description |
---|---|
|
|
|
|
|
compute_face_normals(vertices, faces)
计算三角形网格中每个面的法线 Args: vertices: 顶点数组,形状为 (N, 3) faces: 面数组,形状为 (M, 3),每个面由三个顶点索引组成 Returns: 面法线数组,形状为 (M, 3)
compute_vertex_normals(vertices, faces)
计算三角形网格中每个顶点的法线 Args: vertices: 顶点数组,形状为 (N, 3) faces: 面数组,形状为 (M, 3),每个面由三个顶点索引组成 Returns: 顶点法线数组,形状为 (N, 3)
create_voxels(vertices, resolution=256)
通过顶点创建阵列方格体素
Args: vertices: 顶点 resolution: 分辨率
Returns:
Type | Description |
---|---|
返回 res**3 的顶点 , mc重建需要的缩放及位移 |
Notes
v, f = mcubes.marching_cubes(data.reshape(256, 256, 256), 0)
m=vedo.Mesh([v*scale+translation, f])
cut_mesh_point_loop(mesh, pts, invert=False)
基于vtk+dijkstra实现的基于线的分割;
线支持在网格上或者网格外;
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
_type_
|
待切割网格 |
required |
pts
|
Points
|
切割线 |
required |
invert
|
bool
|
选择保留外部. Defaults to False. |
False
|
Returns:
Name | Type | Description |
---|---|---|
_type_ |
切割后的网格 |
detect_boundary_points(points, labels, config=None)
基于局部标签一致性的边界点检测函数
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
ndarray
|
点云坐标,形状为 (N, 3) |
required |
labels
|
ndarray
|
点云标签,形状为 (N,) |
required |
config
|
dict
|
配置参数,包含: - knn_k: KNN查询的邻居数(默认40) - bdl_ratio: 边界判定阈值(默认0.8) |
None
|
Returns:
Type | Description |
---|---|
np.ndarray: 边界点掩码,形状为 (N,),边界点为True,非边界点为False |
equidistant_mesh(mesh, d=-0.01, merge=True)
此函数用于创建一个与输入网格等距的新网格,可选择将新网格与原网格合并。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
Mesh
|
输入的三维网格对象。 |
required |
d
|
(float, 可选)
|
顶点偏移的距离,默认为 -0.01。负值表示向内偏移,正值表示向外偏移。 |
-0.01
|
merge
|
(bool, 可选)
|
是否将原网格和偏移后的网格合并,默认为 True。 |
True
|
Returns:
Type | Description |
---|---|
vedo.Mesh 或 vedo.Assembly: 如果 merge 为 True,则返回合并后的网格;否则返回偏移后的网格。 |
face_labels_to_vertex_labels(vertices, faces, face_labels)
将三角网格的面片标签转换成顶点标签
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
Union[array, list]
|
牙颌三角网格 |
required |
faces
|
Union[array, list]
|
面片标签 |
required |
face_labels
|
array
|
顶点标签 |
required |
Returns:
Type | Description |
---|---|
array
|
顶点属性 |
farthest_point_sampling(vertices, n_sample=2000, auto_seg=True, n_batches=10)
最远点采样,支持自动分批处理
根据参数配置,自动决定是否将输入点云分割为多个批次进行处理。当处理大规模数据时, 建议启用auto_seg以降低内存需求并利用并行加速。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
ndarray
|
输入点云坐标,形状为(N, 3)的浮点数组 |
required |
n_sample
|
int
|
总采样点数,当auto_seg=False时生效。默认2000 |
2000
|
auto_seg
|
bool
|
是否启用自动分批处理(提速,但会丢失全局距离信息)。默认False |
True
|
n_batches
|
int
|
自动分批时的批次数量。默认10 |
10
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 采样点索引数组,形状为(n_sample,) |
Raises:
Type | Description |
---|---|
ValueError
|
当输入数组维度不正确时抛出 |
Notes
典型场景: - 小规模数据(如5万点以下): auto_seg=False,单批次处理 - 大规模数据(如百万级点): auto_seg=True,分10批处理,每批采样2000点
示例:
vertices = np.random.rand(100000, 3).astype(np.float32)
自动分10批,每批采2000点
indices = farthest_point_sampling(vertices, auto_seg=True)
单批采5000点
indices = farthest_point_sampling(vertices, n_sample=5000)
farthest_point_sampling_by_open3d(vertices, n_sample=2000)
基于open3d最远点采样,返回采样后的点
farthest_point_sampling_by_pointops2(vertices, len_vertices, n_sample=2000, device='cuda')
基于pointops2最远点采样,返回采样后的索引,要求输入为torch.tensor
fill_hole_with_center(mesh, boundaries, return_vf=False)
用中心点方式强制补洞
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
_type_
|
vedo.Mesh |
required |
boundaries
|
vedo.boundaries |
required | |
return_vf
|
是否返回补洞的mesh |
False
|
fix_component_by_meshlab(ms)
移除低质量的组件,如小的连通分量,移除网格中的浮动小组件(小面积不连通部分)。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ms
|
pymeshlab.MeshSet 对象 |
required |
Returns:
Type | Description |
---|---|
pymeshlab.MeshSet 对象 |
fix_floater_by_meshlab(mesh, nbfaceratio=0.1, nonclosedonly=False)
移除网格中的浮动小组件(小面积不连通部分)。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
MeshSet
|
输入的网格模型。 |
required |
nbfaceratio
|
float
|
面积比率阈值,小于该比率的部分将被移除。 |
0.1
|
nonclosedonly
|
bool
|
是否仅移除非封闭部分。 |
False
|
Returns:
Type | Description |
---|---|
Mesh
|
pymeshlab.MeshSet: 移除浮动小组件后的网格模型。 |
fix_invalid_by_meshlab(ms)
处理冗余元素,如合移除重复面和顶点等, 清理无效的几何结构,如折叠面、零面积面和未引用的顶点。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ms
|
pymeshlab.MeshSet 对象 |
required |
Returns:
Type | Description |
---|---|
pymeshlab.MeshSet 对象 |
fix_topology_by_meshlab(ms)
修复拓扑问题,如 T 型顶点、非流形边和非流形顶点,并对齐不匹配的边界。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ms
|
pymeshlab.MeshSet 对象 |
required |
Returns:
Type | Description |
---|---|
pymeshlab.MeshSet 对象 |
furthestsampling_jit(xyz, offset, new_offset)
使用并行批次处理的最远点采样算法实现
该方法将输入点云划分为多个批次,每个批次独立进行最远点采样。通过维护最小距离数组, 确保每次迭代选择距离已选点集最远的新点,实现高效采样。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
xyz
|
ndarray
|
输入点云坐标,形状为(N, 3)的C连续float32数组 |
required |
offset
|
ndarray
|
原始点云的分段偏移数组,表示每个批次的结束位置。例如[1000, 2000]表示两个批次 |
required |
new_offset
|
ndarray
|
采样后的分段偏移数组,表示每个批次的目标采样数。例如[200, 400]表示每批采200点 |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 采样点索引数组,形状为(total_samples,),其中total_samples = new_offset[-1] |
Notes
实现特点: - 使用Numba并行加速,支持多核并行处理不同批次 - 采用平方距离计算避免开方运算 - 每批次独立初始化距离数组,避免跨批次干扰 - 自动处理边界情况(空批次或零采样批次)
典型调用流程:
n_total = 10000 offset = np.array([1000, 2000, ..., 10000], dtype=np.int32) new_offset = np.array([200, 400, ..., 2000], dtype=np.int32) sampled_indices = furthestsampling_jit(xyz, offset, new_offset)
get_axis_rotation(axis, angle)
绕着指定轴获取3*3旋转矩阵
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis
|
list
|
轴向,[0,0,1] |
required |
angle
|
float
|
旋转角度,90.0 |
required |
Returns:
Type | Description |
---|---|
array
|
3*3旋转矩阵 |
get_obb_box(x_pts, z_pts, vertices)
给定任意2个轴向交点及顶点,返回定向包围框mesh Args: x_pts: x轴交点 z_pts: z轴交点 vertices: 所有顶点
Returns:
Type | Description |
---|---|
Tuple[list, list, array]
|
包围框的顶点, 面片索引,3*3旋转矩阵 |
get_obb_box_max_min(x_pts, z_pts, z_max_pts, z_min_pts, x_max_pts, x_min_pts, y_max_pts, y_min_pts, center)
给定任意2个轴向交点及最大/最小点,返回定向包围框mesh
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x_pts
|
array
|
x轴交点 |
required |
z_pts
|
array
|
z轴交点 |
required |
z_max_pts
|
array
|
最大z顶点 |
required |
z_min_pts
|
array
|
最小z顶点 |
required |
x_max_pts
|
array
|
最大x顶点 |
required |
x_min_pts
|
array
|
最小x顶点 |
required |
y_max_pts
|
array
|
最大y顶点 |
required |
y_min_pts
|
array
|
最小y顶点 |
required |
center
|
array
|
中心点 |
required |
Returns:
Type | Description |
---|---|
Tuple[list, list, array]
|
包围框的顶点, 面片索引,3*3旋转矩阵 |
get_pca_rotation(vertices)
通过pca分析顶点,获取3*3旋转矩阵,并应用到顶点;
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
array
|
三维顶点 |
required |
Returns:
Type | Description |
---|---|
array
|
应用旋转矩阵后的顶点 |
get_pca_transform(mesh)
将输入的顶点数据根据曲率及PCA分析得到的主成分向量,
并转换成4*4变换矩阵。
Notes
必须为底部非封闭的网格
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
Mesh
|
vedo网格对象 |
required |
Returns:
Type | Description |
---|---|
array
|
4*4 变换矩阵 |
harmonic_by_igl(v, f, map_vertices_to_circle=True)
谐波参数化后的2D网格
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
_type_
|
顶点 |
required |
f
|
_type_
|
面片 |
required |
map_vertices_to_circle
|
是否映射到圆形(正方形) |
True
|
Returns:
Type | Description |
---|---|
uv,v_p: 创建参数化后的2D网格,3D坐标 |
Note:
```
# 创建空间索引
uv_kdtree = KDTree(uv)
# 初始化可视化系统
plt = Plotter(shape=(1, 2), axes=False, title="Interactive Parametrization")
# 创建网格对象
mesh_3d = Mesh([v, f]).cmap("jet", calculate_curvature(v, f)).lighting("glossy")
mesh_2d = Mesh([v_p, f]).wireframe(True).cmap("jet", calculate_curvature(v, f))
# 存储选中标记
markers_3d = []
markers_2d = []
def on_click(event):
if not event.actor or event.actor not in [mesh_2d, None]:
return
if not hasattr(event, 'picked3d') or event.picked3d is None:
return
try:
# 获取点击坐标
uv_click = np.array(event.picked3d[:2])
# 查找最近顶点
_, idx = uv_kdtree.query(uv_click)
v3d = v[idx]
uv_point = uv[idx] # 获取对应2D坐标
# 创建3D标记(使用球体)
marker_3d = Sphere(v3d, r=0.1, c='cyan', res=12)
markers_3d.append(marker_3d)
# 创建2D标记(使用大号点)
marker_2d = Point(uv_point, c='magenta', r=10, alpha=0.8)
markers_2d.append(marker_2d)
# 更新视图
plt.at(0).add(marker_3d)
plt.at(1).add(marker_2d)
plt.render()
except Exception as e:
log.info(f"Error processing click: {str(e)}")
plt.at(0).show(mesh_3d, "3D Visualization", viewup="z")
plt.at(1).show(mesh_2d, "2D Parametrization").add_callback('mouse_click', on_click)
plt.interactive().close()
```
hole_filling_by_Radial(boundary_coords)
参考
[https://www.cnblogs.com/shushen/p/5759679.html]
实现的最小角度法补洞法;
Parameters:
Name | Type | Description | Default |
---|---|---|---|
boundary_coords
|
_type_
|
有序边界顶点 |
required |
Returns:
Type | Description |
---|---|
v,f: 修补后的曲面 |
Note
# 创建带孔洞的简单网格
s = vedo.load(r"J10166160052_16.obj")
# 假设边界点即网格边界点
boundary =vedo.Spline((s.boundaries().join(reset=True).vertices),res=100)
# 通过边界点进行补洞
filled_mesh =vedo.Mesh(hole_filling(boundary.vertices))
# 渲染补洞后的曲面
vedo.show([filled_mesh,boundary,s.alpha(0.8)], bg='white').close()
isotropic_remeshing_by_acvd(vedo_mesh, target_num=10000)
对给定的 vedo 网格进行均质化处理,使其达到指定的目标面数。
该函数使用 pyacvd 库中的 Clustering 类对输入的 vedo 网格进行处理。 如果网格的顶点数小于等于目标面数,会先对网格进行细分,然后进行聚类操作, 最终生成一个面数接近目标面数的均质化网格。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vedo_mesh
|
Mesh
|
输入的 vedo 网格对象,需要进行均质化处理的网格。 |
required |
target_num
|
int
|
目标面数,即经过处理后网格的面数接近该值。 默认为 10000。 |
10000
|
Returns:
Type | Description |
---|---|
vedo.Mesh: 经过均质化处理后的 vedo 网格对象,其面数接近目标面数。 |
Notes
该函数依赖于 pyacvd 和 pyvista 库,使用前请确保这些库已正确安装。
isotropic_remeshing_by_meshlab(mesh, target_edge_length=0.5, iterations=1)
使用 PyMeshLab 实现网格均匀化。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
输入的网格对象 (pymeshlab.MeshSet)。 |
required | |
target_edge_length
|
目标边长比例 %。 |
0.5
|
|
iterations
|
迭代次数,默认为 1。 |
1
|
Returns:
Type | Description |
---|---|
Mesh
|
均匀化后的网格对象。 |
labels2colors(labels)
将labels转换成颜色标签 Args: labels: numpy类型,形状(N)对应顶点的标签;
Returns:
Type | Description |
---|---|
RGBA颜色标签; |
labels_mapping(old_vertices, old_faces, new_vertices, old_labels, fast=True)
将原始网格的标签属性精确映射到新网格
参数
old_mesh(vedo) : 原始网格对象 new_mesh(vedo): 重网格化后的新网格对象 old_labels (np.ndarray): 原始顶点标签数组,形状为 (N,)
返回
new_labels (np.ndarray): 映射后的新顶点标签数组,形状为 (M,)
load(path)
基于文件扩展名自动解析不同格式的文件并加载数据。
支持的文件类型包括但不限于: - JSON: 解析为字典或列表 - TOML: 解析为字典 - INI: 解析为ConfigParser对象 - Numpy: .npy/.npz格式的数值数组 - Pickle: Python对象序列化格式 - TXT: 纯文本文件 - LMDB: 轻量级键值数据库 - PyTorch: .pt/.pth模型文件 - PTS: pts的3D点云数据文件 - constructionInfo: XML格式的牙齿模型数据
对于未知格式,尝试使用vedo库加载,支持多种3D模型格式。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
文件路径或目录路径(LMDB格式) |
required |
Returns:
Name | Type | Description |
---|---|---|
Any |
根据文件类型返回对应的数据结构,加载失败时返回None。 - JSON/TOML: dict或list - INI: ConfigParser对象 - Numpy: ndarray或NpzFile - Pickle: 任意Python对象 - TXT: 字符串 - LMDB: sindre.lmdb.Reader对象(使用后需调用close()) - PyTorch: 模型权重或张量 - PTS: 包含牙齿ID和边缘点的字典 - constructionInfo: 包含项目信息和多颗牙齿数据的字典 - vedo支持的格式: vedo.Mesh或vedo.Volume等对象 |
Raises:
Type | Description |
---|---|
Exception
|
记录加载过程中的错误,但函数会捕获并返回None |
Notes
- LMDB数据需要手动关闭: 使用完成后调用data.close()
- 3D模型加载依赖vedo库,确保环境已安装
- PyTorch模型默认加载到CPU,避免CUDA设备不可用时的错误
mesh2sdf(v, f, size=64)
体素化网格,该函数适用于非水密网格(带孔的网格)、自相交网格、具有非流形几何体的网格以及具有方向不一致的面的网格。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
array - like
|
网格的顶点数组。 |
required |
f
|
array - like
|
网格的面数组。 |
required |
size
|
int
|
体素化的大小,默认为 64。 |
64
|
Returns:
Name | Type | Description |
---|---|---|
array |
体素化后的数组。 |
Raises:
Type | Description |
---|---|
ImportError
|
如果未安装 'mesh-to-sdf' 库,会提示安装。 |
resample_mesh(vertices, faces, density=1, num_samples=None)
在由顶点和面定义的网格表面上进行点云重采样。
- 密度模式:根据单位面片面积自动计算总采样数
- 指定数量模式:直接指定需要采样的总点数
该函数使用向量化操作高效地在网格表面进行均匀采样,采样密度由单位面积点数决定。 采样策略基于重心坐标系,采用分层随机抽样方法。
注意: 零面积三角形会被自动跳过,因为不会分配采样点。
参考实现: https://chrischoy.github.io/research/barycentric-coordinate-for-mesh-sampling/
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
ndarray
|
网格顶点数组,形状为(V, 3),V表示顶点数量 |
required |
faces
|
ndarray
|
三角形面片索引数组,形状为(F, 3),数据类型应为整数 |
required |
density
|
(float, 可选)
|
每单位面积的采样点数,默认为1 |
1
|
num_samples
|
(int, 可选)
|
指定总采样点数,若提供则忽略density参数 |
None
|
Returns:
Type | Description |
---|---|
numpy.ndarray: 重采样后的点云数组,形状为(N, 3),N为总采样点数 |
Notes
采样点生成公式(重心坐标系): P = (1 - √r₁)A + √r₁(1 - r₂)B + √r₁ r₂ C 其中: - r₁, r₂ ∈ [0, 1) 为随机数 - A, B, C 为三角形顶点 - 该公式可确保在三角形表面均匀采样
算法流程: 1. 计算每个面的面积并分配采样点数 2. 通过随机舍入处理总点数误差 3. 使用向量化操作批量生成采样点
References
[1] Barycentric coordinate system - https://en.wikipedia.org/wiki/Barycentric_coordinate_system
restore_transform(vertices, transform)
根据提供的顶点及矩阵,进行逆变换(还原应用矩阵之前的状态)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
array
|
顶点 |
required |
transform
|
array
|
4*4变换矩阵 |
required |
Returns:
Type | Description |
---|---|
array
|
还原后的顶点坐标 |
sample_sdf_mesh(v, f, number_of_points=200000)
在曲面附近不均匀地采样 SDF 点,该函数适用于非水密网格(带孔的网格)、自相交网格、具有非流形几何体的网格以及具有方向不一致的面的网格。 这是 DeepSDF 论文中提出和使用的方法。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
array - like
|
网格的顶点数组。 |
required |
f
|
array - like
|
网格的面数组。 |
required |
number_of_points
|
int
|
采样点的数量,默认为 200000。 |
200000
|
Returns:
Name | Type | Description |
---|---|---|
tuple |
包含采样点数组和对应的 SDF 值数组的元组。 |
Raises:
Type | Description |
---|---|
ImportError
|
如果未安装 'mesh-to-sdf' 库,会提示安装。 |
save_np_json(output_path, obj)
保存np形式的json
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_path
|
str
|
保存路径 |
required |
obj
|
保存对象 |
required |
simplify_by_meshlab(vertices, faces, max_facenum=30000)
通过二次边折叠算法减少网格中的面数,简化模型。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
MeshSet
|
输入的网格模型。 |
required |
max_facenum
|
int
|
简化后的目标最大面数,默认为 200000。 |
30000
|
Returns:
Type | Description |
---|---|
Mesh
|
pymeshlab.MeshSet: 简化后的网格模型。 |
subdivide_loop_by_trimesh(vertices, faces, iterations=5, max_face_num=100000, face_mask=None)
对给定的顶点和面片进行 Loop 细分。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vertices
|
array - like
|
输入的顶点数组,形状为 (n, 3),其中 n 是顶点数量。 |
required |
faces
|
array - like
|
输入的面片数组,形状为 (m, 3),其中 m 是面片数量。 |
required |
iterations
|
int
|
细分的迭代次数,默认为 5。 |
5
|
max_face_num
|
int
|
细分过程中允许的最大面片数量,达到此数量时停止细分,默认为 100000。 |
100000
|
face_mask
|
array - like
|
面片掩码数组,用于指定哪些面片需要进行细分,默认为 None。 |
None
|
Returns:
Name | Type | Description |
---|---|---|
tuple |
包含细分后的顶点数组、细分后的面片数组和面片掩码数组的元组。 |
Notes
以下是一个示例代码,展示了如何使用该函数:
# 1. 获取每个点的最近表面点及对应面
face_indices = set()
kdtree = cKDTree(mesh.vertices)
for p in pts:
# 查找半径2mm内的顶点
vertex_indices = kdtree.query_ball_point(p, r=1.0)
for v_idx in vertex_indices:
# 获取包含这些顶点的面片
faces = mesh.vertex_faces[v_idx]
faces = faces[faces != -1] # 去除无效索引
face_indices.update(faces.tolist())
face_indices = np.array([[i] for i in list(face_indices)])
new_vertices, new_face, _ = subdivide_loop(v, f, face_mask=face_indices)
vertex_labels_to_face_labels(faces, vertex_labels)
将三角网格的顶点标签转换成面片标签,存在一个面片,多个属性,则获取出现最多的属性。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
faces
|
Union[array, list]
|
三角网格面片索引 |
required |
vertex_labels
|
Union[array, list]
|
顶点标签 |
required |
Returns:
Type | Description |
---|---|
array
|
面片属性 |
voxel2array(grid_index_array, voxel_size=32)
将 voxel_grid_index 数组转换为固定大小的三维数组。
该函数接收一个形状为 (N, 3) 的 voxel_grid_index 数组, 并将其转换为形状为 (voxel_size, voxel_size, voxel_size) 的三维数组。 其中,原 voxel_grid_index 数组中每个元素代表三维空间中的一个网格索引, 在转换后的三维数组中对应位置的值会被设为 1,其余位置为 0。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
grid_index_array
|
ndarray
|
形状为 (N, 3) 的数组, 通常从 open3d 的 o3d.voxel_grid.get_voxels() 方法获取, 表示三维空间中每个体素的网格索引。 |
required |
voxel_size
|
int
|
转换后三维数组的边长,默认为 32。 |
32
|
Returns:
Type | Description |
---|---|
numpy.ndarray: 形状为 (voxel_size, voxel_size, voxel_size) 的三维数组, 其中原 voxel_grid_index 数组对应的网格索引位置值为 1,其余为 0。 |
Example
# 获取 grid_index_array
voxel_list = voxel_grid.get_voxels()
grid_index_array = list(map(lambda x: x.grid_index, voxel_list))
grid_index_array = np.array(grid_index_array)
voxel_grid_array = voxel2array(grid_index_array, voxel_size=32)
grid_index_array = array2voxel(voxel_grid_array)
pointcloud_array = grid_index_array # 0.03125 是体素大小
pc = o3d.geometry.PointCloud()
pc.points = o3d.utility.Vector3dVector(pointcloud_array)
o3d_voxel = o3d.geometry.VoxelGrid.create_from_point_cloud(pc, voxel_size=0.05)
o3d.visualization.draw_geometries([pcd, cc, o3d_voxel])
Flip
对点云数据进行随机翻转增强。
Attributes:
Name | Type | Description |
---|---|---|
axis_x |
bool
|
是否启用X轴翻转,默认为True |
axis_y |
bool
|
是否启用Y轴翻转,默认为True |
axis_z |
bool
|
是否启用Z轴翻转,默认为True |
__call__(points)
对输入点云应用随机翻转变换。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6)(包含法线) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(axis_x=True, axis_y=True, axis_z=True)
初始化翻转增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis_x
|
bool
|
是否沿X轴翻转. Defaults to True. |
True
|
axis_y
|
bool
|
是否沿Y轴翻转. Defaults to True. |
True
|
axis_z
|
bool
|
是否沿Z轴翻转. Defaults to True. |
True
|
Flip_np
__init__(axis_x=True, axis_y=True, axis_z=True)
用于随机翻转点云数据。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis_x
|
bool
|
是否在 x 轴上进行翻转,默认为 True。 |
True
|
axis_y
|
bool
|
是否在 y 轴上进行翻转,默认为 True。 |
True
|
axis_z
|
bool
|
是否在 z 轴上进行翻转,默认为 True。 |
True
|
Jitter
对点云坐标添加随机噪声。
__call__(points)
应用噪声扰动。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(std=0.01, clip=0.05)
初始化噪声增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
std
|
float
|
噪声标准差. Defaults to 0.01. |
0.01
|
clip
|
float
|
噪声截断范围. Defaults to 0.05. |
0.05
|
Jitter_np
Bases: object
__init__(std=0.01, clip=0.05)
用于给点云数据添加随机抖动。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
std
|
float
|
抖动的高斯分布标准差,默认为 0.01。 |
0.01
|
clip
|
float
|
抖动的裁剪范围,默认为 0.05。 |
0.05
|
Normalize
对点云进行归一化处理。
__call__(points)
应用归一化处理。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, C) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 归一化后的点云数据 |
__init__(method='std', v_range=[0, 1])
初始化归一化处理器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
归一化方法,可选"std"(标准化)或其他(最大最小归一化). Defaults to "std". |
'std'
|
v_range
|
list
|
当使用最大最小归一化时的目标范围. Defaults to [0, 1]. |
[0, 1]
|
RandomCrop
__init__(radius=0.15)
随机移除一个点周围指定半径内的所有点
Parameters:
Name | Type | Description | Default |
---|---|---|---|
radius
|
float
|
移除半径,默认为0.15 |
0.15
|
RandomDropout
随机丢弃部分点云数据。
__call__(pc)
应用随机丢弃。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pc
|
Tensor
|
输入点云数据,形状为 (N, C) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 丢弃后的点云数据 |
__init__(max_dropout_ratio=0.2)
初始化丢弃增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_dropout_ratio
|
float
|
最大丢弃比例. Defaults to 0.2. |
0.2
|
RandomDropout_np
Bases: object
__init__(max_dropout_ratio=0.2, return_idx=False)
用于随机丢弃点云数据中的点。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_dropout_ratio
|
float
|
最大丢弃比例,范围为 [0, 1),默认为 0.2。 |
0.2
|
RotateAxis
绕指定轴随机旋转点云。
__call__(points)
应用绕轴随机旋转变换。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(axis=[0.0, 0.0, 1.0])
初始化旋转增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis
|
Tensor
|
旋转轴向量,形状为 (3,). Defaults to Z轴. |
[0.0, 0.0, 1.0]
|
RotateAxis_np
__init__(axis=[0.0, 0.0, 0.0])
初始化 RotateAxis 类,用于绕指定轴随机旋转点云数据。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
axis
|
ndarray
|
旋转轴,形状为 (3,),默认为 [0.0, 0.0, 0.0](z 轴)。 |
[0.0, 0.0, 0.0]
|
RotateXYZ
绕XYZ轴应用随机欧拉角旋转。
__call__(points)
应用三维随机旋转变换。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(angle_sigma=2, angle_clip=torch.pi)
初始化旋转增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle_sigma
|
float
|
旋转角度的标准差. Defaults to 2. |
2
|
angle_clip
|
float
|
旋转角度的截断范围. Defaults to torch.pi. |
pi
|
RotateXYZ_np
Bases: object
__init__(angle_sigma=2, angle_clip=np.pi)
用于在三个轴上随机微扰旋转点云数据。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle_sigma
|
float
|
旋转弧度的高斯分布标准差,默认为 2; |
2
|
angle_clip
|
float
|
旋转弧度的裁剪范围,默认为 np.pi。 |
pi
|
Scale
对点云数据进行随机缩放增强。
__call__(points)
对输入点云应用随机缩放变换。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(lo=0.8, hi=1.25)
初始化缩放增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lo
|
float
|
缩放下限. Defaults to 0.8. |
0.8
|
hi
|
float
|
缩放上限. Defaults to 1.25. |
1.25
|
Scale_np
__init__(lo=0.8, hi=1.25)
初始化 Scale 类,用于随机缩放点云数据。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lo
|
float
|
缩放因子的下限,默认为 0.8。 |
0.8
|
hi
|
float
|
缩放因子的上限,默认为 1.25。 |
1.25
|
ToTensor
将输入数据转换为torch.Tensor格式。
__call__(points)
执行数据类型转换和设备转移。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
ndarray | Tensor
|
输入点云数据 |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 转换后的张量 |
__init__(device='cpu')
初始化转换器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
str
|
目标设备. Defaults to "cpu". |
'cpu'
|
Translate
对点云应用随机平移变换。
__call__(points)
应用平移变换。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points
|
Tensor
|
输入点云数据,形状为 (N, 3) 或 (N, 6) |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 变换后的点云数据 |
__init__(translate_range=0.1)
初始化平移增强器。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
translate_range
|
float
|
平移范围. Defaults to 0.1. |
0.1
|
Translate_np
Bases: object
__init__(translate_range=0.1)
用于随机平移点云数据。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
translate_range
|
float
|
平移的范围,默认为 0.1。 |
0.1
|
angle_axis(angle, axis)
计算绕给定轴旋转指定角度的旋转矩阵(PyTorch版本)。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle
|
float
|
旋转角度(弧度)。 |
required |
axis
|
Tensor
|
旋转轴,形状为 (3,) 的Tensor。 |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 3x3 的旋转矩阵,数据类型为 torch.float32。 |
angle_axis_np(angle, axis)
计算绕给定轴旋转指定弧度的旋转矩阵。 罗德里格斯公式;
Parameters:
Name | Type | Description | Default |
---|---|---|---|
angle
|
float
|
旋转弧度。 |
required |
axis
|
ndarray
|
旋转轴,形状为 (3,) 的 numpy 数组。 |
required |
Returns:
Type | Description |
---|---|
np.array: 3x3 的旋转矩阵,数据类型为 np.float32。 |
set_seeds(seed=1024, cudnn_enable=False)
为Python环境和主要深度学习库设置固定的随机数种子,确保结果可复现。
参数
seed (int): 要使用的基础随机数种子,默认值为42。 cudnn_enable (bool): 是否将CuDNN设置为确定性模式,默认值为False。
专注于牙颌mesh的特殊实现
convert_fdi2idx(labels)
将口腔牙列的FDI编号(11-18,21-28/31-38,41-48)转换为(1-16),只支持单颌: 上颌: - 右上(11-18) → 1-8 - 左上(21-28) → 9-16
下颌: - 左下(31-38) → 1-8 - 右下(41-48) → 9-16 - 0或小于0 → 0
1 9
2 10
3 11
4 12
5 13
6 14
7 15 8 16
convert_labels2color(data)
将牙齿标签转换成RGBA颜色
Notes
只支持以下标签类型:
upper_dict = [0, 18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28]
lower_dict = [0, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Union[array, list]
|
属性 |
required |
Returns:
Name | Type | Description |
---|---|---|
colors |
list
|
对应属性的RGBA类型颜色 |
cut_mesh_point_loop_crow(mesh, pts, error_show=True, invert=True)
实现的基于线的牙齿冠分割;
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mesh
|
_type_
|
待切割网格 |
required |
pts
|
Points / Line
|
切割线 |
required |
error_show(bool,
|
optional
|
裁剪失败是否进行渲染. Defaults to True. |
required |
invert(bool)
|
是否取反; |
required |
Returns:
Name | Type | Description |
---|---|---|
_type_ |
切割后的网格 |
cut_with_ribbon(mesh, pts)
使用点序列切割网格
参数: pts: 切割点序列 (k, 3)
返回: new_v: 切割后顶点 new_f: 切割后面
subdivide_with_pts(v, f, line_pts, r=0.15, iterations=3, method='mid')
对给定的网格和线点集进行局部细分。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
array - like
|
输入网格的顶点数组。 |
required |
f
|
array - like
|
输入网格的面数组。 |
required |
line_pts
|
array - like
|
线的点集数组。 |
required |
r
|
float
|
查找线点附近顶点的半径,默认为 0.15. |
0.15
|
method
|
str
|
细分方法,可选值为 "mid"(中点细分)或其他值(对应 ls3_loop 细分),默认为 "mid"。 |
'mid'
|
Returns:
Type | Description |
---|---|
|
|
|
Notes
# 闭合线可能在曲面上,曲面内,曲面外
line = Line(pts)
mesh = isotropic_remeshing_by_acvd(mesh)
v, f = np.array(mesh.vertices), np.array(mesh.cells)
new_vertices, new_face = subdivide_with_pts(v, f, pts)
show([(Mesh([new_vertices, new_face]).c("green"), Line(pts, lw = 2, c = "red")),
(Mesh([v, f]).c("pink"), Line(pts, lw = 2, c = "red"))], N = 2).close()
transform_crown(near_mesh, jaw_mesh)
调整单冠的轴向
Tip
1.通过连通域分割两个邻牙;
2.以邻牙质心为确定x轴;
3.通过找对颌最近的点确定z轴方向;如果z轴方向上有mesh,则保持原样,否则将z轴取反向;
4.输出调整后的牙冠
Parameters:
Name | Type | Description | Default |
---|---|---|---|
near_mesh
|
Mesh
|
两个邻牙组成的mesh |
required |
jaw_mesh
|
Mesh
|
两个邻牙的对颌 |
required |
Returns:
Type | Description |
---|---|
Mesh
|
变换后的单冠mesh |
SindreMesh
三维网格中转类,假设都是三角面片
center
cached
property
计算网格的加权质心(基于面片面积加权)。
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 加权质心坐标,形状为 (3,)。 |
Notes
使用三角形面片面积作为权重,对三角形质心坐标进行加权平均。 该结果等价于网格的几何中心。
faces_area
cached
property
计算每个三角形面片的面积。
Notes
使用叉乘公式计算面积: 面积 = 0.5 * ||(v1 - v0) × (v2 - v0)||
faces_center
cached
property
每个三角形的中心(重心 [1/3,1/3,1/3])
faces_vertices
cached
property
将面片索引用顶点来表示
get_adj_list
cached
property
邻接表属性
get_adj_matrix
cached
property
基于去重边构建邻接矩阵
get_edges
cached
property
未去重边缘属性
nfaces
cached
property
获取顶点数量
npoints
cached
property
获取顶点数量
to_dict
property
将属性转换成python字典
to_json
property
转换成json
to_meshlab
property
转换成meshlab
to_open3d
property
转换成open3d
to_open3d_t
property
转换成open3d_t
to_trimesh
property
转换成trimesh
to_vedo
property
转换成vedo
to_vedo_pointcloud
property
转换成vedo点云
__repr__()
网格质量检测
apply_inv_transform(mat)
对顶点应用4x4/3x3变换矩阵进行逆变换(支持非正交矩阵)
apply_transform(mat)
对顶点应用4x4/3x3变换矩阵(支持非正交矩阵)
apply_transform_normals(mat)
处理顶点法线的变换(支持非均匀缩放和反射变换)---废弃,在复杂非正定矩阵,重新计算法线比变换更快,更加准确
check()
检测数据完整性,正常返回True
clone()
快速克隆当前网格对象
compute_normals(force=False)
计算顶点法线及面片法线.force代表是否强制重新计算
decimate(n=10000)
将网格下采样到指定点数,采用面塌陷
get_boundary(return_points=True, max_boundary=False)
获取非水密网格的边界环(可能有多个环);
Method: 1. 获取所有的边(未去重),并统计每条边出现的次数。在三角网格中,内部边会被两个三角形共享,而边界边只被一个三角形使用。 2. 筛选出只出现一次的边,这些边就是边界边。 3. 将边界边连接成有序的环(或多个环)。通过构建边界边的图,然后进行深度优先搜索或广度优先搜索来连接相邻的边。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
return_points
|
bool
|
True返回顶点坐标,False返回顶点索引 |
True
|
max_boundary
|
bool
|
True时只返回最大的边界环(按顶点数量) |
False
|
Return: list: 边界环列表,每个环是顶点索引的有序序列(闭合环,首尾顶点相同),当max_boundary=True,单个边界环数组
get_boundary_by_normal_angle(angle_threshold=30, max_boundary=True)
通过相邻三角面法线夹角识别特征边界环
Note
- 计算所有三角面的归一化法向量
- 遍历网格所有边,筛选出相邻两面法线夹角大于阈值的边(特征边)
- 将特征边连接成有序封闭环
Parameters:
Name | Type | Description | Default |
---|---|---|---|
self
|
必须为水密网格; |
required | |
angle_threshold
|
法线夹角阈值(度),默认30度; |
30
|
|
max_boundary
|
是否仅返回最长边界环,默认True; |
True
|
Returns:
Type | Description |
---|---|
边界环顶点索引列表(若max_boundary=True则返回单个环) |
get_color_mapping(value)
将向量映射为颜色,遵从vcg映射标准
get_curvature()
获取曲率
get_curvature_advanced()
获取更加精确曲率,但要求网格质量
get_near_idx(query_vertices)
获取最近索引
get_texture(write_path='texture_uv.png', image_size=(512, 512), uv=None)
将颜色转换为纹理贴图, Mesh([v, f]).texture(write_path,uv)
get_uv(return_circle=False)
cached
获取uv映射 与顶点一致(npoinst,2)
homogenize(n=10000)
均匀化网格到指定点数,采用聚类
load(load_path)
读取(.sm .smesh)文件
print_o3d()
使用open3d网格质量检测
rotate_xyz(angles_xyz, return_mat=False)
按照给定xyz角度列表进行xyz对应旋转
sample(density=1, num_samples=None)
网格表面上进行点云重采样 Args: density (float, 可选): 每单位面积的采样点数,默认为1 num_samples (int, 可选): 指定总采样点数N,若提供则忽略density参数
Returns:
Type | Description |
---|---|
numpy.ndarray: 重采样后的点云数组,形状为(N, 3),N为总采样点数 |
save(write_path)
保存mesh,pickle(.sm .smesh),其他由vedo支持
scale_xyz(dxdydz)
缩放xyz指定量,支持输入3个向量和1个向量
set_vertex_labels(vertex_labels)
设置顶点labels,并自动渲染颜色
shift_xyz(dxdydz)
平移xyz指定量,支持输入3个向量和1个向量
show(show_append=[], labels=None, exclude_list=[0], create_axes=True, return_vedo_obj=False)
渲染展示网格数据,并根据标签添加标记和坐标轴。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
show_append
|
list)
|
需要一起渲染的vedo属性 |
[]
|
labels
|
ndarray
|
网格顶点的标签数组,默认为None。如果提供,将根据标签为顶点着色,并为每个非排除标签添加标记。 |
None
|
exclude_list
|
list
|
要排除的标签列表,默认为[0]。列表中的标签对应的标记不会被显示。 |
[0]
|
create_axes
|
是否强制绘制世界坐标系。 |
True
|
|
return_vedo_obj
|
是否返回vedo显示对象列表; |
False
|
Returns:
Name | Type | Description |
---|---|---|
None |
该方法没有返回值,直接进行渲染展示。 |
split_component()
将网格按照连通分量分割,并返回最大和其余连通分量的顶点索引
Returns:
Name | Type | Description |
---|---|---|
tuple |
包含三个数组的元组 - 第一个元素: 连通分量数量 - 第二个元素: 最大连通分量的节点索引 - 第三个元素: 剩余部分的节点索引(即非最大连通分量的所有节点) |
subdivison(face_mask, iterations=3, method='mid')
局部细分
texture2colors(image_path='texture_uv.png', uv=None)
将纹理贴图转换成顶点颜色
to_pytorch3d(device='cpu')
转换成pytorch3d形式
Returns:
Name | Type | Description |
---|---|---|
mesh |
pytorch3d类型mesh |
to_torch(device='cpu')
将顶点&面片转换成torch形式
Returns:
Type | Description |
---|---|
vertices,faces,vertex_normals,vertex_colors: 顶点,面片,法线,颜色(没有则为None) |
update_geometry(new_vertices, new_faces=None)
更新网格的几何结构(顶点和面片),并通过最近邻算法将原有的顶点属性映射到新顶点上。
适用于在保持网格拓扑结构基本不变的情况下,对网格进行变形,细化,简化的场景。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
new_vertices
|
形状为(N,3)的浮点型数组,表示新的顶点坐标 |
required | |
new_faces
|
可选参数,形状为(M,3)的整数型数组,表示新的面片索引 |
None
|
notes
- 当新顶点数量与原顶点数量不同时,原顶点属性会根据最近邻关系进行映射
- 如果未提供新的面片信息,函数会尝试根据旧面片和顶点映射关系重建面片
matrix3d_by_vedo
Bases: Plotter
Generate a rendering window with slicing planes for the input Volume.
__init__(data, cmaps=('gist_ncar_r', 'hot_r', 'bone', 'bone_r', 'jet', 'Spectral_r'), clamp=True, show_histo=True, show_icon=True, draggable=False, at=0, **kwargs)
Generate a rendering window with slicing planes for the input Volume.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cmaps
|
(list) list of color maps names to cycle when clicking button |
('gist_ncar_r', 'hot_r', 'bone', 'bone_r', 'jet', 'Spectral_r')
|
|
clamp
|
(bool) clamp scalar range to reduce the effect of tails in color mapping |
True
|
|
use_slider3d
|
(bool) show sliders attached along the axes |
required | |
show_histo
|
(bool) show histogram on bottom left |
True
|
|
show_icon
|
(bool) show a small 3D rendering icon of the volume |
True
|
|
draggable
|
(bool) make the 3D icon draggable |
False
|
|
at
|
(int) subwindow number to plot to |
0
|
|
**kwargs
|
(dict) keyword arguments to pass to Plotter. |
{}
|
Examples:
show_matrix_by_vedo(data)
用vedo渲染矩阵
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
ndarray
|
输入的2d/3d数组; |
required |
神经网络API
Point Transformer V3 模型实现 用于点云处理的深度学习模型,支持序列化注意力机制、稀疏卷积和多种空间编码方法
关键特性: - 支持Z序和希尔伯特曲线编码,保持空间局部性 - 使用稀疏卷积(spconv)处理大规模点云 - 集成Flash Attention加速注意力计算 - 模块化设计,包含可堆叠的Transformer块
作者: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com) 依赖: addict, spconv, torch_scatter, flash_attn(可选)
Needed Pkgs: addict, flash_attn (requires CUDA)(recommended), spconv (requires CUDA toolkit), torch_scatter (torch version specific)
flash attn is not used in this test
pip install addict spconv-${CUDA} torch-scatter -f https://data.pyg.org/whl/torch-2.4.0+${CUDA}.html
${CUDA} is the CUDA version of your machine, e.g. cu124 for CUDA 12.4 OR cpu for cpu
DropPath
Bases: Module
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
Point
Bases: Dict
Point Structure of Pointcept
A Point (point cloud) in Pointcept is a dictionary that contains various properties of a batched point cloud. The property with the following names have a specific definition as follows:
- "coord": original coordinate of point cloud;
- "grid_coord": grid coordinate for specific grid size (related to GridSampling); Point also support the following optional attributes:
- "offset": if not exist, initialized as batch size is 1;
- "batch": if not exist, initialized as batch size is 1;
- "feat": feature of point cloud, default input of model;
- "grid_size": Grid size of point cloud (related to GridSampling); (related to Serialization)
- "serialized_depth": depth of serialization, 2 ** depth * grid_size describe the maximum of point cloud range;
- "serialized_code": a list of serialization codes;
- "serialized_order": a list of serialization order determined by code;
- "serialized_inverse": a list of inverse mapping determined by code; (related to Sparsify: SpConv)
- "sparse_shape": Sparse shape for Sparse Conv Tensor;
- "sparse_conv_feat": SparseConvTensor init with information provide by Point;
serialization(order='z', depth=None, shuffle_orders=False)
空间编码序列化(支持Z序和希尔伯特曲线)
relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
sparsify(pad=96)
转换为稀疏卷积张量
Point cloud is sparse, here we use "sparsify" to specifically refer to preparing "spconv.SparseConvTensor" for SpConv.
relay on ["grid_coord" or "coord" + "grid_size", "batch", "feat"]
pad: padding sparse for sparse shape.
PointModule
Bases: Module
点云处理模块基类,所有自定义模块应继承此类
PointSequential
Bases: PointModule
A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in.
PointTransformerV3
Bases: PointModule
forward(x, p)
PyTorch前向传播函数,用于处理点云数据的特征提取与变换。
该函数主要实现以下功能: 1. 将输入数据打包为点云处理库要求的data_dict格式 2. 进行点云序列化/稀疏化预处理 3. 通过嵌入层、编码器和解码器处理特征 4. 最终返回与输入形状匹配的特征张量
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
输入特征张量,形状应为(batch_size, num_points, feat_dim) |
required |
p
|
Tensor
|
点云坐标数据,形状应为(batch_size, num_points, 2),假设为二维坐标 |
required |
Returns:
Type | Description |
---|---|
torch.Tensor: 输出特征张量,形状与输入x保持一致 |
Notes
使用Pointcept库处理点云数据,需要构造包含以下关键属性的data_dict: - feat: 展平后的特征矩阵 - batch: 批次数目索引 - coord: 包含三维坐标(添加z轴零值)的展平坐标 - grid_size: 体素化网格尺寸
batch2offset(batch)
批次索引转偏移量
binary2gray(binary, axis=-1)
Convert an array of binary values into Gray codes.
This uses the classic X ^ (X >> 1) trick to compute the Gray code.
binary: An ndarray of binary values.
axis: The axis along which to compute the gray code. Default=-1.
Returns an ndarray of Gray codes.
gray2binary(gray, axis=-1)
Convert an array of Gray codes back into binary values.
gray: An ndarray of gray codes.
axis: The axis along which to perform Gray decoding. Default=-1.
Returns an ndarray of binary values.
key2xyz(key, depth=16)
Decodes the shuffled key to :attr:x
, :attr:y
, :attr:z
coordinates
and the batch index based on pre-computed look up tables.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
Tensor
|
The shuffled key. |
required |
depth
|
int
|
The depth of the shuffled key, and must be smaller than 17 (< 17). |
16
|
offset2batch(offset)
偏移量转批次索引
offset2bincount(offset)
将偏移量转换为各批次点的数量
right_shift(binary, k=1, axis=-1)
Right shift an array of binary values.
binary: An ndarray of binary values.
k: The number of bits to shift. Default 1.
axis: The axis along which to shift. Default -1.
Returns an ndarray with zero prepended and the ends truncated, along whatever axis was specified.
xyz2key(x, y, z, b=None, depth=16)
Encodes :attr:x
, :attr:y
, :attr:z
coordinates to the shuffled keys
based on pre-computed look up tables. The speed of this function is much
faster than the method based on for-loop.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
The x coordinate. |
required |
y
|
Tensor
|
The y coordinate. |
required |
z
|
Tensor
|
The z coordinate. |
required |
b
|
Tensor or int
|
The batch index of the coordinates, and should be
smaller than 32768. If :attr: |
None
|
depth
|
int
|
The depth of the shuffled key, and must be smaller than 17 (< 17). |
16
|
ConvPointnet
Bases: Module
基于PointNet的编码器网络,每个点使用ResNet块进行特征提取。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
c_dim
|
int
|
潜在代码c的维度(默认512) |
512
|
dim
|
int
|
输入点的维度(默认3) |
3
|
hidden_dim
|
int
|
网络隐藏层维度(默认128) |
128
|
scatter_type
|
str
|
局部池化时的特征聚合方式('max'或'mean') |
'max'
|
unet
|
bool
|
是否使用UNet结构处理平面特征(默认True) |
True
|
unet_kwargs
|
dict
|
UNet参数配置(默认深度4,合并方式concat) |
{'depth': 4, 'merge_mode': 'concat', 'start_filts': 32}
|
plane_resolution
|
int
|
平面特征分辨率(默认64) |
64
|
plane_type
|
str
|
特征类型('xz'单平面,['xz','xy','yz']三平面,['grid']3D网格) |
['xz', 'xy', 'yz']
|
padding
|
float
|
坐标归一化时的填充系数(默认0.1) |
0.1
|
n_blocks
|
int
|
ResNet块数量(默认5) |
5
|
inject_noise
|
bool
|
是否注入噪声(默认False) |
False
|
coordinate2index(x, reso)
将归一化坐标转换为网格索引
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
归一化坐标 (B, T, 2) |
required |
reso
|
int
|
网格分辨率 |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
网格索引 (B, 1, T) |
forward(p, query)
前向传播主函数
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p
|
Tensor
|
输入点云 (B, T, 3) |
required |
query
|
Tensor
|
查询点坐标 (B, Q, 3) |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
聚合后的特征 (B, Q, c_dim) |
generate_plane_features(p, c, plane='xz')
生成指定平面的特征图
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p
|
Tensor
|
输入点云 (B, T, 3) |
required |
c
|
Tensor
|
点云特征 (B, T, c_dim) |
required |
plane
|
str
|
平面类型 ('xz','xy','yz') |
'xz'
|
Returns:
Name | Type | Description |
---|---|---|
Tensor |
平面特征图 (B, c_dim, reso, reso) |
normalize_coordinate(p, padding=0.1, plane='xz')
坐标归一化到[0,1]范围
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p
|
Tensor
|
输入坐标 (B, T, 3) |
required |
padding
|
float
|
填充系数 |
0.1
|
plane
|
str
|
平面类型 |
'xz'
|
Returns:
Name | Type | Description |
---|---|---|
Tensor |
归一化坐标 (B, T, 2) |
pool_local(xy, index, c)
局部特征池化操作
Parameters:
Name | Type | Description | Default |
---|---|---|---|
xy
|
dict
|
各平面归一化坐标 |
required |
index
|
dict
|
各平面网格索引 |
required |
c
|
Tensor
|
点云特征 (B, T, c_dim) |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
池化后的特征 (B, T, c_dim) |
sample_plane_feature(query, plane_feature, plane)
从平面特征图采样特征值
Parameters:
Name | Type | Description | Default |
---|---|---|---|
query
|
Tensor
|
查询点坐标 (B, Q, 3) |
required |
plane_feature
|
Tensor
|
平面特征图 (B, c_dim, reso, reso) |
required |
plane
|
str
|
平面类型 |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
采样后的特征 (B, Q, c_dim) |
DownConv
Bases: Module
下采样卷积块(Conv+ReLU+Conv+ReLU+MaxPool)
ResnetBlockFC
Bases: Module
全连接ResNet块
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size_in
|
int
|
输入维度 |
required |
size_out
|
int
|
输出维度 |
None
|
size_h
|
int
|
隐藏层维度 |
None
|
UNet
Bases: Module
二维UNet网络结构,用于平面特征处理
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_classes
|
int
|
输出通道数 |
required |
in_channels
|
int
|
输入通道数 |
3
|
depth
|
int
|
网络深度 |
5
|
start_filts
|
int
|
初始卷积核数量 |
64
|
up_mode
|
str
|
上采样方式 ('transpose'或'upsample') |
'transpose'
|
same_channels
|
bool
|
是否保持通道数不变 |
False
|
merge_mode
|
str
|
特征融合方式 ('concat'或'add') |
'concat'
|
forward(x)
前向传播
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
输入特征图 (B, C, H, W) |
required |
Returns:
Name | Type | Description |
---|---|---|
Tensor |
输出特征图 (B, num_classes, H, W) |
UpConv
Bases: Module
上采样卷积块(UpConv+Merge+Conv+ReLU+Conv+ReLU)
conv1x1(in_channels, out_channels, groups=1)
1x1卷积层
conv3x3(in_channels, out_channels, stride=1, padding=1, bias=True, groups=1)
3x3卷积层
upconv2x2(in_channels, out_channels, mode='transpose')
2x2上采样层
PointNetFeaturePropagation
Bases: Module
forward(xyz1, xyz2, points1, points2)
Input
xyz1: input points position data, [B, C, N] xyz2: sampled input points position data, [B, C, S] points1: input points data, [B, D, N] points2: input points data, [B, D, S]
Return: new_points: upsampled points data, [B, D', N]
PointNetSetAbstraction
Bases: Module
forward(xyz, points)
Input
xyz: input points position data, [B, C, N] points: input points data, [B, D, N]
Return: new_xyz: sampled points position data, [B, C, S] new_points_concat: sample points feature data, [B, D', S]
PointNetSetAbstractionMsg
Bases: Module
forward(xyz, points)
Input
xyz: input points position data, [B, C, N] points: input points data, [B, D, N]
Return: new_xyz: sampled points position data, [B, C, S] new_points_concat: sample points feature data, [B, D', S]
farthest_point_sample(xyz, npoint)
Input
xyz: pointcloud data, [B, N, 3] npoint: number of samples
Return: centroids: sampled pointcloud index, [B, npoint]
index_points(points, idx)
Input
points: input points data, [B, N, C] idx: sample index data, [B, S]
Return: new_points:, indexed points data, [B, S, C]
pca_with_svd(data, eps=1e-06)
PCA预测旋转正交矩阵
def pca_with_svd(data, n_components=3):
# 数据中心化
mean = torch.mean(data, dim=0)
centered_data = data - mean
# 执行 SVD
_, _, v = torch.linalg.svd(centered_data, full_matrices=False)
# 提取前 n_components 个主成分
components = v[:n_components]
return components
query_ball_point(radius, nsample, xyz, new_xyz)
Input
radius: local region radius nsample: max sample number in local region xyz: all points, [B, N, 3] new_xyz: query points, [B, S, 3]
Return: group_idx: grouped points index, [B, S, nsample]
query_knn(nsample, xyz, new_xyz, include_self=True)
Find k-NN of new_xyz in xyz
sample_and_group(npoint, radius, nsample, xyz, points, returnfps=False)
Input
npoint: radius: nsample: xyz: input points position data, [B, N, 3] points: input points data, [B, N, D]
Return: new_xyz: sampled points position data, [B, npoint, nsample, 3] new_points: sampled points data, [B, npoint, nsample, 3+D]
sample_and_group_all(xyz, points)
Input
xyz: input points position data, [B, N, 3] points: input points data, [B, N, D]
Return: new_xyz: sampled points position data, [B, 1, 3] new_points: sampled points data, [B, 1, N, 3+D]
sdf2mesh_by_diso(sdf, diffdmc=None, deform=None, return_quads=False, normalize=True, isovalue=0, invert=True)
用pytorch方式给,sdf 转换成 mesh
square_distance(src, dst)
Calculate Euclid distance between each two points.
src^T * dst = xn * xm + yn * ym + zn * zm; sum(src^2, dim=-1) = xnxn + ynyn + znzn; sum(dst^2, dim=-1) = xmxm + ymym + zmzm; dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2 = sum(src2,dim=-1)+sum(dst2,dim=-1)-2src^Tdst
Input
src: source points, [B, N, C] dst: target points, [B, M, C]
Output: dist: per-point square distance, [B, N, M]
ShapeVAE
Bases: Module
center_vertices(vertices)
staticmethod
Translate the vertices so that bounding box is centered at zero.
结合gridsample和conv3d处理点云数据 - anchor的文章 - 知乎 https://zhuanlan.zhihu.com/p/1894179743487743623
核心实现思路 体素化预处理:将无序点云映射到规则网格 特征提取:提取体素局部几何特征 动态网格采样:预测偏移量进行特征重采样 网格重建:生成规则拓扑结构
关键实现说明 体素化模块: 使用3D直方图统计点云分布 归一化坐标到[-1,1]区间 输出体素密度图 动态采样器: 通过3D卷积预测每个体素的偏移量 对基础网格进行非线性形变 grid_sample实现特征重采样 网格生成: 解码器输出体素占用概率 结合Marching Cubes算法生成三角面片(需配合PyMCubes等库)
性能优化技巧 稀疏体素处理: # 使用稀疏张量加速计算 sparse_voxel = voxel.to_sparse() 多尺度特征融合: # 添加多尺度采样路径 self.sampler2 = DynamicGridSampler(64, 3) 自适应网格密度: # 根据点密度调整网格分辨率 adaptive_grid_size = int(points.std() * 64)
DynamicGridSampler
Bases: Module
forward(voxel_feats)
输入:体素特征 [B,C,D,H,W] 输出:变形网格特征 [B,C,D,H,W]
PointCloudVoxelizer
Bases: Module
forward(points)
输入:点云 [B, N, 3] 输出:体素特征 [B, C, D, H, W]
报告模块API
Windows工具API
@path :sindre_package -> py2pyd.py
@IDE :PyCharm
@Author :sindre
@Email :yx@mviai.com
@Date :2024/6/17 16:32
@Version: V0.1
@License: (C)Copyright 2021-2023 , UP3D
@Reference:
ip_bind
Bases: Thread
实现本地0.0.0.0:8000 <--> 远程端口 内网穿透
set_ip(remote_ip, remote_port)
设置远程ip及端口
Parameters:
Name | Type | Description | Default |
---|---|---|---|
remote_ip
|
str
|
远程ip |
required |
remote_port
|
str
|
远程端口 |
required |
Returns:
tcp_mapping_qt
Bases: Thread
TCP 传输线程
check_port(port)
检测win端口是否被占用
Parameters:
Name | Type | Description | Default |
---|---|---|---|
port
|
int
|
端口号 |
required |
Returns:
Type | Description |
---|---|
bool
|
是否被占用 |
download_url_file(url, package_path='test.zip')
下载网络文件
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url
|
str
|
文件下载地址 |
required |
package_path
|
str
|
保存路径 |
'test.zip'
|
Returns:
Type | Description |
---|---|
bool
|
下载是否成功 |
exe2nsis(work_dir, files_to_compress, exe_name, appname='AI', version='1.0.0.0', author='SindreYang', license='', icon_old='')
将exe进行nsis封装成安装程序;
Notes
files_to_compress =[f"{self.work_dir}/{i}" for i in ["app", "py", "third", "app.exe", "app.py", "requirements.txt"]]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
work_dir
|
str
|
生成的路径 |
required |
files_to_compress
|
list
|
需要转换的文件夹/文件列表 |
required |
exe_name
|
str
|
指定主运行程序,快捷方式也是用此程序生成 |
required |
appname
|
str
|
产品名 |
'AI'
|
version
|
str
|
版本号--必须为 X.X.X.X |
'1.0.0.0'
|
author
|
str
|
作者 |
'SindreYang'
|
license
|
str
|
licence.txt协议路径 |
''
|
icon_old
|
str
|
图标 |
''
|
is_service_exists(service_name)
使用sc query命令来查询服务
Parameters:
Name | Type | Description | Default |
---|---|---|---|
service_name
|
str
|
服务名 |
required |
Returns:
Type | Description |
---|---|
bool
|
返回是否存在服务 |
kill_process_using_port(server_port)
请求管理员权限,并强制释放端口
Parameters:
Name | Type | Description | Default |
---|---|---|---|
server_port
|
int
|
端口号 |
required |
Returns:
Type | Description |
---|---|
bool
|
端口是否成功释放 |
pip_install(package_name='', target_dir='', requirements_path='')
模拟pip安装
Parameters:
Name | Type | Description | Default |
---|---|---|---|
package_name
|
str
|
包名 |
''
|
target_dir
|
str
|
安装目录,为空,则自动安装到当前环境下 |
''
|
requirements_path
|
str
|
requirementsTxT路径 |
''
|
py2pyd(source_path, clear_py=False)
将目录下所有py文件编译成pyd文件。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source_path
|
str
|
源码目录 |
required |
clear_py
|
bool
|
是否编译后清除py文件,注意备份。 |
False
|
python_installer(install_dir, version='3.9.6')
python自动化安装
Notes
默认从 https://mirrors.huaweicloud.com/python/{version}/python-{version}-embed-amd64.zip 下载安装
Parameters:
Name | Type | Description | Default |
---|---|---|---|
install_dir
|
str
|
安装位置 |
required |
version
|
str
|
版本号 |
'3.9.6'
|
zip_extract(zip_path, install_dir)
将zip文件解压
Args: zip_path: zip文件路径 install_dir: 解压目录
Returns:
Type | Description |
---|---|
bool
|
解压是否成功 |
set_windows_alpha(alpha=255, class_name='Shell_TrayWnd')
通过查找class_name,强制用于设置任务栏透明程度
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alpha
|
int
|
透明度,(0--完全透明,255--完全不透明) |
255
|
class_name
|
str
|
窗口名 |
'Shell_TrayWnd'
|
部署相关 API
OnnxInfer
__call__(inputs)
执行模型推理
__init__(onnx_path, providers=[('CPUExecutionProvider', {})], enable_log=False)
ONNX模型推理类,支持多种推理后端(CPU/GPU等)
参数
onnx_path: ONNX模型文件路径 providers: 推理提供者列表,格式为[(provider_name, options_dict), ...]
convert_opset_version(save_path, target_version)
转换ONNX模型的Opset版本 :param save_path: 保存路径 :param target_version: 目标Opset版本(如16)
dynamic_input_shape(save_path, dynamic_dims)
设置ONNX模型的输入为动态尺寸(支持多输入,None表示动态维度) :param dynamic_dims: 动态维度列表,如 [[None, 3, None, 480], [None, 3, None, 480]] 每个子列表对应一个输入的维度,None表示该维度动态可变
fix_input_shape(save_path, input_shapes)
固定ONNX模型的输入尺寸(支持多输入) :param save_path: 保存路径 :param input_shapes: 输入形状列表,如 [[1,3,416,480], [1,3,416,480]] or [[1,3,416,480]]
get_session(onnx_path, providers, enable_log=False)
加载并验证ONNX模型,创建推理会话
optimizer(save_onnx)
优化并简化ONNX模型
test_performance(loop=10, warmup=3)
测试模型推理速度
SimpleSharedMemory
get_status()
获取状态标志
read()
读取数据并清空内存
set_status(status)
设置状态标志:0-空,1-已写入
write(array)
写入数据,如果内存未清空则等待
TRTInfer
__call__(data)
执行推理
build_engine(onnx_path, engine_path, max_workspace_size=4 << 30, fp16=False, dynamic_shape_profile=None, hardware_compatibility='', optimization_level=3, version_compatible=False)
从ONNX模型构建TensorRT引擎
参数
onnx_path (str): ONNX模型路径 engine_path (str, optional): 引擎保存路径 max_workspace_size (int, optional): 最大工作空间大小,默认为4GB fp16 (bool, optional): 是否启用FP16精度 dynamic_shape_profile (dict, optional): 动态形状配置,格式为: { "input_name": { "min": (1, 3, 224, 224), # 最小形状 "opt": (4, 3, 224, 224), # 优化形状 "max": (8, 3, 224, 224) # 最大形状 } } hardware_compatibility (str, optional): 硬件兼容性级别,可选值: - "": 默认(最快) - "same_sm": 相同计算能力(其次) - "ampere_plus": Ampere及更高架构(最慢) Pascal(10系)、Volta(V100)、Turing(20系)、Ampere(30系)、 Ada(40系)、Hopper(H100)、Blackwell(50系) optimization_level (int): 优化级别,默认最优级别3; ・等级0:通过禁用动态内核生成并选择执行成功的第一个策略,实现最快的编译。这也不会考虑计时缓存。 ・等级1:可用策略按启发式方法排序,但仅测试排名靠前的策略以选择最佳策略。如果生成动态内核,其编译优化程度较低。 ・等级2:可用策略按启发式方法排序,但仅测试最快的策略以选择最佳策略。 ・等级3:应用启发式方法,判断静态预编译内核是否适用,或者是否必须动态编译新内核。 ・等级4:始终编译动态内核。 ・等级5:始终编译动态内核,并将其与静态内核进行比较。 version_compatible (bool): 是否启用版本兼容模式(8.6构建的引擎可以在10.x上运行)
load_model(engine_path)
从TensorRT引擎文件加载模型
test_performance(loop=10, warmup=3)
测试推理性能(自动生成随机输入)
参数
loop: 正式测试循环次数 warmup: 预热次数
grid_sample(input, grid, align_corners=True)
自适应版本的grid_sample,根据输入维度自动选择2D或3D实现
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
Tensor
|
输入图像 - 对于2D采样: 形状为 (N, C, H, W) - 对于3D采样: 形状为 (N, C, D, H, W) |
required |
grid
|
Tensor
|
采样网格 - 对于2D采样: 形状为 (N, Hg, Wg, 2) - 对于3D采样: 形状为 (N, D_out, H_out, W_out, 3) |
required |
align_corners
|
bool
|
坐标归一化方式,与F.grid_sample的align_corners参数含义一致 |
True
|
Returns:
Type | Description |
---|---|
torch.Tensor: 采样结果 - 对于2D采样: 形状为 (N, C, Hg, Wg) - 对于3D采样: 形状为 (N, C, D_out, H_out, W_out) |
Raises:
Type | Description |
---|---|
ValueError
|
如果输入维度不是4D(2D)或5D(3D) |
ValueError
|
如果grid的最后一维不是2(2D)或3(3D) |
Notes
该函数根据输入维度自动调用grid_sample_2d或grid_sample_3d 等效于PyTorch的F.grid_sample,padding_mode='zeros'
grid_sample_2d(im, grid, align_corners=False)
2D版本的grid_sample,使用双线性插值对输入像素进行采样
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im
|
Tensor
|
输入特征图,形状 (N, C, H, W) |
required |
grid
|
Tensor
|
点坐标,形状 (N, Hg, Wg, 2),最后一维是(x,y)坐标 |
required |
align_corners
|
bool
|
坐标归一化方式,与F.grid_sample的align_corners参数含义一致 |
False
|
Returns:
Type | Description |
---|---|
torch.Tensor: 采样结果,形状为 (N, C, Hg, Wg) |
Notes
等效于PyTorch的F.grid_sample,padding_mode='zeros'
grid_sample_3d(image, grid, align_corners=False)
3D版本的grid_sample,功能等同于F.grid_sample(image, grid_3d, align_corners=True) 支持align_corners参数,控制坐标归一化方式
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Tensor
|
输入图像,形状为 (N, C, D, H, W) |
required |
grid
|
Tensor
|
采样网格,形状为 (N, D_out, H_out, W_out, 3),最后一维是(x,y,z)坐标 |
required |
align_corners
|
bool
|
坐标归一化方式,与F.grid_sample的align_corners参数含义一致 |
False
|
Returns:
Type | Description |
---|---|
torch.Tensor: 采样结果,形状为 (N, C, D_out, H_out, W_out) |
Notes
等效于PyTorch的F.grid_sample,padding_mode='zeros'
日志工具 API
CustomLogger
一个使用 loguru 库的自定义日志记录器类,支持多进程、print重定向、日志分级存储等。
Attributes:
Name | Type | Description |
---|---|---|
logger |
logger
|
配置好的 loguru 日志记录器实例。 |
__init__(logger_name=None, level='DEBUG', log_dir='logs', console_output=True, file_output=False, capture_print=False, filter_log=None)
初始化 CustomLogger。
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logger_name
|
str
|
日志记录器名称。 |
None
|
level
|
str
|
日志级别,默认为 'DEBUG'。 |
'DEBUG'
|
log_dir
|
str
|
日志文件存储目录。 |
'logs'
|
console_output
|
bool
|
是否启用控制台输出。 |
True
|
file_output
|
bool
|
是否启用文件输出。 |
False
|
capture_print
|
bool
|
是否捕获 print 输出。 |
False
|
filter_log
|
callable
|
自定义日志过滤函数。 |
None
|
get_logger()
获取配置好的日志记录器实例。