我如何恢复从使用numpy.lib.stride_tricks.as_strided到另一个ndarray所获得的ndarray

时间:2018-11-24 06:40:43

标签: python-3.x numpy numpy-ndarray

import numpy as np
sudoku = np.array([   
    [2, 8, 7, 1, 6, 5, 9, 4, 3],
    [9, 5, 4, 7, 3, 2, 1, 6, 8],
    [6, 1, 3, 8, 4, 9, 7, 5, 2],
    [8, 7, 9, 6, 5, 1, 2, 3, 4],
    [4, 2, 1, 3, 9, 8, 6, 7, 5],
    [3, 6, 5, 4, 2, 7, 8, 9, 1],
    [1, 9, 8, 5, 7, 3, 4, 2, 6],
    [5, 4, 2, 9, 1, 6, 3, 8, 7],
    [7, 3, 6, 2, 8, 4, 5, 1, 9]
])
shape = (3, 3, 3, 3)
strides = sudoku.itemsize * np.array([27, 3, 9, 1])
squares = np.lib.stride_tricks.as_strided(sudoku, shape=shape, strides=strides) 
print(squares)

'''
[[[[2 8 7]    [9 5 4]    [6 1 3]]
  [[1 6 5]    [7 3 2]    [8 4 9]]
  [[9 4 3]    [1 6 8]    [7 5 2]]]

 [[[8 7 9]    [4 2 1]    [3 6 5]]
  [[6 5 1]    [3 9 8]    [4 2 7]]
  [[2 3 4]    [6 7 5]    [8 9 1]]]

 [[[1 9 8]    [5 4 2]    [7 3 6]]
  [[5 7 3]    [9 1 6]    [2 8 4]]
  [[4 2 6]    [3 8 7]    [5 1 9]]]]
'''

squares是一个四维数组,我想通过一些操作来处理它,但是如何将平方恢复到数独?

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是

from numpy import hstack
sudoku= hstack(hstack(squares))

请注意,skimage.util.view_as_blocks执行直接操作:

rows=skimage.util.view_as_blocks(sudoku,(1,9))
cols=skimage.util.view_as_blocks(sudoku,(9,1))
blks=skimage.util.view_as_blocks(sudoku,(3,3))

sudoku= hstack(hstack())颠倒了三种表示形式。