0

I have a numpy array, which represent image pixels, shape of the array is (500, 800, 3) I need to multiply each pixel with the formula:

pixel_color = r * 0.299 + g * 0.587 + b * 0.114

So, [r, g, b] -> [pixel_color, pixel_color, pixel_color]

How can I do this with numpy operations?

5
  • Does the last (inner) dimension contain the rgb values? And if so, do you want to end up with a two dimensional array? Commented Jul 23, 2018 at 13:42
  • @9769953 It's a grayscale shades of rgb Commented Jul 23, 2018 at 13:43
  • I think you're looking forvectorize. Commented Jul 23, 2018 at 13:43
  • There are no grayscale shades of rgb; that doesn't mean anything. Do you mean the (relative) values of the three colours, or a three dimensional grayscale picture? Commented Jul 23, 2018 at 13:44
  • @9769953 Relative values Commented Jul 23, 2018 at 13:46

1 Answer 1

1

You're looking for the weighted average of pixels.

a = np.ones(shape=(500,800,3))
gray_image = np.average(a, axis=2, weights=[.299, .587, .114])

Then, to get back to the original shape, you can use np.repeat with a new axis.

np.repeat(gray_image[:,:,np.newaxis], repeats=3, axis=2)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the np.repeat example, very relevant here!

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.