1

I have three matrices, R, B, G, which all are the same in size, say m*n. I want to stack all three of them together into a different channel of a new matrix (3*m* n or m*n*3), as implemented in Matlab:

 A(:,:,1) = R
 A(:,:,2) = G
 A(:,:,3) = B

How do I achieve this efficiently in Python?

2
  • Are you using a particular package (e.g. NumPy) for your matrices, or are they just pure lists? Commented Jun 3, 2017 at 1:13
  • @Alden: yeah. I know numpy has stack functions, but they seem only to be applicable to two matrices Commented Jun 3, 2017 at 1:17

1 Answer 1

4

numpy.stack should work for three arrays:

numpy.stack((R, G, B))

For example,

a = numpy.array([[1,2],[2,1]])
b = numpy.array([[3,3],[4,4]])
c = numpy.array([[5,6],[7,8]])
print(numpy.stack((a, b, c)))

prints

[[[1 2]
  [2 1]]

 [[3 3]
  [4 4]]

 [[5 6]
  [7 8]]]
Sign up to request clarification or add additional context in comments.

2 Comments

TypeError: stack() takes at most 2 arguments (3 given)
Make sure you are passing (R, G, B) (one argument, a tuple containing the three arrays), not R, G, B (the three arrays as individual arguments).

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.