利用numpy对稠密点集进行降采样,最直接且高效的方法是基于网格的均匀采样(grid-based downsampling)。具体做法是将所有点的坐标除以目标网格的尺寸,取整后作为索引,然后使用`np.unique`或字典去重保留每个网格单元内的一个代表点。这种方法避免了python层面的循环,完全依赖numpy的向量化操作,能够显著降低数据量同时保持空间分布的均匀性。

如何基于固定网格尺寸实现均匀降采样
通过设定一个固定的网格边长(例如0.5米),可以将连续的空间离散化为离散的单元格。对于输入的点集,计算每个点所属的网格索引,然后提取唯一的索引组合,最后将这些索引映射回原始点集中的某个点(通常取第一个遇到的点)作为该网格的代表。这样得到的点集在空间上是均匀分布的,且数量由网格密度决定。

import numpy as np
def grid_downsample(points, cell_size):
# points: (N, 2) or (N, 3) array
# cell_size: float, size of the grid cell
# 1. Calculate grid indices
grid_indices = np.floor(points / cell_size).astype(int)
# 2. Find unique grid cells and their first occurrence indices
# We need to map each unique grid index back to the original point index
unique_indices, inverse_indices = np.unique(grid_indices, axis=0, return_index=True)
# 3. Return the downsampled points
return points[inverse_indices]
# Example usage:
# Generate 100,000 random points in a 10x10 area
np.random.seed(42)
points = np.random.rand(100000, 2) * 10
# Downsample with a grid size of 0.5
downsampled_points = grid_downsample(points, 0.5)
print(f"Original points: {len(points)}")
print(f"Downsampled points: {len(downsampled_points)}")
如何基于固定点数进行随机降采样
如果应用场景要求严格限制输出点的数量(例如为了匹配特定的传感器分辨率或内存限制),可以使用随机抽样而不替换(Random Sampling Without Replacement)。虽然这不能保证空间均匀性,但在点集分布相对均匀时,它能快速减少数据量。结合NumPy的`np.random.choice`可以高效实现。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import numpy as np
def random_downsample(points, num_samples):
# points: (N, D) array
# num_samples: int, number of points to keep
if num_samples >= len(points):
return points
# Generate random indices
indices = np.random.choice(len(points), size=num_samples, replace=False)
# Return the sampled points
return points[indices]
# Example usage:
# Using the same 100,000 points from before
num_to_keep = 1000
randomly_downsampled_points = random_downsample(points, num_to_keep)
print(f"Randomly downsampled points: {len(randomly_downsampled_points)}")
当点集存在高度聚集区域时降采样效果如何
当点集存在高度聚集区域(如密集的云团或边缘)时,均匀网格降采样会保留这些区域的代表性点,但可能会丢失一些细微结构,因为多个点会被映射到同一个网格单元中。相比之下,随机降采样可能会偶然遗漏稀疏区域的重要点,或者在密集区域过度采样。为了处理这种情况,可以先对点进行聚类或使用自适应网格方法,但这会增加计算复杂度。在实际应用中,如果聚集区域是关键信息所在,建议先可视化点集分布,再选择合适的网格尺寸或采用分层采样策略。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










