【问题标题】:How to convert 1D array of pixels to image in python?如何将一维像素数组转换为python中的图像?
【发布时间】:2018-09-13 04:15:54
【问题描述】:

这是关于FER2013 dataset。数据由 48x48 像素的人脸灰度图像组成。 CSV 文件包含三列(情感、像素、使用情况),其中使用具有三个值中的任何一个 - 训练、私人测试和公共测试。我想读取像素数组,将它们转换为图像并将它们保存在根据其使用类型命名的相应文件夹中。

我需要可以执行上述操作的 python 代码。 以下是我的代码

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

df=pd.read_csv("fer2013.csv")
for rows in df:
  
   arr=np.array(df['pixels'])
   print(arr)
   print(arr.shape)
   img = Image.fromarray(arr.reshape(48,48), 'L')
   img.save("dataset/df['Usage']/img.jpg", "JPEG")

以上代码显示错误:

无法将大小为 35887 的数组重新整形为 (48,48)。

【问题讨论】:

  • 我也很困惑像素数组(每个图像是 48*48 像素)如何具有形状 (35887, )。
  • 这些像素是如何创建这样大小的图像的?这甚至不是一个完美的正方形。你应该有一个 2304 长度的数组
  • 我认为你的意思是写 arr = np.array(rows['pixels']) 或类似的东西
  • @chrisz 谢谢,您提供的代码有效。但是对于通过 fromarray 将像素数组转换为图像仍然不起作用。其显示错误为:“numpy.ndarray”对象没有属性“掩码”
  • @MohammadAthar 是的,这是我犯的错误之一。谢谢。

标签: python image detection emotion


【解决方案1】:

如果有任何疑问(因为我一直在使用 FER 数据集):

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

df = pd.read_csv('fer2013.csv')
for image_pixels in df.iloc[1:,1]: #column 2 has the pixels. Row 1 is column name.
    image_string = image_pixels.split(' ') #pixels are separated by spaces.
    image_data = np.asarray(image_string, dtype=np.uint8).reshape(48,48)
    img = Image.fromarray(image_data) #final image

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 2019-01-19
    • 1970-01-01
    • 2019-08-13
    • 2021-12-17
    • 2020-12-26
    • 2017-10-06
    • 2021-12-22
    • 2020-12-15
    相关资源
    最近更新 更多