【问题标题】:How can I find groups in an array?如何在数组中找到组?
【发布时间】:2020-09-28 17:05:13
【问题描述】:

我有一个包含1 小组和1 大组的二进制 3d 数组。我想搜索数组,当找到1 时,我想搜索x,y,z 方向中的周围值并计算连接了多少1。如果x 的数量少于1,我想将该组设置为0。整个3d 数组由10 组成。

数组示例:

img  = np.array([[[0,0,0,1,0],
                  [0,0,0,1,1]],
                 [[0,0,0,1,0],
                  [0,0,0,0,0]]])

在 x,y,z 方向上有一组1 直接相邻。在我的这个场景的代码中,该组是num_group = 4。由于该组小于 10,我想将该组设为 0

img  = np.array([[[0,0,0,0,0],
                  [0,0,0,0,0]],
                 [[0,0,0,0,0],
                  [0,0,0,0,0]]])

我的数组中有 1-2 个非常大且不同的组。我只想在我的最终数组中包含这些大组。

import nibabel as nib
import numpy as np
import os, sys

x = 10

img = nib.load(\\test.nii).get_fdata()
print(img.shape)
>>>(512,512,30)
size_x, size_y, size_z = vol.shape

for z_slices in range(size_z):
    for y_slices in range(size_y):
        for x_slices in range(size_x):
            num_group = (Find a 1 and count how many 1s are connected)
            if num_group < x:
                num_group = 0

【问题讨论】:

  • 代码与问题的关系如何?
  • 你如何定义“组”?我们在谈论什么类型的连接?
  • 只做卷积可以吗?
  • @MadPhysicist 我只是在展示我目前的方法/思考过程。我愿意接受任何方法。
  • 您的代码和散文已断开连接。详细描述你想要什么,并解释代码是如何实现/不实现的。否则就没什么问题了。

标签: python arrays numpy multidimensional-array nibabel


【解决方案1】:

您可以为此使用 skimage:

from skimage.measure import regionprops,label
sz = 10  #this is your set threshold
xyz = np.vstack([i.coords for i in regionprops(label(img)) if i.area<sz]) #finding regions and coordinates of regions smaller than threshold
img[tuple(xyz.T)]=0 #setting small regions to 0

输出:

[[[0 0 0 0 0]
  [0 0 0 0 0]]

 [[0 0 0 0 0]
  [0 0 0 0 0]]]

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多