【问题标题】:Converting images to csv file in python在python中将图像转换为csv文件
【发布时间】:2018-08-10 17:37:22
【问题描述】:

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

【问题讨论】:

  • 写入一个新文件,将矩阵的内容写入一行?
  • 您可以发布示例数据吗?
  • 嗨@MohamedThasinah,我已经发布了输出和输入。
  • 嗨@IMCoins,我没明白你的意思! :\

标签: python image csv


【解决方案1】:

根据您的问题,我想您想了解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 编写器并将您的 float64 更改为整数(这应该没问题,因为像素数据是 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 文件的一行。简而言之,我想将图像转换为其他任务的特征向量。
  • 我的回答应该给你所有你需要的代码。不过,我假设您所有的图像都具有相同的高度和宽度。如果没有,您可能需要在 csv 文件的每一行的开头添加“宽度,高度”。
  • 亲爱的@Pam,我在 python 方面没有太多经验。我已经编辑了我的代码。您可以再次检查我的代码吗?
  • @Zeinab 如果将图像保存为一维数组,您将如何知道它们的尺寸?您需要添加某种标题。
  • 这不是一个好主意 - 您想删除黑色像素而无法将它们放回原处?图像将被完全破坏。你的图片有多大?聪明的做法是调整它们的大小。列数是(宽 x 高),从中可以计算出图像需要多小。
【解决方案2】:

您如何将图像转换为 2D numpy 数组,然后将它们写为带有 .csv 扩展名和 , 作为分隔符的 txt 文件?

也许您可以使用如下代码:

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

【讨论】:

    【解决方案3】:
    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) 一样吗?
    【解决方案4】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多