【问题标题】:How can I convert a png to a dataframe for python?如何将 png 转换为 python 的数据框?
【发布时间】:2019-04-29 06:53:50
【问题描述】:

我为数字识别器 (https://www.kaggle.com/c/digit-recognizer/data) 训练了一个模型。输入数据是一个 csv 文件。文件中的每一行代表一个高 28 像素、宽 28 像素的图像,总共 784 像素。该模型已准备好使用,但我想知道如何为此输入创建测试数据?如果我有一个带有数字编号的图像,如何将其转换为 28 x 28 像素的数组格式。

我尝试了下面的代码,但它将图像背景呈现为黄色。 png 图像有白色背景,所以我不明白为什么它显示为黄色。

import numpy as np
import cv2 
import csv 
import matplotlib.pyplot as plt

img = cv2.imread('./test.png', 0) # load grayscale image. Shape (28,28)

flattened = img.flatten() # flatten the image, new shape (784,)
row = flattened.reshape(28,28)

plt.imshow(row)
plt.show()

【问题讨论】:

  • 请提供 CSV 样本。

标签: python pandas kaggle


【解决方案1】:

我为你准备了一个小例子,希望它能让你了解如何完成这项任务:

我以这张图片为例:

完整脚本:

import numpy as np
import cv2 
import csv 

img = cv2.imread('./1.png', 0) # load grayscale image. Shape (28,28)

flattened = img.flatten() # flatten the image, new shape (784,)

flattened = np.insert(flattened, 0, 0) # insert the label at the beginning of the array, in this case we add a 0 at the index 0. Shape (785,0)


#create column names 
column_names = []
column_names.append("label")
[column_names.append("pixel"+str(x)) for x in range(0, 784)] # shape (785,0)

# write to csv 
with open('custom_test.csv', 'w') as file:
    writer = csv.writer(file, delimiter=';')
    writer.writerows([column_names]) # dump names into csv
    writer.writerows([flattened]) # add image row 
    # optional: add addtional image rows

现在您的 csv 结构与示例中提供的相同。

custom_test.csv 输出(缩短):

label;pixel0;pixel1;pixel2;pixel3;pixel4;pixel5;pixel6;pixel7;pixel ...
0;0;0;0;0;0;0;0;0;0;0;0....

编辑: 要使用 matplotlib 可视化展平图像,您必须指定颜色图:

row = flattened.reshape(28,28)
plt.imshow(row, cmap='gray') # inverse grayscale is possible with: cmap='gray_r'

【讨论】:

  • 我已经尝试了您的代码,并绘制了由imshow 扁平化的图形,这给了我黄色背景色的图像。原图是白色背景为什么变成黄色?
  • @ZhaoYi 我更新了我的答案。如果对您有帮助,请投票/接受我的回答。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 2011-06-05
  • 2022-11-22
  • 2018-05-02
  • 2013-09-21
  • 2018-12-08
相关资源
最近更新 更多