简体   繁体   中英

Replace each pixel in a numpy array with a formula

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM