pythonimagegrayscale

How to convert array to Gray Scale Image output?


I have the data in a txt.How should i do to convert the data to Gray Scale Image output?Thx! The number of rows is 2378 and the number of columns is 5362. enter image description here

I'm a noob in python.I have tried this,but it did not work.

from numpy import *
from PIL import Image


def rdnumpy(txtname):
    f = open(txtname)
    line = f.readlines()
    lines = len(line)
    for l in line:
        le = l.strip('\n').split(' ')
        columns = len(le)
    A = zeros((lines, columns), dtype=int)
    A_row = 0
    for lin in line:
        list = lin.strip('\n').split(' ')
        A[A_row:] = list[0:columns]
        A_row += 1
    return A


A = rdnumpy('oop.txt')
im = Image.fromarray(array)
im = im.convert('L')
im.save('T7.png')

Solution

  • Your code with small changes (see # <<< in code):

    from numpy import *
    from PIL import Image
    
    
    def rdnumpy(txtname):
        f = open(txtname)
        line = f.readlines()
        lines = len(line)
        for l in line:
            le = l.strip('\n').split(' ')
            columns = len(le)
        A = zeros((lines, columns), dtype=uint8) # <<< uint8
        A_row = 0
        for lin in line:
            list = lin.strip('\n').split(' ')
            A[A_row:] = list[0:columns]
            A_row += 1
        return A
    
    
    A = rdnumpy('PIL_imgFromText.txt')
    im = Image.fromarray(A) # <<< A
    im = im.convert('L')
    im.save('PIL_imgFromText.png')
    

    creates in case of 'PIL_imgFromText.txt'

    100 128 156
    200 225 255
    

    following grayscale image (magnified):

    image

    P.S. Below a suggestion how the code of the function can be further improved:

    import numpy as np
    def rdnumpy_improved(txtname):
        lst = []
        with open(txtname) as f: 
            lines = f.readlines()
            imgSizeY = len(lines)
            imgSizeX = len(lines[0].strip('\n').split(' '))
        for line in lines:
            lst_c = line.strip('\n').split(' ')
            assert imgSizeX == len(lst_c)
            lst += lst_c
        A = np.array(lst, dtype=uint8).reshape((imgSizeY, imgSizeX))
        return A
    

    and finally how the entire code can be shorten to a one-liner using numpy.loadtxt() function (as suggested in another answer)

    import numpy as np
    from PIL import Image
    Image.fromarray(np.loadtxt('PIL_imgFromText.txt', dtype=np.uint8)).save('PIL_imgFromText.png')