Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting images to csv file in python

Tags:

python

csv

image

I have converted my image into a csv file and it's like a matrix but I want it to be a single row. How can I convert all of the images in dataset into a csv file (each image into one line).

Here's the code I've used:

from PIL import Image
import numpy as np
import os, os.path, time

format='.jpg'
myDir = "Lotus1"
def createFileList(myDir, format='.jpg'):
    fileList = []
    print(myDir)
    for root, dirs, files in os.walk(myDir, topdown=False):
            for name in files:
               if name.endswith(format):
                  fullName = os.path.join(root, name)
                  fileList.append(fullName)
                  return fileList

fileList = createFileList(myDir)
fileFormat='.jpg'
for fileFormat in fileList:
 format = '.jpg'
 # get original image parameters...
 width, height = fileList.size
 format = fileList.format
 mode = fileList.mode
 # Make image Greyscale
 img_grey = fileList.convert('L')
 # Save Greyscale values
 value = np.asarray(fileList.getdata(),dtype=np.float64).reshape((fileList.size[1],fileList.size[0]))
 np.savetxt("img_pixels.csv", value, delimiter=',')

input : http://uupload.ir/files/pto0_lotus1_1.jpg

output:http://uupload.ir/files/huwh_output.png

like image 933
Nebula Avatar asked Mar 02 '18 13:03

Nebula


People also ask

How do I convert an image to a CSV file?

To convert a JPG image to CSV format, simply drag and drop the JPG file into the data upload area, select the 'OCR' option, and click the 'Convert' button. You'll get an CSV spreadsheet populated with data from the JPG file.

Can I save image in CSV file?

Use the 'Image to CSV Converter' to export a table of data from an image to CSV format. Our free service uses a powerful 'OCR' feature to recognize the table structure and extract text from the cells in the image. You will get an editable CSV spreadsheet that you can adjust as you need.

Can you convert PNG to CSV?

You can convert your PNG documents from any platform (Windows, Linux, macOS). No registration needed. Just drag and drop your PNG file on upload form, choose the desired output format and click convert button. Once conversion completed you can download your CSV file.


1 Answers

From your question, I think you want to know about numpy.flatten(). You want to add

value = value.flatten()

right before your np.savetxt call. It will flatten the array to only one dimension and it should then print out as a single line.

The rest of your question is unclear bit it implies you have a directory full of jpeg images and you want a way to read through them all. So first, get a file list:

def createFileList(myDir, format='.jpg'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
    for name in files:
        if name.endswith(format):
            fullName = os.path.join(root, name)
            fileList.append(fullName)
return fileList

The surround your code with a for fileName in fileList:

Edited to add complete example Note that I've used csv writer and changed your float64 to ints (which should be ok as pixel data is 0-255

from PIL import Image
import numpy as np
import sys
import os
import csv

#Useful function
def createFileList(myDir, format='.jpg'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
    for name in files:
        if name.endswith(format):
            fullName = os.path.join(root, name)
            fileList.append(fullName)
return fileList

# load the original image
myFileList = createFileList('path/to/directory/')

for file in myFileList:
    print(file)
    img_file = Image.open(file)
    # img_file.show()

    # get original image parameters...
    width, height = img_file.size
    format = img_file.format
    mode = img_file.mode

    # Make image Greyscale
    img_grey = img_file.convert('L')
    #img_grey.save('result.png')
    #img_grey.show()

    # Save Greyscale values
    value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0]))
    value = value.flatten()
    print(value)
    with open("img_pixels.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(value)
like image 145
Pam Avatar answered Sep 21 '22 19:09

Pam