pythonimage-processingnumpycomputer-visionobject-comparison

How can I convert an image's pixel color information into numbers and store it in a CSV?


How do I extract the pixel color information in an image into numbers and store them in a CSV file? These numbers should all go into 1 row and multiple columns. If the image is 50*50 then there should be only 1 row and 2500 columns containing the pixel color information. How can I achieve this in Python? Please advice.

I found the code which was,

pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]

But I want this list in a single row and multiple columns as my svm expects it in that format for training the images.

The output should look like below given since this is a grey scale image, 2 3 253...

where 2 is the color of the 1st pixel and 3 is the color of the 2nd pixel and 253 is the color of 3rd etc. 2 will be in 1st cell of the 1st row and 3 in 2nd cell and 253 in 3rd cell and so on. But the whole image pixels will be in this row. So if its a 50*50 picture there will be 2500 columns/cells containing the pixel values as mentioned above.


Solution

  • Basically you want to unwind the array (which is a list of lists). You can do this with a double list comprehension:

    pixels = [i for row in pixels for i in row]
    

    If you want to write it to a file with spaces between your values you can do this

    with open('output.csv', 'w') as outfile:
       outfile.write(' '.join([str(i) for i in pixels])