1#!/usr/bin/python3 2""" Convert binary back to image. Use float32 as default. 3 4usage: convert_binary_to_img.py [-h] -i INPUT -s height width depth 5 6optional arguments: 7 -h, --help show this help message and exit 8 -i INPUT, --input INPUT 9 Path to input binary file. File extension needs to be .input. 10 -s height width depth, --shape height width depth 11 Output image shape. e.g. 224 224 3 12Example usage: 13python3 convert_binary_to_img.py -i image_file.input -s 224 224 3 14""" 15 16import argparse 17import os 18import sys 19 20import numpy as np 21from PIL import Image 22 23def convert_file(filename: str, h: int, w: int, d: int): 24 """Converts the input binary file back to image with shape following the input parameters. 25 26 Parameters 27 ---------- 28 h : int, height 29 w : int, width 30 d : int, depth 31 """ 32 with open(filename, 'rb') as f: 33 arr = np.frombuffer(f.read(), dtype=np.float32) 34 print(f'Reshape buffer from {arr.shape} to {(h, w, d)}.') 35 arr = arr.reshape((h, w, d)) 36 arr = (arr + 1) * 128 37 im = Image.fromarray(arr.astype(np.uint8)) 38 destination = filename.replace('input', 'jpg') 39 print(f'Image generated to {destination}.') 40 im.save(destination) 41 42if __name__ == '__main__': 43 parser = argparse.ArgumentParser() 44 parser.add_argument('-i','--input', type=str, required=True, help='Path to input binary file. File extension needs to be .input.') 45 parser.add_argument('-s','--shape', type=int, required=True, nargs=3, help='Output image shape. e.g. 224 224 3', metavar=('height', 'width', 'depth')) 46 args = parser.parse_args() 47 48 convert_file(args.input, *args.shape) 49