-2
$\begingroup$

So what I'm trying to do is iterate over a grayscale image and look at each pixel and write that pixel's grayscale value to the second row (the first row being the pixel number). The following code isn't doing anything so far:

from __future__ import with_statement
from PIL import Image

im = Image.open("my28x28image.png") #relative path to file


pix = im.load()


width, height = im.size
print(width)
print(height)


with open('my28x28image.csv', 'a') as f:
    for y in range(28):
        for x in range(28):
            data.append(pix[x,y])

add values to row 2(0-255)

$\endgroup$
1
  • $\begingroup$ Where exactly are you having problems? Is this about how to write the program? $\endgroup$
    – Corion
    Oct 21, 2018 at 7:37

1 Answer 1

0
$\begingroup$

I wrote you a small utility function which converts a greyscale image stored in a numpy matrix into a csv file.

def greyscale_image_to_csv(img_grayscale, file_name):
    csv_header = ['pixel' + str(i) for i in range(np.prod(img_grayscale.shape))]
    csv_data = [str(j) for i in img_grayscale for j in i]
    csv_string = ','.join(csv_header) + '\n' + ','.join(csv_data) 

    f = open(file_name + '.csv','w')
    f.write(csv_string)
    f.close()

Here is an example on how to use this function. I have the following image saved to file which is RGB. I load the image and convert the image to greyscale.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray

img = mpimg.imread('greyscale_image.png')
img_grayscale = rgb2gray(img)

Finally, we can write a csv using our utility function to get a csv file in the desired format.

greyscale_image_to_csv(img_grayscale, 'test')

enter image description here

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.