用Python将图像转换为CSV文件

11

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


将您的矩阵内容写入新文件中,只写入一行。 - IMCoins
5个回答

20

从您的问题中,我认为您想了解 numpy.flatten()。您想要添加

value = value.flatten()

在调用np.savetxt之前加入ravel()函数,可以将数组压缩为一维数组,这样它就应该作为一行输出。

你的问题其余部分不清楚,但它暗示你有一个充满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更改为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)

嗨,@Pam,我有285张图片,我想把它们转换成CSV文件,同时我希望每个图像都是CSV文件的一行。简而言之,我想把这些图像转换成特征向量以供其他任务使用。 - Nebula
亲爱的 @Pam,我在 Python 方面没有太多经验。我已经编辑了我的代码。你能再次检查一下我的代码吗? - Nebula
@Zeinab 如果图像保存为一维数组,你如何知道它们的尺寸?你需要添加某种标头。 - Nyerguds
另外,我更愿意保存为十六进制值;这将使它们更加统一和紧凑。 - Nyerguds
1
这不是一个好主意 - 你想要删除黑色像素,却没有办法把它们放回去?图像将会被完全破坏。你的图像有多大?聪明的做法是调整它们的大小。列数是(宽度 x 高度),从中可以计算出你的图像需要缩小到多小。 - Pam
显示剩余11条评论

6

你可以将图片转换为2D numpy数组,然后用.csv作为扩展名并以,作为分隔符将它们写入文本文件中。例如:

你可以使用下面的代码:

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

6
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=",")

“img_array = img_array.reshape(-1, 1).T” 和 “img_array = img_array.reshape(1, -1)” 是相同的吗? - Aditya Gupta

3
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)

-1
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接