Photo ViewerΒΆ

Simple Python program that reads a specified image file and calculates a color matrix based on this image by averaging the pixels. The image is then set on the keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""
Author: RedFantom
License: GNU GPLv3
Copyright (c) 2018-2019 RedFantom
"""
import masterkeys as mk
from os import path
from PIL import Image
import sys


def print_progress(done, total):
    """Print a progress bar using #"""
    filled, percent = int(60 * done / total), done * 100 / total
    bar = "[{}]".format("#" * filled + " " * (60 - filled))
    sys.stdout.write("\r{} {:02.1f}%\r".format(bar, percent))
    sys.stdout.flush()


if __name__ == '__main__':
    """
    Open a file from a path given on input and process that to create a 
    grid of key colors to set on the keyboard.
    """
    # Open the file
    file = input("File: ")
    if not path.exists(file):
        print("That file does not exist.")
        exit(-1)
    img = Image.open(file)

    # Process the image
    w, h = img.size
    pixels = img.load()
    layout = mk.build_layout_list()
    w_p_c, h_p_r = (w // mk.MAX_COLS), (h // mk.MAX_ROWS)
    done, total = 0, mk.MAX_ROWS * mk.MAX_COLS
    for r in range(mk.MAX_ROWS):
        for c in range(mk.MAX_COLS):
            sums = [0, 0, 0]
            xrange = list(range(w_p_c * c, w_p_c * (c + 1)))
            yrange = list(range(h_p_r * r, h_p_r * (r + 1)))
            for x in xrange:
                for y in yrange:
                    for i in range(3):
                        sums[i] += pixels[x, y][i]
            color = (v // (w_p_c * h_p_r) for v in sums)
            color = tuple(map(int, color))
            layout[r][c] = color

            done += 1
            print_progress(done, total)
    print()

    # Update the color of the keyboard
    devices = mk.detect_devices()
    if len(devices) == 0:
        print("No devices connected.")
        exit(-2)
    mk.set_device(devices[0])
    mk.enable_control()
    mk.set_all_led_color(layout)
    mk.disable_control()