0

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)

Have a look at the first image:

plt.imshow(images[1])

enter image description here

View as gray scale:

plt.imshow(to_grayscale(images[1]))

enter image description here

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.

Vlad
  • 3,058
  • 4
  • 25
  • 53

2 Answers2

0

Use PIL

from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')
Aditya
  • 2,380
  • 2
  • 14
  • 39
0

I'm not sure if this is the fastest or most elegant way to do this in general, based on this answer

images_g = np.array([to_grayscale(images[i]) for i in range(images.shape[0])])
Vlad
  • 3,058
  • 4
  • 25
  • 53