Skip to main content
 首页 » 编程设计

python之在python中将图像转换为csv文件

2025年05月04日8Free-Thinker

我已将图像转换为 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

请您参考如下方法:

根据你的问题,我认为你想了解 numpy.flatten()。你要加

value = value.flatten() 

就在您的 np.savetxt 调用之前。它会将数组展平到只有一个维度,然后它应该作为一行打印出来。

你的问题的其余部分不清楚,这意味着你有一个充满 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 并将你的 float64 更改为 ints(这应该没问题,因为像素数据是 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)