从NumPy数组中提取块或补丁 [英] Extract blocks or patches from NumPy Array

查看:164
本文介绍了从NumPy数组中提取块或补丁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维numpy数组,如下所示:

I have a 2-d numpy array as follows:

a = np.array([[1,5,9,13],
              [2,6,10,14],
              [3,7,11,15],
              [4,8,12,16]]

我想将其提取为2 x 2大小的小块,而无需重复元素.

I want to extract it into patches of 2 by 2 sizes with out repeating the elements.

答案应该完全相同.可以是3维数组,也可以是具有以下元素顺序的列表:

[[[1,5],
 [2,6]],   

 [[3,7],
 [4,8]],

 [[9,13],
 [10,14]],

 [[11,15],
 [12,16]]]

如何轻松做到?

在我的实际问题中,a的大小为(36,72).我不能一一做到.我想要编程的方式.

In my real problem the size of a is (36, 72). I can not do it one by one. I want programmatic way of doing it.

推荐答案

这是一个相当隐秘的numpy单层代码,用于生成3-d数组,在这里称为result1:

Here's a rather cryptic numpy one-liner to generate your 3-d array, called result1 here:

In [60]: x
Out[60]: 
array([[2, 1, 2, 2, 0, 2, 2, 1, 3, 2],
       [3, 1, 2, 1, 0, 1, 2, 3, 1, 0],
       [2, 0, 3, 1, 3, 2, 1, 0, 0, 0],
       [0, 1, 3, 3, 2, 0, 3, 2, 0, 3],
       [0, 1, 0, 3, 1, 3, 0, 0, 0, 2],
       [1, 1, 2, 2, 3, 2, 1, 0, 0, 3],
       [2, 1, 0, 3, 2, 2, 2, 2, 1, 2],
       [0, 3, 3, 3, 1, 0, 2, 0, 2, 1]])

In [61]: result1 = x.reshape(x.shape[0]//2, 2, x.shape[1]//2, 2).swapaxes(1, 2).reshape(-1, 2, 2)

result1就像2维数组的1维数组:

result1 is like a 1-d array of 2-d arrays:

In [68]: result1.shape
Out[68]: (20, 2, 2)

In [69]: result1[0]
Out[69]: 
array([[2, 1],
       [3, 1]])

In [70]: result1[1]
Out[70]: 
array([[2, 2],
       [2, 1]])

In [71]: result1[5]
Out[71]: 
array([[2, 0],
       [0, 1]])

In [72]: result1[-1]
Out[72]: 
array([[1, 2],
       [2, 1]])

(对不起,我现在没有时间详细介绍其工作方式.也许以后...)

(Sorry, I don't have time at the moment to give a detailed breakdown of how it works. Maybe later...)

这是一个使用嵌套列表推导的不太隐秘的版本.在这种情况下,result2是二维numpy数组的python列表:

Here's a less cryptic version that uses a nested list comprehension. In this case, result2 is a python list of 2-d numpy arrays:

In [73]: result2 = [x[2*j:2*j+2, 2*k:2*k+2] for j in range(x.shape[0]//2) for k in range(x.shape[1]//2)]

In [74]: result2[5]
Out[74]: 
array([[2, 0],
       [0, 1]])

In [75]: result2[-1]
Out[75]: 
array([[1, 2],
       [2, 1]])

这篇关于从NumPy数组中提取块或补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆