2

My question is related to a Kaggle data science competition. I'm trying to read an image from a one-dimensional array containing 1-bit grayscale pixel information (0 to 255) for an 28x28 image. So the array is from 0 to 783 where each pixel is encoded as x = i * 28 + j.

Converted into a two-dimensional 28x28 matrix this:

000 001 002 003 ... 026 027
028 029 030 031 ... 054 055
056 057 058 059 ... 082 083
 |   |   |   |  ...  |   |
728 729 730 731 ... 754 755
756 757 758 759 ... 782 783

For reasons of image manipulation (resizing, skewing) I would like to read that array into an in-memory PIL image. I did some research on the Matplotlib image function, which I think is most promising. Another idea is the Numpy image functions.

What I'm looking for, is a code example that shows me how to load that 1-dimensional array via Numpy or Matplotlib or anything else. Or how to convert that array into a 2-dimensional image using for instance Numpy.vstack and then read it as an image.

3
  • 1
    Simple use np.reshape() with the desired shape of (28,28) with it? Commented Aug 15, 2016 at 9:51
  • and how to use it to load the image? code? Commented Aug 15, 2016 at 10:02
  • Yeah, I am not sure about reading image part. Commented Aug 15, 2016 at 10:04

1 Answer 1

5

You can convert a NumPy array to PIL image using Image.fromarray:

import numpy as np
from PIL import Image 

arr = np.random.randint(255, size=(28*28))
img = Image.fromarray(arr.reshape(28,28), 'L')

L mode indicates the array values represent luminance. The result will be a gray-scale image.

Sign up to request clarification or add additional context in comments.

5 Comments

just found this one too, which is used for the Kaggle tutorial.
How do I do the same with color image stored as ndarray, where we have 3 channels BGR? @unutbu
@Santhosh: To convert BGR --> RGB you could use img = img[..., ::-1].
Thank You @unutbu img = img[...,::-1] seems to be much faster than color conversion in OpenCV in which I'm working. Even this worked out = Image.fromarray(ima.reshape(ima.shape[0],ima.shape[1],3),"RGB")
Your posts have helped me a lot! Would love to learn much more tricks from you 😃 @unutbu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.