~cryptoxic/dumb-dithering

e923d82481442a898b2854e16080bd3faced4b52 — cryptoxic 2 months ago
Initial commit
2 files changed, 50 insertions(+), 0 deletions(-)

A dumb_dithering.py
A themes.json
A  => dumb_dithering.py +49 -0
@@ 1,49 @@
#!/usr/bin/python
import json
from math import sqrt
from collections import namedtuple
from PySide6.QtGui import QImage

Rgb = namedtuple('Rgb', 'r, g, b')

def main():
    themes = json.load(open("themes.json"))

    theme = themes["solarized"]
    rgb_theme = {}
    for name, color in theme.items():
        triple = color.strip("#")
        red = int(triple[0:2], 16)
        green = int(triple[2:4], 16)
        blue = int(triple[4:6], 16)
        rgb_theme[name] = Rgb(r=red, g=green, b=blue)

    pic = QImage()
    pic.load("test2.jpg")

    lines = pic.sizeInBytes() // pic.bytesPerLine()
    for line in range(0, lines):
        pic_line = pic.scanLine(line)
        pic_line.tolist()
        cols = (len(pic_line) // 4) * 4
        for x in range(0, cols, 4):
            dist = {}
            pixel = Rgb(pic_line[x], pic_line[x+1], pic_line[x+2])
            for name, color in rgb_theme.items():
                dist[name] = distance(pixel, color)
                sorted_dist = sorted(dist.items(), key=lambda x: x[1])
            pic_line[x] = rgb_theme[sorted_dist[0][0]].r
            pic_line[x+1] = rgb_theme[sorted_dist[0][0]].g
            pic_line[x+2] = rgb_theme[sorted_dist[0][0]].b
    pic.save("newtest2.jpg")


def distance(initial, target):
    dist_r = (initial.r - target.r)**2
    dist_g = (initial.g - target.g)**2
    dist_b = (initial.b - target.b)**2
    return sqrt(dist_r + dist_g + dist_b)


if __name__ == "__main__":
    main()

A  => themes.json +1 -0
@@ 1,1 @@
{"solarized": {"Base03": "#002b36", "Base02": "#073642", "Base01": "#586e75", "Base00": "#657b83", "Base0": "#839496", "Base1": "#93a1a1", "Base2": "#eee8d5", "Base3": "#fdf6e3", "Yellow": "#b58900", "Orange": "#cb4b16", "Red": "#dc322f", "Magenta": "#d33682", "Violet": "#6c71c4", "Blue": "#268bd2", "Cyan": "#2aa198", "Green": "#859900"}}
\ No newline at end of file