Converting RGB Numpy Matrix To Greyscale Martix

- 1 answer

I want to convert rgb matrix to greyscale martix without directly opening the image file as the process is very slow in python?



In general, you always have to load image into python program if you want to process it. If you dont wan to use image procesing library, you can do all with numpy (for example OpenCV works with numpy arrays anyway, so I would be using OpenCV)

If you want to use purely matrixes(numpy) you can use for saving and loading

matrix = np.load('image.npy')'grayscale.npy',grayscale)

For processing:

Suppose you have have numpy matrix with this RGB shape:

>>> matrix.shape
(1000, 1000, 3)

In order to transform it into grayscale without doing any 'image processing', you can simply do MEAN over 3rd. dimension (color dimension)

grayscale = matrix.mean(axis=-1) # you can use axis=2 or as Nils Werner pointed out: axis=-1 which is more general

>>> grayscale.shape


BEFORE: enter image description here

AFTER MEAN enter image description here