【问题标题】:Stack images as rows in csv file将图像堆叠为 csv 文件中的行
【发布时间】:2021-10-25 12:52:53
【问题描述】:

我正在尝试将文件夹中的图像保存为 csv 文件的行。在此 csv 中,每一行将对应于每个图像的像素值。为此,每个图像矩阵(例如 (720, 1280, 3))都被展平并重新整形为行 (1, 2764800)。此外,我将图像尺寸 (720, 1280) 添加为该行的前 2 个元素。这是因为处理了不同尺寸的图像。

我成功保存了一张图片的 csv 文件,但我想自动保存多张图片的过程。

这是我仅用于 1 张图片的代码

import pandas as pd
from PIL import Image 
import numpy as np 
import matplotlib.image as img

imageMat = img.imread('images/image1.jpg')
image_reshape = imageMat.flatten().reshape(-1, 1).T

image_csv = [] 
image_csv.append([imageMat.shape[0],imageMat.shape[1]]) 
image_csv = np.array(image_csv) 
image_csv = np.append(image_csv, image_reshape, axis=1) 

mat_df = pd.DataFrame(image_csv)   
mat_df.to_csv('gfgfile.csv', header = None, index = None)

【问题讨论】:

  • CSV 似乎是一个非常糟糕的选择。也许将实际图像的文件名放在 CSV 中,然后从该位置单独加载到内存中?
  • 你是对的@tripleee。感谢您的评论

标签: python pandas image numpy csv


【解决方案1】:

要自动化多个图像的代码,您可以选择要使用的图像文件名。为此,我们可以设置我们接受的图像格式,并使用此信息从文件夹中获取文件名,如下所示:

import os

#Defines image formats supported
image_formats = ['png','jpg','jpeg']
#Gets all filenames that correspond to images
filenames = [f for f in os.listdir('images/') if os.path.isfile('images/'+f) and f.split('.')[-1] in image_formats]

在上面的代码中,我们列出了文件夹 images/ 中所有对象的名称,并选择了那些是文件名并具有支持的图像扩展名的对象。

获得文件名后,我们可以遍历它们并应用您的代码,并进行一些修改,以对所有行进行分组并将它们保存在数据框中。

#List that stores all the images
image_list = []

#Loop over the filenames
for f in filenames:
    #Loads a new image
    imageMat = img.imread('images/'+f)
    #Transforms the image in the flatten array
    image_reshape = imageMat.flatten().reshape(-1, 1).T
    #Saves the image dimensions
    image_csv = [imageMat.shape[0],imageMat.shape[1]]
    #Appends a new row to the list of images, with the dimensions and the flattened image
    image_list.append(image_csv + image_reshape.tolist()[0])

#Creates the dataframe
mat_df = pd.DataFrame(np.array(image_list))
mat_df.to_csv('gfgfile.csv', header = None, index = None)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 2017-07-08
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-08-28
    • 2014-09-20
    相关资源
    最近更新 更多