python - numpy 2d 区域的快速随机到唯一重新标记(无循环)

标签 python arrays numpy scipy vectorization

我有一个大的 numpy 二维数组 (10000,10000),其中的区域(具有相同数量的细胞簇)被随机标记。结果,一些单独的区域被分配到相同的标签。我想要的是重新标记 numpy 二维数组,以便所有单独的区域都分配给一个唯一的标签(参见示例)。

我现在如何用循环解决这个问题。但是由于我正在处理一个包含许多小区域的大型阵列,所以这个过程需要很长时间。因此,矢量化方法会更合适。

例子:

-两个独立的区域用1标记
-两个独立的区域 标有 3

## Input
random_arr=np.array([[1,1,3,3],[1,2,2,3],[2,2,1,1],[3,3,3,1]])

random

## Apply function
unique_arr=relabel_regions(random_arr)
## Output
>>> unique_arr
array([[1, 1, 3, 3],
       [1, 2, 2, 3],
       [2, 2, 4, 4],
       [5, 5, 5, 4]])

unique

带循环的慢速解决方案:

def relabel_regions(random_regions):
    # Locate random regions index
    random_labs=np.unique(random_regions)

    unique_segments=np.zeros(np.shape(random_regions),dtype='uint64')
    count=0
    kernel=np.array([[0,1,0],[1,1,1],[0,1,0]],dtype='uint8')
    # Assign unique number to each random labeled region
    for i in range(len(random_labs)):
        mask=np.zeros(np.shape(random_regions))
        mask[np.where(random_regions==random_labs[i])]=1
        labeled_mask, freq = ndimage.label(mask, structure=kernel)
        labeled_mask=labeled_mask+count
        unique_segments[np.where(labeled_mask>0+count)]=labeled_mask[np.where(labeled_mask>0+count)]
        count+=freq
    return unique_segments

最佳答案

让我们作弊,只使用一些提供此功能的高质量库 ( scikit-image)。

您可以从它的实现中学习或直接使用它!

import numpy as np
from skimage.measure import label

random_arr = np.array([[1,1,3,3],[1,2,2,3],[2,2,1,1],[3,3,3,1]])
labels = label(random_arr, connectivity=1)  # neighborhood-definition here!

print(labels)

输出

[[1 1 2 2]
 [1 3 3 2]
 [3 3 4 4]
 [5 5 5 4]]

编辑: 正如 Jeon 在评论中提到的,scipy 的 scipy.ndimage.measurements.label如果不想再使用一个额外的库,也可能是一个候选人!感谢 Jeon 的评论!

关于python - numpy 2d 区域的快速随机到唯一重新标记(无循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613884/

相关文章:

Javascript - 播放声音以及数组中的随机值

javascript - 创建 Letter 字符串和字符串长度

python re match, findall or search 然后NLP(用它做什么?)

python - 为什么所有 twisted/wokkel xmpp 示例都忽略了 xmpp 协议(protocol)中 JID 的正确用法?

python - Pandas 绘制一组

python - 时间数据 '2015-02-10T13:00:00Z' 与格式 '%Y-%m-%d %H:%M:%S' 不匹配

java - 从 Java 转换为 Python

python - 三角形 Numpy 切片

python - pandas系列上的短路numpy逻辑_and

python - Opencv写视频正在运行,但保存的output.avi文件为0KB