2

I have 3 images of the same size, I read each one using matplotlib.image.imread which returns a 3D numpy array.

(Height, Width, ChannelsNumber) # ChannelsNumber = 3 for RGB

Now, i want to merge the 3 images into a 4D numpy array like this :

(Height, Width, ChannelsNumber, NumberOfImages)

Meaning, the 3rd dimension array at position (X,Y) will no longer contain RGB values for pixel (X,Y) but will contain 3 arrays one for each channel (), where each array will contain 3 R, G, r B values (for 3 images)

  • array at position X,Y,0 will contain all RED values for images 1,2,3 at pixel X,Y
  • array at position X,Y,1 will contain all GREEN values for images 1,2,3 at pixel X,Y
  • array at position X,Y,2 will contain all BLUE values for images 1,2,3 at pixel X,Y

For example :

(10,15,0) will be an array containing all the RED values for all the images for Pixel (10,15)

Here's what i have tried :

import numpy as np
import os
import matplotlib.image as mpimg

img1 = mpimg.imread('./image1.jpg')
img2 = mpimg.imread('./image2.jpg')
img3 = mpimg.imread('./image3.jpg')

x = np.dstack((img1, img2, img3))

this returns a 3D array, where the 3rd dimension is an array that contains the RGB values of the images in this format:

[R-img1, B-img1, G-img1, R-img2, B-img2, G-img2, R-img3, B-img3, G-img3]

where what i want is :

[ 
    [R-img1, R-img2, R-img3,],
    [R-img1, B-img2, -img3,],
    [B-img1, B-img2, B-img3,]
]

Thank you !

5
  • 1
    .stack along axis=-1 Commented Nov 10, 2019 at 1:11
  • @Scott thank you .. put this as an answer so that i mark this as answerd .. Commented Nov 10, 2019 at 1:13
  • x = np.vstack((img1, img2, img3)) Commented Nov 10, 2019 at 1:16
  • @Scott how do i reverse, do the opposite, for output to input ? Commented Nov 10, 2019 at 10:01
  • 1
    The first img is the 0th element along the last index. img1 = stacked_imgs[...,0] Commented Nov 10, 2019 at 13:05

2 Answers 2

3

the answer is the one Scott commented

x = np.stack((img1, img2, img3), axis = -1)
Sign up to request clarification or add additional context in comments.

Comments

2

import numpy as np
import os
import matplotlib.image as mpimg

img1 = mpimg.imread('1.png')
img2 = mpimg.imread('2.png')
img3 = mpimg.imread('1.png')

print(img1.shape)
print(img2.shape)
print(img3.shape)
x = np.vstack((img1, img2, img3))

Stack arrays in sequence vertically

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.