Say I have 9 2D arrays in the following format:
JavaScript
x
12
12
1
A1 = [[ a1, b1, c1 ],
2
[ d1, e1, f1 ],
3
[ g1, h1, i1 ]]
4
5
A2 = [[ a2, b2, c2 ],
6
[ d2, e2, f2 ],
7
[ g2, h2, i2 ]]
8
..
9
A9 = [[ a9, b9, c9 ],
10
[ d9, e9, f9 ],
11
[ g9, h9, i9 ]]
12
and I want to concatenate them to get a 2D array like this:
JavaScript
1
2
1
A = [B1, B2, B3]
2
where
JavaScript
1
4
1
B1 = np.concatenate((A1,A2, A3),axis=1)
2
B2 = np.concatenate((A4,A5, A6),axis=1)
3
B3 = np.concatenate((A7,A8, A9),axis=1)
4
I will have N arrays in my case and I calculate the value of N like so:
JavaScript
1
16
16
1
img = Image.open(file_name)
2
img_width, img_height = img.size
3
4
tile_height = int(input('Enter the height of tile:'))
5
tile_width = int(input("Enter the width of tile:'))
6
7
N = (img_height//tile_height)*(img_width//tile_width)
8
9
# **The image will be broken down into n tiles of size tile_width x tile_height**
10
11
for i in range(img_height//tile_height):
12
for j in range(img_width//tile_width):
13
box = (j*width, i*height, (j+1)*width, (i+1)*height)
14
img.crop(box)
15
16
So essentially, I had an image that was broken down into N tiles and after some processing, I have these image tile data stored as numpy arrays and I want to concatenate/merge them into a single 2D numpy array in the same orientation as the original image. How can I do that?
Advertisement
Answer
This seems a perfect use case for bmat
Edit: How to use bmat
bmat accepts as the first argument a matrix of blocks.
JavaScript
1
5
1
[[A11, A12, , A1n]
2
[A21, A22, , A2n]
3
4
[Am1, Am2, , Amn]]
5
And is not limited to the 9 submatrices case, it was a coincidence that in the bmat
documentation their example is the same size as the example in your question.
JavaScript
1
6
1
import numpy as np;
2
mats = []
3
for i in range(10):
4
mats.append(np.ones((4, 2)) * i);
5
np.bmat([mats[:5], mats[5:]])
6
Gives
JavaScript
1
9
1
matrix([[0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
2
[0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
3
[0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
4
[0., 0., 1., 1., 2., 2., 3., 3., 4., 4.],
5
[5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
6
[5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
7
[5., 5., 6., 6., 7., 7., 8., 8., 9., 9.],
8
[5., 5., 6., 6., 7., 7., 8., 8., 9., 9.]])
9