如何将png转换为python的数据帧?

2024-06-11 11:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我为数字识别器(https://www.kaggle.com/c/digit-recognizer/data)训练了一个模型。输入数据是一个csv文件。文件中的每一行表示一个高28像素宽28像素的图像,总共784像素。模型已经可以使用了,但是我想知道如何为这个输入创建一个测试数据?如果我有一个数字图像,我怎么能把它转换成28乘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()

Tags: 文件csv模型图像imageimportimgpng
1条回答
网友
1楼 · 发布于 2024-06-11 11:15:01

我为你准备了一个小例子,希望能给你一个如何完成这项任务的想法:

我以这张图片为例:

example image

完整脚本:

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结构。你知道吗

自定义_测试.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'

相关问题 更多 >