#!/usr/bin/env python # # Copyright (C) 2014 Antonio Ospite # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys import Image def usage(program_name): sys.stderr.write("usage: %s \n" % program_name) sys.exit(1) # The code below has been copied from the C implementation in PatternPaint: # https://github.com/Blinkinlabs/PatternPaint def save_animation(input_filename, output_filename): output_file = open(output_filename, "w") img = Image.open(input_filename).convert('RGB') w, h = img.size colors = img.getcolors(w*h) palette = img.getpalette() pixels = img.getdata() output_file.write("const PROGMEM prog_uint8_t animationData[] = {\n") output_file.write("// Length of the color table - 1, in bytes. length: 1 byte\n") output_file.write(" %d,\n" % (len(colors) - 1)) output_file.write("// Color table section. Each entry is 3 bytes. length: %d bytes\n" % (len(colors) * 3)) color_map = {} for i, c in enumerate(colors): output_file.write(" %3d, %3d, %3d,\n" % (c[1][0], c[1][1], c[1][2])) color_map[c[1]] = i output_file.write("// Pixel runs section. Each pixel run is 2 bytes. length: -1 bytes\n") for x in range(0, w): run_count = 0 for y in range(0, h): new_color = color_map[pixels.getpixel((x, y))] if run_count == 0: current_color = new_color if current_color != new_color: output_file.write(" %3d, %3d,\n" % (run_count, current_color)) run_count = 1 current_color = new_color else: run_count += 1 output_file.write(" %3d, %3d,\n" % (run_count, current_color)) output_file.write("};\n\n") output_file.write("#define NUM_FRAMES %d\n" % w) output_file.write("#define NUM_LEDS %d\n" % h) output_file.write("Animation animation(NUM_FRAMES, animationData, NUM_LEDS);\n") output_file.close() if __name__ == "__main__": if len(sys.argv) < 3: usage(sys.argv[0]) save_animation(sys.argv[1], sys.argv[2])