以图像格式转换Mnist数据集

时间:2017-02-13 15:27:28

标签: python mnist

我想以图像格式转换.csv文件中可用的mnist数据集,如jpeg或png。

from PIL import Image
temp = mnist.train.images[0]
temp=np.reshape(temp,(28,28))
temp=temp*255
im = Image.fromarray(temp).convert('L')
im.save("C:/Users/user/Desktop/ML/image/img.png")

我使用上面的代码将像素转换为图像,我可以将其转换为图像,但问题是图像以黑白格式保存。 并在声明中

im = Image.fromarray(temp).convert('L')

如果我使用' RGB'而不是' L'图像保存为黑色图像。 那么如何将图像转换为彩色格式。

1 个答案:

答案 0 :(得分:0)

您可以将整数作为压缩字节保存在mongoDB中,以便您可以使用PIL以如下方式将压缩字节转换为图像。

此代码显示如何保存10个测试图像,然后检索其中一个并将其另存为.png

>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> db = client.test_database
>>> import csv
>>> from struct import pack
>>> posts = db.posts
>>> with open('mnist_test_10.csv') as mnist_csv:
...     mnist_reader = csv.reader(mnist_csv)
...     for row in mnist_reader:
...         digit = row[0]
...         pixels = pack((-1+len(row))*'B', *[int(_) for _ in row[1:]])
...         post = {'digit': digit, 'pixels': pixels}
...         post_id = posts.insert_one(post).inserted_id
...         
>>> record = posts.find_one({'digit':'7'})
>>> from PIL import Image
>>> im = Image.frombytes('L',(28,28),record['pixels'])
>>> im.save('temp.png')
>>> 
相关问题