Convert colour to grey scale numpy array

How do I convert an array of two colour images to an array of two gray scale images using the to_grayscale (from this site) function below.

Important: I don’t want image files, I want the array image_g defined below.

First create the function and sample images:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
np.random.seed(0)

def to_grayscale(im):
    tile = np.tile(np.c_[0.333, 0.333, 0.333], reps=(im.shape[0],im.shape[1],1))
    return np.sum(tile * im, axis=2)

images = np.random.randint(0, 255, 24).reshape(2, 2, 2, 3)
images.shape

out> (2, 2, 2, 3)

How do I convert images to an array of gray scale images image_g ? I’d like to do something like this:

image_g = np.somefunction(to_grayscale, images)
images_g.shape

out> (2, 2, 2)

where somefunction is a placeholder for the answer.

if you really want to use what you write, then check out these methods to map a function to an array (mapping is what your “somefunction” would mean):

But I would not use that, the easiest and fastest way of greyscaling I know using the mean would be this one line:

images_g = np.mean(images, -1)

At least for your example above it looks identical (looking at the pics with plt.imshow() ) and is fully vectorized = fast, faster than mapping your python function (which is irrelevant for 2 pics, but I assume that’s not your usecase…)

1 Like

Thanks to the link, it seems this should be on par with the fastest method:

images_g = np.array([to_grayscale(images[i]) for i in range(images.shape[0])])

Please let me know if there is a more elegant way to do this (except for np.mean which is great for the specific case where I don’t ever need to change the 0.333 values in the function).

It would be really nice if Fast.ai had a default function for this purpose!

Do you mean opening images as grayscale by default? ImageList and open_image take a convert_mode argument. See docs :slight_smile:

Yes, but they take data from a path correct?

Having a numpy -> fastai Image and vice versa would be helpful without and file save, or file open… if there is a one line way of doing this please let me know! :slight_smile: