20

What's the best way to use Numpy to convert a size (x, y, 3) array of rgb pixel values to a size (x, y, 1) array of grayscale pixel values?

I have a function, rgbToGrey(rgbArray) that can take the [r,g,b] array and return the greyscale value. I'd like to use it along with Numpy to shrink the 3rd dimension of my array from size 3 to size 1.

How can I do this?

Note: This would be pretty easy if I had the original image and could grayscale it first using Pillow, but I don't have it.

UPDATE:

The function I was looking for was np.dot().

From the answer to this quesiton:

Assuming we convert rgb into greyscale through the formula:

.3r * .6g * .1b = grey,

we can do np.dot(rgb[...,:3], [.3, .6, .1]) to get what I'm looking for, a 2d array of grey-only values.

MarcinKonowalczyk
  • 2,577
  • 4
  • 20
  • 26
SlothFriend
  • 601
  • 1
  • 7
  • 14

1 Answers1

30

See the answers in another thread.

Essentially:

gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
lange
  • 590
  • 5
  • 9
  • Thanks, it was the np.dot() method I was needing! – SlothFriend Feb 01 '17 at 04:47
  • could you please tell how to convert rgb array to black an white image? or should I ask new question? – GD- Ganesh Deshmukh Apr 02 '19 at 18:21
  • @ganeshdeshmukh You can use the fromarray function of the PIL Image. Convert the rgb array to gray scale using the method mentioned here, then im = Image.fromarray(grey_array). If you pass the rgb array, then you can get a color image Image.fromarray(rgb_array, mode='RGB') – lange Apr 08 '19 at 18:20
  • alternatively: `rgb[..., :3] @ [0.299, 0.587, 0.114]` see https://numpy.org/doc/stable/reference/generated/numpy.matmul.html – Robz Sep 04 '20 at 07:40