Scott Todd | 7ca0f46 | 2022-06-09 09:30:05 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # Copyright 2022 The IREE Authors |
| 4 | # |
| 5 | # Licensed under the Apache License v2.0 with LLVM Exceptions. |
| 6 | # See https://llvm.org/LICENSE.txt for license information. |
| 7 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 8 | |
Scott Todd | 0748091 | 2022-06-09 13:30:41 -0700 | [diff] [blame] | 9 | # This script converts an image into a 28x28 grayscale f32 buffer. |
| 10 | # Usage: |
| 11 | # cat image.png | python3 convert_image.py > converted_image.bin |
| 12 | |
Scott Todd | 7ca0f46 | 2022-06-09 09:30:05 -0700 | [diff] [blame] | 13 | import sys |
| 14 | from PIL import Image |
| 15 | import numpy as np |
| 16 | |
| 17 | # Read image from stdin (in any format supported by PIL). |
| 18 | with Image.open(sys.stdin.buffer) as color_img: |
Jakub Kuderski | be24f02 | 2023-06-21 14:44:18 -0400 | [diff] [blame] | 19 | # Resize to 28x28, matching what the program expects. |
| 20 | resized_color_img = color_img.resize((28, 28)) |
| 21 | # Convert to grayscale. |
| 22 | grayscale_img = resized_color_img.convert("L") |
| 23 | # Rescale to a float32 in range [0.0, 1.0]. |
| 24 | grayscale_arr = np.array(grayscale_img) |
| 25 | grayscale_arr_f32 = grayscale_arr.astype(np.float32) / 255.0 |
| 26 | # Write bytes back out to stdout. |
| 27 | sys.stdout.buffer.write(grayscale_arr_f32.tobytes()) |