12

I have an RGB image which I want to convert to a grayscale image, so that I can have one number (maybe between 0 and 1) for each pixel. This gives me a matrix which has the dimensions equal to that of the pixels of the image. Then I want to do some manipulations on this matrix and generate a new grayscale image from this manipulated matrix. How can I do this?

lovespeed
  • 4,835
  • 15
  • 41
  • 54
  • There is numpy and scipy. Scipy let you load an image and transform it into numpy array. It use PIL behind. With numpy you can "flat" the RGB into a greyscale image. Then you can do anything you want with that array – Pierre Turpin May 29 '14 at 14:34
  • Use --> [openCV](http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html) -- or [SimpleCV](http://simplecv.org/) –  May 29 '14 at 14:35
  • [This answer](http://stackoverflow.com/a/12201744/1595865) should suffice – loopbackbee May 29 '14 at 14:37
  • @goncalopp: the conversion is fine, but how do I convert it to a 2D array? – lovespeed May 29 '14 at 14:48
  • @lovespeed: Loading an image using the PIL (a la goncalopp's answer) is essentially a 2D array. You'd access a pixel using `img[x,y]`. Is that not sufficient? – rayryeng May 31 '14 at 04:32

1 Answers1

17

I frequently work with images as NumPy arrays - I do it like so:

import numpy as np
from PIL import Image

x=Image.open('im1.jpg','r')
x=x.convert('L') #makes it greyscale
y=np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0]))

<manipulate matrix y...>

y=np.asarray(y,dtype=np.uint8) #if values still in range 0-255! 
w=Image.fromarray(y,mode='L')
w.save('out.jpg')

If your array values y are no longer in the range 0-255 after the manipulations, you could step up to 16-bit TIFFs or simply rescale.

-Aldo

Aldo
  • 390
  • 5
  • 12
  • you can use ```plt.imshow(y, cmap=plt.get_cmap('gray'))``` to display grayscale image – KY Lu Aug 13 '19 at 02:54
  • If you plan to go on and work with tensorflow (2.x+) you might find tensorflow.keras.preprocessing.image.img_to_array(image) useful too since this will convert a PIL Image to numpy.ndarray – jtromans Dec 17 '20 at 10:21