如何将png转换为python的数据帧?
我为数字识别器()训练了一个模型。输入数据是一个csv文件。文件中的每一行表示一个图像,该图像的高度为28像素,宽度为28像素,总计784像素。该模型已准备好使用,但我想知道如何为该输入创建测试数据?如果我有一个带有数字的图像,如何将其转换为28×28像素的数组格式 我尝试了下面的代码,但它将图像背景渲染为黄色。png图像有白色背景,所以我不明白为什么它显示黄色如何将png转换为python的数据帧?,python,pandas,kaggle,Python,Pandas,Kaggle,我为数字识别器()训练了一个模型。输入数据是一个csv文件。文件中的每一行表示一个图像,该图像的高度为28像素,宽度为28像素,总计784像素。该模型已准备好使用,但我想知道如何为该输入创建测试数据?如果我有一个带有数字的图像,如何将其转换为28×28像素的数组格式 我尝试了下面的代码,但它将图像背景渲染为黄色。png图像有白色背景,所以我不明白为什么它显示黄色 import numpy as np import cv2 import csv import matplotlib.pyplot
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()
我为您准备了一个小例子,希望能让您了解如何完成此任务: 我使用此图像作为示例: 完整脚本:
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结构
自定义_test.csv输出(缩短):
编辑:
要使用matplotlib可视化展平图像,必须指定颜色贴图:
row = flattened.reshape(28,28)
plt.imshow(row, cmap='gray') # inverse grayscale is possible with: cmap='gray_r'
请提供CSV的示例。我已经尝试了您的代码,并通过
imshow
绘制了展平的图像,该图像具有黄色背景色。原始图像背景为白色,为什么会变为黄色?@ZhaoYi我更新了答案。如果我的回答对你有帮助,请投票/接受。谢谢
row = flattened.reshape(28,28)
plt.imshow(row, cmap='gray') # inverse grayscale is possible with: cmap='gray_r'