在Python中提取多个子矩阵
如果我的稀疏矩阵有多个非零值区域,我将尝试提取多个子矩阵 比如说,, 假设我有以下矩阵:在Python中提取多个子矩阵,python,indexing,Python,Indexing,如果我的稀疏矩阵有多个非零值区域,我将尝试提取多个子矩阵 比如说,, 假设我有以下矩阵: x = np.array([0,0,0,0,0,0], [0,1,1,0,0,0], [0,1,1,0,0,1], [0,0,0,0,1,1], [0,0,0,0,1,0]) 然后我需要能够提取非零值的区域,即 x_1 = [[1,1] [1,1]] 及 我一直在使用np.where()
x = np.array([0,0,0,0,0,0],
[0,1,1,0,0,0],
[0,1,1,0,0,1],
[0,0,0,0,1,1],
[0,0,0,0,1,0])
然后我需要能够提取非零值的区域,即
x_1 = [[1,1]
[1,1]]
及
我一直在使用np.where()查找非零值的索引,并仅返回一个子矩阵的区域,但如何将其扩展到稀疏矩阵中所有可能的子区域
谢谢 程序:
您可以为此使用内置程序
from scipy.ndimage.measurements import find_objects, label
from scipy.ndimage import generate_binary_structure as gbs
import numpy as np
# create array
x = np.array([[0,0,0,0,0,0],
[0,1,1,0,0,0],
[0,1,1,0,0,1],
[0,0,0,0,1,1],
[0,0,0,0,1,0]])
# define labeling structure to inlcude adjacent (including diagonal) cells
struc = gbs(2,2)
# generate array of labeled sections labels
x2, numlabels = label(x,struc)
# pull out first group of "ones"
xy1 = find_objects(x2==1)[0]
# pull out second group of "ones"
xy2 = find_objects(x2==2)[0]
现在测试:
>>> x[xy1]
array([[1, 1],
[1, 1]])
>>> x[xy2]
array([[0, 1],
[1, 1],
[1, 0]])
瞧!如果您想取出所有可以迭代的子部分,这会告诉您数组中有多少个不同的组。谢谢,但全局定义有一个错误:NameError:全局名称“res”不是definedIt也似乎不适用于任何两个子矩阵的一般情况。@alvarezcl,首先需要在主函数中定义
res=[]
。我已经上传了完整的代码。试试看。此外,它适用于两个子矩阵的任何情况。我已经在很多情况下对它进行了测试。这实际上比国际海事组织认可的解决方案更好。
from scipy.ndimage.measurements import find_objects, label
from scipy.ndimage import generate_binary_structure as gbs
import numpy as np
# create array
x = np.array([[0,0,0,0,0,0],
[0,1,1,0,0,0],
[0,1,1,0,0,1],
[0,0,0,0,1,1],
[0,0,0,0,1,0]])
# define labeling structure to inlcude adjacent (including diagonal) cells
struc = gbs(2,2)
# generate array of labeled sections labels
x2, numlabels = label(x,struc)
# pull out first group of "ones"
xy1 = find_objects(x2==1)[0]
# pull out second group of "ones"
xy2 = find_objects(x2==2)[0]
>>> x[xy1]
array([[1, 1],
[1, 1]])
>>> x[xy2]
array([[0, 1],
[1, 1],
[1, 0]])