Python 以图像格式转换Mnist数据集

Python 以图像格式转换Mnist数据集,python,mnist,Python,Mnist,我想将mnist数据集转换为.csv文件中的图像格式,如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") 我使用上面的代码将像素转换为图像,我能够将其转换为图像

我想将mnist数据集转换为.csv文件中的图像格式,如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”,则图像将保存为黑色图像。
因此,我如何将图像转换为彩色格式。

您可以将整数保存为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')
>>> 

您可以将整数保存为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')
>>> 

im.save('temp.png')将图像保存在mongoDB数据库或任何特定文件夹中。因为我希望图像存储在mongoDB中。
post\u id=posts.insert\u one(post)。inserted\u id
将图像字节存储在mongoDB中。从
record=
开始,代码中只是演示了如何检索和使用字节,在本例中转换为
.png
图像并存储为文件。我应该在回答中提到,一些细节将取决于您对图像.im.save('temp.png')的目的将图像保存在mongoDB数据库或任何特定文件夹中。因为我希望图像存储在mongoDB中。
post\u id=posts.insert\u one(post)。inserted\u id
将图像字节存储在mongoDB中。从
record=
开始,代码中只是演示了如何检索和使用字节,在本例中转换为
.png
图像并存储为文件。我应该在回答中提到,一些细节将取决于您对图像的目的。