在Python中将图像转换为CSV文件

yzckvree  于 2023-04-03  发布在  Python
关注(0)|答案(5)|浏览(165)

我已经把我的图像转换成一个csv文件,它就像一个矩阵,但我希望它是一个单行。我如何才能把所有的图像在数据集中转换成一个csv文件(每个图像成一行)。
下面是我使用的代码:

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=',')

输入:http://uupload.ir/files/pto0_lotus1_1.jpg
输出:http://uupload.ir/files/huwh_output.png

tpgth1q7

tpgth1q71#

从你的问题来看,我认为你想知道numpy.flatten()。你想添加

value = value.flatten()

它将把数组展平到只有一个维度,然后打印成一行。
你的问题的其余部分是不清楚的位,它意味着你有一个充满jpeg图像的目录,你想要一种方法来读取它们。所以首先,得到一个文件列表:

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

for fileName in fileList:包围代码

编辑以添加完整的示例请注意,我使用了csv writer并将float 64更改为int(这应该可以,因为像素数据为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)
inn6fuwd

inn6fuwd2#

如何将您的图像转换为2D numpy数组,然后将它们写入带有**.csv扩展名和,**作为分隔符的txt文件?
你可以使用如下代码:

np.savetxt('np.csv', image, delimiter=',')
but5z9lq

but5z9lq3#

import numpy as np
import cv2
import os

IMG_DIR = '/home/kushal/Documents/opencv_tutorials/image_reading/dataset'

for img in os.listdir(IMG_DIR):
        img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)

        img_array = (img_array.flatten())

        img_array  = img_array.reshape(-1, 1).T

        print(img_array)

        with open('output.csv', 'ab') as f:

            np.savetxt(f, img_array, delimiter=",")
q1qsirdb

q1qsirdb4#

import os
import pandas as pd

path = 'path-to-the-folder'
os.chdir(path)
lists = os.listdir(path)
labels = []
file_lst = []

for folder in lists:
    files = os.listdir(path +"/"+folder)
    for file in files:
      path_file = path + "/" + folder + "/" + file
      file_lst.append(path_file)
      labels.append(folder)

dictP_n = {"path": file_lst,
           "label_name": labels,
          "label": labels}   

data  = pd.DataFrame(dictP_n, index = None)
data = data.sample(frac=1)
data['label'] = data['label'].replace({"class1": 0, "class2": 1 })
data.to_csv("path-to-save-location//file_name.csv", index =None)
ef1yzkbh

ef1yzkbh5#

from logging import root

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

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

    return fileList

myFileList = createfilelist('C:/Users/Rahul/Desktop/CASIA2/Au')

for file in myFileList:
    print(file)
    img_file = Image.open(file)
    width, height = img_file.size
    format = img_file.format
    mode = img_file.mode
    img_grey  = img_file.convert('L')

    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("image_to_csv.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(value)

相关问题