2

I have a numpy array in the shape (244,244,3). Each holds a RGB image as numpy array. From each of the channels I want to subtract a value.

Of course I can easily do it with a for loop, but I assume that there is a faster way in numpy?

Any ideas?

Many thanks

3
  • 1
    Show us the loopy version? Commented Apr 24, 2017 at 22:25
  • 1
    Are you subtracting an array of values of the same size? In that case you can just do array1 - array2; as simple as that. If this is not the case, can you clarify the dimensions of the values you'd like to substract? Commented Apr 24, 2017 at 22:37
  • that shape suggests that it is rgb image. your reference to 'each', does that mean you have others with the same shape? Commented Apr 24, 2017 at 22:39

1 Answer 1

5

You may simply subtract a 3-vector, numpy will broadcast it automatically.

Little demo with a 5x5 RGB image, subtracting 2 from red channel, 5 from green channel, 3 from blue channel:

>>> A = 10*np.ones((5,5,3), dtype=int)
>>> A -= [2, 5, 3]
>>> A[:,:,0]  # Red
array([[8, 8, 8, 8, 8],
       [8, 8, 8, 8, 8],
       [8, 8, 8, 8, 8],
       [8, 8, 8, 8, 8],
       [8, 8, 8, 8, 8]])
>>> A[:,:,1]  # Green
array([[5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5]])
>>> A[:,:,2]  # Blue
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])
Sign up to request clarification or add additional context in comments.

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.