convert mnist to pictures in python

To convert MNIST dataset images to actual pictures in python, follow the steps below:

  1. Import the required libraries
main.py
import numpy as np
from PIL import Image
41 chars
3 lines
  1. Load the MNIST dataset train-images-idx3-ubyte.gz
main.py
with open("train-images-idx3-ubyte", "rb") as f:
    f.read(16) # skip the first 16 bytes
    data = np.fromfile(f, dtype=np.uint8).reshape(-1, 28, 28)
152 chars
4 lines
  1. Convert the data to grayscale images of type uint8
main.py
for i in range(len(data)):
    image = Image.fromarray(data[i], mode='L')
    image.save(f'images/{i}.png')
108 chars
4 lines
  1. The images will be saved in a folder named images in your current directory.

gistlibby LogSnag