Extract submatrix at certain row/col values

拜拜、爱过 提交于 2021-02-16 19:03:07

问题


I need to slice a 2D input array from row/col indices and a slicing distance. In my example below, I can extract a 3x3 submatrix from an input matrix, but I cannot adapt this code to work for any search distance I would like, without resorting to manually writing down the indices:

Example:

import numpy as np

# create matrix
mat_A = np.arange(100).reshape((10, 10))

row = 5
col = 5

# Build 3x3 matrix around the centre point
matrix_three = ((row - 1, col - 1),
                (row, col - 1),
                (row + 1, col - 1),
                (row - 1, col),
                (row, col),  # centre point
                (row + 1, col),
                (row - 1, col + 1),
                (row, col + 1),
                (row + 1, col + 1))

list_matrix_max_values = []

for loc in matrix_three:
    val = mat_A[loc[0]][loc[1]]
    list_matrix_max_values.append(val)


submatrix = np.matrix(list_matrix_max_values)
print(submatrix)

Returns:

[[44 54 64 45 55 65 46 56 66]]

How can I do the same thing if i would like for example to extract a 5x5 matrix around the cell defined by my row/col indices? Thanks in advance!


回答1:


S=3 # window "radius"; S=3 gives a 5x5 submatrix
mat_A[row-S+1:row+S,col-S+1:col+S]
#array([[33, 34, 35, 36, 37],
#       [43, 44, 45, 46, 47],
#       [53, 54, 55, 56, 57],
#       [63, 64, 65, 66, 67],
#       [73, 74, 75, 76, 77]])



回答2:


Numpy has matrix slicing, so you can slice on both rows and columns.

mat_A[4:7, 4:7]

returns

  [[44, 45, 46],
   [54, 55, 56],
   [64, 65, 66]]


来源:https://stackoverflow.com/questions/48329672/extract-submatrix-at-certain-row-col-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!