Back to Parent

# Autogenerating pixel images from csv file
# Harley Guo
# Carnegie Mellon University
# March 2022


from PIL import Image
import numpy as np
import csv, math, colorsys

print("file name: ", end = '')
SAVEFILE = input()
FILE = "YOURFILENAME.csv"
SAT = 50
SIZE = 1080

def getInRange(x, l, r):
    if x < l:
        return l
    elif x > r:
        return r
    return x

def main():
    with open(FILE, 'r') as tf:
        treader = csv.reader(tf)
        tempMin, tempMax, lightMin, lightMax = 4095, 0, 4095, 0
        rowCount = 0
        for row in treader:
            temp = float(row[1])
            light = int(row[0])
            if temp < tempMin:
                tempMin = temp
            elif temp > tempMax:
                tempMax = temp
            if light < lightMin:
                lightMin = light
            elif light > lightMax:
                lightMax = light
            rowCount += 1

    with open(FILE, 'r') as f:
        reader = csv.reader(f)
        size = math.floor(math.sqrt(rowCount))
        pixels = [[] for _ in range(size)]
        res = size ** 2

        counter = 0

        for row in reader:
            if counter >= res:
                break

            imageRow = math.floor(counter / size)

            # temp as hue 0~90
            h = float(row[1])
            s = round(SAT / 255, 3)
            # brightness as light 300~3600
            l = int(row[0])

            # remap
            h = round(np.interp(h, [tempMin, tempMax], [0, 1]), 4) 
            l = round(np.interp(l, [lightMin, lightMax], [0, 1]), 4)

            #convert
            r,g,b = colorsys.hls_to_rgb(h,l,s)
            r,g,b = int(r*255), int(g*255), int(b*255)
            
            pixels[imageRow].append((r,g,b))
            counter += 1
    png = []
    for i in range(imageRow):
        temp = []
        for j in range(imageRow):
            for k in range(int(SIZE/imageRow)):
                temp.append(pixels[i][j])
        for k in range(int(SIZE/imageRow)):
            png.append(temp)

    arr = np.array(png, dtype=np.uint8)

    new_image = Image.fromarray(arr)
    new_image.save(f'{SAVEFILE}.png')
    print(f'saved as {SAVEFILE}.png...')

if __name__ == "__main__":
    main()
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0