import os
from PIL import Image, ImageDraw

DAT_DIR = "E:/" # path to the folder with the .DAT files (source folder)
JPG_DIR = "C:/Users/nxf35196/Desktop/AN12892_software/Scripts/jpgs/" # path to the folder, where the .jpg files will be stored (destination folder)

for i in range(10):
    for filename in os.listdir(DAT_DIR + '/' + str(i)):
        with open(DAT_DIR + '/' + str(i) + '/' + filename, 'rb') as f:
            arr = f.read()
            os.makedirs(os.path.dirname(JPG_DIR + '/' + str(i) + '/' + filename[:-3] + 'jpg'), exist_ok=True)
            img = Image.frombuffer('L', (28,28), arr[:784],'raw', 'L', 0, 1)
            img.save(JPG_DIR + '/' + str(i) + '/' + filename[:-3] + 'jpg')