【问题标题】:Saving images to csv file and then reading it from csv file将图像保存到 csv 文件,然后从 csv 文件中读取
【发布时间】:2020-12-16 07:14:36
【问题描述】:

我已使用以下代码将图像转换为 csv:

import pandas as pd
from PIL import Image 
import numpy as np 


image_array = []
for name in combined_df['path']:
    image_array.append(np.array(Image.open(name)))

image_df_1 = pd.DataFrame(image_array)     #Then coverted list to dataframe

image_df_1.to_csv('image.csv', index=False) # exported it to csv  (question 1)


csv_df = pd.read_csv('image.csv')  # exported csv using pandas   (question 2)

# I want to see images from csv file but there is problem

np.array(csv_df.iloc[0][0]).shape         # (question 3)
Output: ()      

# but if I see shape of dataframe before saving it to csv

np.array(image_df_1.iloc[0][0]).shape
output: (466, 806, 3)

有什么我做错了吗:

  1. 将数据帧保存到 csv 文件时?
  2. 还是在读取 csv 文件时?
  3. 还是在将值转换为数组时?
# data is available but not able to convert in from of array

csv_df.iloc[0][0]

Output: '[[[180 193 212]\n  [181 194 213]\n  [182 195 214]\n  ...\n  [177 190 209]\n  [177 190 209]\n  [177 190 209]]\n\n [[180 193 212]\n  [181 194 213]\n 

请指教。

【问题讨论】:

  • 不能使用image_df_1.to_json('image.csv', index=False)将其保存为json文件吗?

标签: python pandas numpy csv python-imaging-library


【解决方案1】:

简答:

答案是 1:保存到 csv 时,多维 DataFrame 变成了简单的字符串。所以从 csv 读取后,DataFrame 单元格类型变为 str。 => 从 csv 读取后,csv_df.iloc[0][0] 的类型为 str。但image_df_1.iloc[0][0] 的类型是list(3D 嵌套列表)。

长答案:

这是因为当你将多维DataFrame保存到csv中时,csv变成了纯文本,然后当你将csv读入新的DataFrame时,新的DataFrame并不是多维的,它只是一个带有字符串单元格的2D DataFrame .

因此,您的代码中 csv_df.iloc[0][0] 的类型是字符串,而 image_df_1.iloc[0][0] 的类型是 3D 嵌套列表。

所以你的完整答案是 1 和 2 的组合:它将字符串写入 csv,然后在将 csv 转换为 DataFrame 时读取字符串。

看看我对你的代码的模拟:

>>> image_df_1 = pd.DataFrame([ [ [1, 2], [1, 2] ], [[1, 2], [1, 2] ], [ [1, 2], [1, 2] ], [[1, 2], [1, 2] ] ])  # a multidimensional DataFrame
>>> image_df_1.to_csv('image.csv', index=False)
>>> csv_df = pd.read_csv('image.csv')
>>> csv_df.iloc[0][0]
'[1, 2]'
>>> image_df_1.iloc[0][0]
[1, 2]
>>> type(csv_df.iloc[0][0])
<class 'str'>
>>> type(image_df_1.iloc[0][0])
<class 'list'>
>>> 

可以看到csv_df.iloc[0][0]的类型是strimage_df_1.iloc[0][0]的类型是list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2015-10-01
    • 1970-01-01
    相关资源
    最近更新 更多