在Python中提取多个子矩阵
我想从一个稀疏矩阵中提取多个子矩阵,前提是这个矩阵里有多个非零值的区域。
比如说,我有下面这个矩阵:
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]]
还有:
x_2 = [[0,1],
[1,1],
[1,0]]
我之前一直在用np.where()来找到非零值的索引,并且只返回一个子矩阵的区域,但我该如何扩展这个方法,以便提取出我稀疏矩阵中的所有可能的子区域呢?
谢谢!
2 个回答
3
你可以使用内置的功能来做到这一点。
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]])
太好了!如果你想提取所有的小部分,你可以逐个查看,这样就能知道数组里有多少个不同的组。
7
步骤:
- 删除所有边缘的行和列,如果它们全是零。(中间的行和列不动)
- 找出所有空的行和列,然后根据这些位置把矩阵分开。这会生成一个矩阵的列表。
- 对每个新生成的矩阵,重复这个过程,直到不能再分割为止。
代码:
def delrc(arr):
while True: # delete leading rows with all zeros
if np.all(arr[0]==0):
arr=np.delete(arr,0,axis=0)
else: break
while True: # delete trailing rows with all zeros
if np.all(arr[-1]==0):
arr=np.delete(arr,-1,axis=0)
else: break
while True: # delete leading cols with all zeros
if np.all(arr[:,0]==0):
arr=np.delete(arr,0,axis=1)
else: break
while True: # delete trailing cols with all zeros
if np.all(arr[:,-1]==0):
arr=np.delete(arr,-1,axis=1)
else: break
return arr
def rcsplit(arr):
if np.all(arr==0): return [] # if all zeros return
global res
arr = delrc(arr) # delete leading/trailing rows/cols with all zeros
print arr
indr = np.where(np.all(arr==0,axis=1))[0]
indc = np.where(np.all(arr==0,axis=0))[0]
if not indr and not indc: # If no further split possible return
res.append(arr)
return
arr=np.delete(arr,indr,axis=0) #delete empty rows in between non empty rows
arr=np.delete(arr,indc,axis=1) #delete empty cols in between non empty cols
arr=np.split(arr,indc,axis=1) # split on empty (all zeros) cols
print arr
arr2=[]
for i in arr:
z=delrc(i)
arr2.extend(np.split(z,indr,axis=0)) # split on empty (all zeros) rows
for i in arr2:
rcsplit(np.array(i)) # recursive split again no further splitting is possible
if __name__=="__main__":
import numpy as np
res = []
arr = 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]])
rcsplit(arr)
for i in res: print i