如何在二维Numpy数组指定区域获取最大N个值的全局索引?
解决方法
你可以通过将局部索引转换为切片内的二维坐标,再叠加切片的起始偏移量,得到原数组的全局索引。具体实现步骤如下:
步骤拆解
生成切片区域的全局坐标网格
先构建切片区域对应的全局行、列索引矩阵,让切片内的每个位置都能直接映射到原数组的全局索引:# 生成切片覆盖的全局行、列范围 roi_rows = np.arange(top, bottom) roi_cols = np.arange(left, right) # 生成与切片形状一致的全局坐标网格(行优先索引) grid_rows, grid_cols = np.meshgrid(roi_rows, roi_cols, indexing='ij')将扁平化局部索引转为二维局部坐标
使用np.unravel_index把扁平化后的局部索引,还原为切片内的二维(行、列)索引:# 把扁平化局部索引转换为切片内的二维坐标 local_rows, local_cols = np.unravel_index(ind, depthRoi.shape)提取全局索引
从预先生成的坐标网格中,直接获取对应位置的全局行、列索引:# 获取全局行、列索引 global_rows = grid_rows[local_rows, local_cols] global_cols = grid_cols[local_rows, local_cols]整理结果格式
可以将全局索引组合成你需要的形式,比如元组列表或二维数组:# 组合为(行, 列)形式的索引列表 global_indices = list(zip(global_rows, global_cols))
完整代码示例
import numpy as np # 示例原数组与切片参数 depthFrame = np.random.rand(100, 100) # 100×100的随机数组 top, bottom, left, right = 20, 80, 30, 70 # 目标切片范围 # 提取目标切片并处理局部索引 depthRoi = depthFrame[top:bottom, left:right] depthRoiFlat = depthRoi.flatten() ind = np.argpartition(depthRoiFlat, -1000)[-1000:] # 切片内最大1000个值的局部扁平化索引 # 转换为全局索引 roi_rows = np.arange(top, bottom) roi_cols = np.arange(left, right) grid_rows, grid_cols = np.meshgrid(roi_rows, roi_cols, indexing='ij') local_rows, local_cols = np.unravel_index(ind, depthRoi.shape) global_rows = grid_rows[local_rows, local_cols] global_cols = grid_cols[local_rows, local_cols] # 输出结果示例 global_indices = np.stack((global_rows, global_cols), axis=1) print(global_indices[:5]) # 打印前5个全局索引
补充优化
如果需要按值从大到小排序全局索引,可以在获取局部索引后增加排序步骤:
# 按切片内数值从大到小排序局部索引 sorted_ind = ind[np.argsort(-depthRoiFlat[ind])] # 转换为排序后的全局索引 local_rows_sorted, local_cols_sorted = np.unravel_index(sorted_ind, depthRoi.shape) global_rows_sorted = grid_rows[local_rows_sorted, local_cols_sorted] global_cols_sorted = grid_cols[local_rows_sorted, local_cols_sorted]
内容的提问来源于stack exchange,提问作者sharkyenergy
相关产品推荐
相关产品推荐

