blob: ee1ef440e80e828858ac62e37cdbb1d7321406b8 [file] [log] [blame]
Scott Todd7ca0f462022-06-09 09:30:05 -07001#!/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 Todd07480912022-06-09 13:30:41 -07009# 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 Todd7ca0f462022-06-09 09:30:05 -070013import sys
14from PIL import Image
15import numpy as np
16
17# Read image from stdin (in any format supported by PIL).
18with Image.open(sys.stdin.buffer) as color_img:
Jakub Kuderskibe24f022023-06-21 14:44:18 -040019 # 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())