hueshift-pixel 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.3
2
+ Name: hueshift-pixel
3
+ Version: 0.1.0
4
+ Summary: Hue-shifted pixel-art color ramps from hex colors or a reference image.
5
+ Author: Enrico Shippole
6
+ Author-email: Enrico Shippole <enricoship@gmail.com>
7
+ Requires-Dist: numpy>=2.5.5
8
+ Requires-Dist: pillow>=13.0.0
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+
12
+ Generate hue-shifted pixel-art color ramps from hex colors or a reference image. Based on color theory from Color and Light by James Gurney.
13
+
14
+ Installation:
15
+ ```bash
16
+ uv pip install hueshift
17
+ ```
18
+
19
+ Usage:
20
+ ```bash
21
+ uv run hueshift 3a7bd5 e0533a [options]
22
+ uv run hueshift input.png [options]
23
+ ```
24
+
25
+ Options (defaults shown):
26
+ - `-n 9` shades per ramp (3–16)
27
+ - `-k 6` ramps to extract from an image
28
+ - `--shift mid` hue shift: `none`, `mid`, `strong`, or `LIGHT,DARK` degrees
29
+ - `--light ffd700` / `--shadow 2a0c42` colors highlights and shadows shift toward
30
+ - `--merge 0.04` make similar colors in different ramps identical (off by default)
31
+ - `--range 0.2 0.96` lightness range (`1` = pure white top)
32
+ - `--tint 0.03` warm/cool cast on grays
33
+ - `-o palette` writes `palette.png`, `.gpl`, `.hex`, `.aseprite`
34
+ - `--scale 16` swatch size in the PNG
@@ -0,0 +1,23 @@
1
+ Generate hue-shifted pixel-art color ramps from hex colors or a reference image. Based on color theory from Color and Light by James Gurney.
2
+
3
+ Installation:
4
+ ```bash
5
+ uv pip install hueshift
6
+ ```
7
+
8
+ Usage:
9
+ ```bash
10
+ uv run hueshift 3a7bd5 e0533a [options]
11
+ uv run hueshift input.png [options]
12
+ ```
13
+
14
+ Options (defaults shown):
15
+ - `-n 9` shades per ramp (3–16)
16
+ - `-k 6` ramps to extract from an image
17
+ - `--shift mid` hue shift: `none`, `mid`, `strong`, or `LIGHT,DARK` degrees
18
+ - `--light ffd700` / `--shadow 2a0c42` colors highlights and shadows shift toward
19
+ - `--merge 0.04` make similar colors in different ramps identical (off by default)
20
+ - `--range 0.2 0.96` lightness range (`1` = pure white top)
21
+ - `--tint 0.03` warm/cool cast on grays
22
+ - `-o palette` writes `palette.png`, `.gpl`, `.hex`, `.aseprite`
23
+ - `--scale 16` swatch size in the PNG
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "hueshift-pixel"
3
+ version = "0.1.0"
4
+ description = "Hue-shifted pixel-art color ramps from hex colors or a reference image."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "numpy>=2.5.5",
9
+ "pillow>=13.0.0",
10
+ ]
11
+
12
+ [[project.authors]]
13
+ name = "Enrico Shippole"
14
+ email = "enricoship@gmail.com"
15
+
16
+ [project.scripts]
17
+ hueshift = "hueshift.main:main"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.12.19,<0.13.0"]
21
+ build-backend = "uv_build"
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "hueshift-pixel"
3
+ version = "0.1.0"
4
+ description = "Hue-shifted pixel-art color ramps from hex colors or a reference image."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Enrico Shippole", email = "enricoship@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "numpy>=2.5.5",
12
+ "pillow>=13.0.0",
13
+ ]
14
+
15
+ [project.scripts]
16
+ hueshift = "hueshift.main:main"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.12.19,<0.13.0"]
20
+ build-backend = "uv_build"
@@ -0,0 +1,4 @@
1
+ from .config import SHIFTS
2
+ from .core import to_lab, extract, save, merge, ramp, hue
3
+
4
+ __all__ = ["to_lab", "extract", "save", "merge", "ramp", "hue", "SHIFTS"]
@@ -0,0 +1 @@
1
+ SHIFTS = {'none': (0, 0), 'mid': (60, 25), 'strong': (115, 75)}
@@ -0,0 +1,142 @@
1
+ import struct
2
+ import sys
3
+ import zlib
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+ M1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929],
10
+ [0.2119034982, 0.6806995451, 0.1073969566],
11
+ [0.0883024619, 0.2817188376, 0.6299787005]])
12
+ M2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468],
13
+ [1.9779984951, -2.4285922050, 0.4505937099],
14
+ [0.0259040371, 0.7827717662, -0.8086757660]])
15
+ M1I, M2I = np.linalg.inv(M1), np.linalg.inv(M2)
16
+
17
+
18
+ def to_lab(rgb):
19
+ c = np.asarray(rgb, float) / 255
20
+ c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
21
+ return np.cbrt(c @ M1.T) @ M2.T
22
+
23
+
24
+ def lin(L, z):
25
+ return (np.array([L, z.real, z.imag]) @ M2I.T) ** 3 @ M1I.T
26
+
27
+
28
+ def to_rgb(L, z):
29
+ c = np.clip(lin(L, z), 0, 1)
30
+ c = np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
31
+ return tuple(int(v) for v in np.round(c * 255))
32
+
33
+
34
+ def hue(z):
35
+ return np.angle(z, deg=True) % 360
36
+
37
+
38
+ def cmax(L, h):
39
+ u, lo, hi = np.exp(1j * np.radians(h)), 0.0, 0.5
40
+ for _ in range(24):
41
+ m = (lo + hi) / 2
42
+ c = lin(L, m * u)
43
+ lo, hi = (m, hi) if c.min() >= -1e-6 and c.max() <= 1 + 1e-6 else (lo, m)
44
+ return lo
45
+
46
+
47
+ def ramp(L, z, n, light, shadow, shift, tint, lo, hi):
48
+ h = hue(z)
49
+ rel = abs(z) / max(cmax(L, h), 1e-9)
50
+ lo, hi = min(lo, L / 2), max(hi, (L + 1) / 2)
51
+ b = int(np.clip(round((L - lo) / (hi - lo) * (n - 1)), 1, n - 2))
52
+ out = []
53
+ for i in range(n):
54
+ up = i > b
55
+ s = (i - b) / (n - 1 - b) if up else (b - i) / b
56
+ t, deg, sat = (light, shift[0], 0.5) if up else (shadow, shift[1], 0.86)
57
+ d = (t - h + 180) % 360 - 180
58
+ hs = h + np.sign(d) * min(abs(d), deg * s)
59
+ e = 1 - (1 - s) ** 1.3
60
+ Ls = L + (hi - L) * e if up else L - (L - lo) * e
61
+ c = rel * (1 + (sat - rel) * s) * cmax(Ls, hs)
62
+ zs = c * np.exp(1j * np.radians(hs)) + tint * (1 - rel) * s * np.exp(1j * np.radians(t))
63
+ out.append(to_rgb(Ls, min(abs(zs), cmax(Ls, hue(zs))) * np.exp(1j * np.angle(zs))))
64
+ return out, b
65
+
66
+
67
+ def merge(ramps, tol, fixed):
68
+ cols = [c for r in ramps for c in r]
69
+ n, lab = len(ramps[0]), to_lab(np.array(cols))
70
+ D = np.linalg.norm(lab[:, None] - lab[None], axis=-1)
71
+ rep, grp = list(range(len(cols))), {i: {i} for i in range(len(cols))}
72
+ pairs = sorted((D[i, j], i, j) for i in range(len(cols)) for j in range(i) if i // n != j // n and D[i, j] < tol)
73
+ for _, i, j in pairs:
74
+ a, b = rep[i], rep[j]
75
+ if a == b or (a in fixed and b in fixed) or {m // n for m in grp[a]} & {m // n for m in grp[b]}:
76
+ continue
77
+ g = grp[a] | grp[b]
78
+ for r in [x for x in (a, b) if x in fixed] or sorted((a, b), key=lambda x: max(D[x, m] for m in g)):
79
+ if max(D[r, m] for m in g) <= tol and all(
80
+ (m % n == 0 or lab[rep[m - 1], 0] < lab[r, 0]) and
81
+ (m % n == n - 1 or lab[rep[m + 1], 0] > lab[r, 0]) for m in g):
82
+ for m in g:
83
+ rep[m] = r
84
+ del grp[a], grp[b]
85
+ grp[r] = g
86
+ break
87
+ return [[cols[rep[k * n + j]] for j in range(n)] for k in range(len(ramps))]
88
+
89
+
90
+ def extract(path, k):
91
+ im = Image.open(path).convert('RGBA')
92
+ im.thumbnail((256, 256), Image.Resampling.NEAREST)
93
+ px = np.asarray(im).reshape(-1, 4)
94
+ rgb, w = np.unique(px[px[:, 3] > 127, :3], axis=0, return_counts=True)
95
+ if not len(rgb):
96
+ raise ValueError('no opaque pixels in image')
97
+ lab = to_lab(rgb)
98
+ ab = lab[:, 1] + 1j * lab[:, 2]
99
+ rng = np.random.default_rng(0)
100
+ c = ab[[w.argmax()]]
101
+ while len(c) < k:
102
+ d = np.abs(ab[:, None] - c).min(1)
103
+ if d.max() < 0.02:
104
+ break
105
+ c = np.append(c, rng.choice(ab, p=d ** 2 * w / (d ** 2 * w).sum()))
106
+ for _ in range(50):
107
+ lbl = np.abs(ab[:, None] - c).argmin(1)
108
+ c = np.array([np.average(ab[lbl == j], weights=w[lbl == j]) if (lbl == j).any() else c[j]
109
+ for j in range(len(c))])
110
+ lbl = np.abs(ab[:, None] - c).argmin(1)
111
+ bases = [(np.average(lab[lbl == j, 0], weights=w[lbl == j]), c[j]) for j in range(len(c)) if (lbl == j).any()]
112
+ return sorted(bases, key=lambda b: (abs(b[1]) > 0.03, hue(b[1])))
113
+
114
+
115
+ def save_ase(path, ramps, pal, name):
116
+ h, w = len(ramps), len(ramps[0])
117
+ chunk = lambda t, d: struct.pack('<IH', len(d) + 6, t) + d
118
+ frame = b''.join([
119
+ chunk(0x2007, struct.pack('<HHI8x', 1, 0, 0)),
120
+ chunk(0x2019, struct.pack('<III8x', len(pal), 0, len(pal) - 1) +
121
+ b''.join(struct.pack('<H4BH', 1, *c, 255, len(x)) + x.encode() for x, c in pal)),
122
+ chunk(0x2004, struct.pack('<6HB3xH', 3, 0, 0, 0, 0, 0, 255, len(name)) + name),
123
+ chunk(0x2005, struct.pack('<HhhBHh5x2H', 0, 0, 0, 255, 2, 0, w, h) +
124
+ zlib.compress(bytes(v for row in ramps for c in row for v in (*c, 255))))])
125
+ frame = struct.pack('<IHHH2xI', 16 + len(frame), 0xF1FA, 4, 100, 4) + frame
126
+ Path(path).write_bytes(struct.pack('<IHHHHHIHIIB3xHBBhhHH84x', 128 + len(frame), 0xA5E0, 1, w, h, 32, 1,
127
+ 100, 0, 0, 0, len(pal), 1, 1, 0, 0, 16, 16) + frame)
128
+
129
+
130
+ def save(ramps, out, scale):
131
+ arr = np.array(ramps, np.uint8)
132
+ Image.fromarray(arr).resize((arr.shape[1] * scale, arr.shape[0] * scale), Image.Resampling.NEAREST).save(f'{out}.png')
133
+ hexes = [[f'{r:02x}{g:02x}{b:02x}' for r, g, b in row] for row in ramps]
134
+ uniq = dict.fromkeys((h, c) for row, hr in zip(ramps, hexes) for c, h in zip(row, hr))
135
+ Path(f'{out}.hex').write_text(''.join(h + '\n' for h, _ in uniq))
136
+ Path(f'{out}.gpl').write_text(f'GIMP Palette\nName: {Path(out).stem}\nColumns: {arr.shape[1]}\n#\n' +
137
+ ''.join(f'{r:3d} {g:3d} {b:3d}\t{h}\n' for h, (r, g, b) in uniq))
138
+ save_ase(f'{out}.aseprite', ramps, list(uniq), Path(out).stem.encode())
139
+ tty = sys.stdout.isatty()
140
+ for row, hr in zip(ramps, hexes):
141
+ print(' '.join((f'\x1b[48;2;{r};{g};{b}m \x1b[0m' if tty else '') + h for (r, g, b), h in zip(row, hr)))
142
+ print(f'{len(uniq)} colors')
@@ -0,0 +1,52 @@
1
+ import argparse
2
+ import re
3
+ from pathlib import Path
4
+
5
+ from .config import SHIFTS
6
+ from .core import extract, hue, merge, ramp, save, to_lab
7
+
8
+
9
+ def shift_arg(s):
10
+ if s in SHIFTS:
11
+ return SHIFTS[s]
12
+ v = [float(x) for x in s.split(',')]
13
+ return v[0], v[-1]
14
+
15
+
16
+ def main():
17
+ p = argparse.ArgumentParser(description=__doc__)
18
+ p.add_argument('src', nargs='+', help='hex colors (e.g. 3a7bd5 e0533a) or one reference image')
19
+ p.add_argument('-n', '--steps', type=int, default=9, help='shades per ramp, 3-16')
20
+ p.add_argument('-k', '--ramps', type=int, default=6, help='ramps to extract from an image')
21
+ p.add_argument('--shift', type=shift_arg, default='mid',
22
+ help='none | mid | strong | degrees as LIGHT,DARK (e.g. 80,40)')
23
+ p.add_argument('--light', default='ffd700', help='color highlights shift toward (sunlight)')
24
+ p.add_argument('--shadow', default='2a0c42', help='color shadows shift toward (sky-lit shadow)')
25
+ p.add_argument('--tint', type=float, default=0.03, help='light/shadow cast on grays (0 = none)')
26
+ p.add_argument('--range', type=float, nargs=2, default=(0.2, 0.96), metavar=('DARK', 'LIGHT'),
27
+ help='lightness range 0-1; 1 = pure white top')
28
+ p.add_argument('--merge', type=float, default=0, metavar='TOL',
29
+ help='make similar colors in different ramps identical (OKLab distance, e.g. 0.04)')
30
+ p.add_argument('-o', '--out', default='palette', help='output name; writes .png .gpl .hex .aseprite')
31
+ p.add_argument('--scale', type=int, default=16, help='swatch size in the PNG')
32
+ a = p.parse_args()
33
+ image = len(a.src) == 1 and Path(a.src[0]).is_file()
34
+ if not 3 <= a.steps <= 16:
35
+ p.error('--steps must be 3-16')
36
+ for s in [a.light, a.shadow] + ([] if image else a.src):
37
+ if not re.fullmatch(r'#?[0-9a-fA-F]{6}', s):
38
+ p.error(f'invalid hex color or missing image: {s}')
39
+ lab = lambda s: to_lab([int(s.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4)])
40
+ try:
41
+ bases = extract(a.src[0], a.ramps) if image else [(v[0], complex(*v[1:])) for v in map(lab, a.src)]
42
+ except (OSError, ValueError) as e:
43
+ p.error(str(e))
44
+ lh, sh = (hue(complex(*lab(s)[1:])) for s in (a.light, a.shadow))
45
+ ramps, bs = zip(*(ramp(L, z, a.steps, lh, sh, a.shift, a.tint, *a.range) for L, z in bases))
46
+ if a.merge > 0:
47
+ ramps = merge(ramps, a.merge, {k * a.steps + b for k, b in enumerate(bs)})
48
+ save(ramps, a.out, a.scale)
49
+
50
+
51
+ if __name__ == '__main__':
52
+ main()