Picard
Picard

Reputation: 1037

How to concatenate images horizontally with numpy?

I'm trying to generate a synthetic sequence with MNIST images. Each image is flattened 784. When I select five of them, my data is shape (5,784). I want to concatenate 5 of them horizontally, that my final image has shape (28,5*28). How can I achieve that?

I tried it with np.reshape but the best I could achieve, was a vertical concatenation.

Upvotes: 0

Views: 7198

Answers (1)

John Zwinck
John Zwinck

Reputation: 249133

For demonstration, let's say we want to horizontally concatenate three images which are 4x4, stored flat as 16 elements:

a = np.arange(16)
b = np.arange(16,32)
c = np.arange(32,48)

images = np.array([a,b,c]) # 3x16

That's just to prepare the sample data. Now reshape and concatenate:

np.hstack(images.reshape(3,4,4))

The result is:

array([[ 0,  1,  2,  3, 16, 17, 18, 19, 32, 33, 34, 35],
       [ 4,  5,  6,  7, 20, 21, 22, 23, 36, 37, 38, 39],
       [ 8,  9, 10, 11, 24, 25, 26, 27, 40, 41, 42, 43],
       [12, 13, 14, 15, 28, 29, 30, 31, 44, 45, 46, 47]])

In your original case, the expression would be:

np.hstack(stuff.reshape(5,28,28))

And indeed the shape is (28,140).

Upvotes: 3

Related Questions