0

I am trying to parse a folder with images into a numpy array. I want to obtain an array which looks like this:

import numpy as np
from sklearn.datasets import fetch_mldata

#load 70,000 MNIST images (28 X 28 pixels)
mnist = fetch_mldata("MNIST original")
X = mnist.data

print X.shape 

Desired output:

(70000L, 784L)

This is what I tried:

from PIL import Image                                                            
import numpy                                                                     
import matplotlib.pyplot as plt                                                  
import glob

#I have two colour images, each 64 X 64 pixels, in the folder
imageFolderPath = 'C:\\Users\\apples\\Desktop\\t-sne\\pics'
imagePath = glob.glob(imageFolderPath+'/*.JPEG') 

im_array = numpy.array( [numpy.array(Image.open(imagePath[i])) for i in range(len(imagePath))] )

print im_array.shape

But it produces the following output:

(2L, 64L, 64L, 3L)

How can I obtain an array with the following dimensions:

(m, n)

1 Answer 1

2

PIL loads color images in RGB format (maybe not always), hence the last dimension is size 3 (one for each color channel). So you probably want to convert the image to a different pixel format. Also you need to flatten the image arrays to get to the layout that you want. You could do something like:

def img2array(path):
    img = Image.open(path).convert('F')
    return numpy.array(img).ravel()

im_array = numpy.array([img2array(path) for path in imagePath])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this worked like a charm! Can I ask in what order does this process the images in the folder. I have to make another array with labels corresponding to each image e.g. (0,1...n), therefore I need to make sure the labels match the correct image.
@apples-oranges - glob.glob uses os.listdir which gives paths in arbitrary order. Of course you can wrap it in a call to sorted to fix the order. Or you could parse the filenames.

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.