4

I want to create an image out of an csv data.

I am reading the csv with:

f = open('file.csv', 'rb')
reader = csv.reader(f)

From here, I want to make a grayscale image that is translating each row of numbers in the list into a line of intensities in an image file.

Not sure what would be useful but here are some details about my csv file: using floats, columns:315, rows: 144

Thanks

Voltronika
  • 560
  • 2
  • 5
  • 13

4 Answers4

6

Two steps:

  1. convert the csv file to a numpy array using genfromtxt

From @Andrew on How to read csv into record array in numpy?

from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')
  1. then save the numpy array as an image
Community
  • 1
  • 1
Vincent
  • 12,919
  • 1
  • 42
  • 64
1
from numpy import genfromtxt
from matplotlib import pyplot
from matplotlib.image import imread
my_data = genfromtxt('path to csv', delimiter=',')
matplotlib.image.imsave('path to save image as Ex: output.png', my_data, cmap='gray')
image_1 = imread('path to read image as Ex: output.png')
# plot raw pixel data
pyplot.imshow(image_1)
# show the figure
pyplot.show()
Vignesh
  • 11
  • 2
0

For a very simple solution if you just want to get an impression of what the image would look like you can use the pgm format.

You can create it by writing out the pixels as ascii. The link goes into more detail but the gist is that you have a file of the format:

P2 //which format it is
width height //dimensions
maxValue //the highest value a pixel can have (represents white)
a b c ... //the pixel values (new line needed at the end of each row)

How you get the values out of the CSV should be straightforward, then you could use a function like (untested):

def toFile(array, filename):
    f = file(filename, 'w')
    f.write("P2\n%d %d\n255\n" %(len(array[1]), len(array))
    for i in array:
        for j in i:
            f.write("%d " %(j))
        f.write("\n")
    f.close()
Holloway
  • 6,412
  • 1
  • 26
  • 33
0


I think you could try with glob.glob, what should help


import numpy as np
import glob
import cv2
import csv

Libraries ⬆️; You know what⬇️

image_list = []

for filename in glob.glob(r'C:\your path to\file*.png'):    # '*' will count files each by one
    
    #Read
    img = cv2.imread(filename)
    flattened = img.flatten() 
    print(flattened) # recommend to avoid duplicates, see files and so on.

    #Save
    with open('output2.csv', 'ab') as f: #ab is set 
            np.savetxt(f, flattened, delimiter=",")

Cheers

Also, find an easier method that is making fast and not weight image/csv

image_list = []
with open('train_train_.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter ='-')

    for filename in glob.glob(r'C:\your path to\file*.png'):

        img = cv2.imread(filename)
        image_list.append(img)
        csv_writer.writerow(img)
        print(img)
horizon
  • 67
  • 5