pythonpython-imaging-librarygetpixel

Save pixel data in txt format in PIL


My program is to extract the pixel from an image and to save the pixel data in the text file for analysis. My picture is a binary image that gives only 255 and 0 's

Here is the program:

from PIL import Image

im = Image.open("thresh.jpg")
pixel = im.load()
row, column = im.size
for y in range(column)
    for x in range(row)
        pixel = pix[x, y]

Question:

I want to save the pixel data in a text file. Suggest me some techniques to save the data.


Solution

  • Just create a file writer object and write the value of the variable pixel to that.

    from PIL import Image
    
    im = Image.open("thresh.jpg")
    fil = open('file', 'w')
    pixel = im.load()
    row, column = im.size
    for y in range(column):
        for x in range(row):
            pixel = pix[x, y]
            fil.write(str(pixel) + '\n')
    fil.close()