【问题标题】:How do I merge several 2D arrays into a single 2D array (list) in a box-like manner in python?如何在 python 中以类似盒子的方式将几个 2D 数组合并为一个 2D 数组(列表)?
【发布时间】:2021-06-07 06:13:42
【问题描述】:

假设我有 9 个二维数组,格式如下:

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 ]]

我想将它们连接起来得到一个像这样的二维数组:

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 数组中作为原始图像。我该怎么做?

【问题讨论】:

    标签: python arrays list numpy image-processing


    【解决方案1】:

    这似乎是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.]])
    

    【讨论】:

    • 是的,bmat 很好,但在我的场景中,虽然我准备好了 numpy 数组,但我不会总是得到 9。我什至可能得到 10、11、12...,具体取决于原始图像的尺寸。可能有 5x2 块或 3x3 块或 3x4 块。那么在那种情况下,我该如何使用 bmat?
    • 在答案中添加了一个示例。
    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 2020-03-21
    • 2021-06-04
    • 2011-05-19
    • 2019-02-07
    • 2020-06-25
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多