Say I have 9 2D arrays in the following format:
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 ]]
and I want to concatenate them to get a 2D array like this:
A = [B1, B2, B3]
where
B1 = np.concatenate((A1,A2, A3),axis=1) B2 = np.concatenate((A4,A5, A6),axis=1) B3 = np.concatenate((A7,A8, A9),axis=1)
I will have N arrays in my case and I calculate the value of N like so:
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) ...
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.
[[A11, A12, ..., A1n] [A21, A22, ..., A2n] ... [Am1, Am2, ..., Amn]]
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.
import numpy as np; mats = [] for i in range(10): mats.append(np.ones((4, 2)) * i); np.bmat([mats[:5], mats[5:]])
Gives
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.]])