numpy 如何在python中以类似盒子的方式将多个2D数组合并为一个2D数组(列表)?

vmdwslir  于 2023-04-06  发布在  Python
关注(0)|答案(1)|浏览(185)

假设我有9个2D数组,格式如下:

A1 = [[ a1, b1, c1 ],
      [ d1, e1, f1 ],
      [ g1, h1, i1 ]]

A2 = [[ a2, b2, c2 ],
      [ d2, e2, f2 ],
      [ g2, h2, i2 ]] 
.....
A9 = [[ a9, b9, c9 ],
      [ d9, e9, f9 ],
      [ g9, h9, i9 ]]

我想把它们连接起来,得到一个像这样的2D数组:

A = [B1, B2, B3]

何处

B1 = np.concatenate((A1,A2, A3),axis=1) 
B2 = np.concatenate((A4,A5, A6),axis=1) 
B3 = np.concatenate((A7,A8, A9),axis=1)

在我的例子中,我有N个数组,我计算N的值如下:

img = Image.open(file_name)
img_width, img_height = img.size

tile_height = int(input('Enter the height of tile:'))
tile_width = int(input('Enter the width of tile:'))

N = (img_height//tile_height)*(img_width//tile_width)

# **The image will be broken down into n tiles of size tile_width x tile_height**

for i in range(img_height//tile_height):
    for j in range(img_width//tile_width):
         box = (j*width, i*height, (j+1)*width, (i+1)*height)
         img.crop(box)
         ...

因此,本质上,我有一个被分解为N个图块的图像,经过一些处理,我将这些图像图块数据存储为numpy数组,我想将它们连接/合并到一个与原始图像相同方向的2D numpy数组中。我如何做到这一点?

cetgtptt

cetgtptt1#

这似乎是bmat的完美用例

编辑:如何使用bmat

BMAT接受块矩阵作为第一自变量。

[[A11, A12, ..., A1n]
 [A21, A22, ..., A2n]
 ...
 [Am1, Am2, ..., Amn]]

并且不限于9个子矩阵的情况,在bmat文档中,他们的示例与您问题中的示例大小相同,这是一个巧合。

import numpy as np;
mats = []
for i in range(10):
    mats.append(np.ones((4, 2)) * i);
np.bmat([mats[:5], mats[5:]])

给予

matrix([[0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
        [0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
        [0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
        [0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
        [5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
        [5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
        [5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
        [5., 5., 6., 6., 7., 7., 8., 8., 9., 9.]])

相关问题