duotonics 1.0.0__py3-none-any.whl
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.
duotone_generator.py
ADDED
|
@@ -0,0 +1,993 @@
|
|
|
1
|
+
"""Duotonics: pure duotone processing with GUI and CLI shells."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import csv
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import stat
|
|
14
|
+
import struct
|
|
15
|
+
import tempfile
|
|
16
|
+
import warnings
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
|
|
19
|
+
import cv2
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
__version__ = "1.0.0"
|
|
23
|
+
|
|
24
|
+
DEFAULT_VARIATION_COUNT = 100
|
|
25
|
+
|
|
26
|
+
# Extensions accepted by convert_to_duotone. Anything else is rejected before
|
|
27
|
+
# loading, so failures are reported against the advertised formats.
|
|
28
|
+
SUPPORTED_EXTENSIONS = (".jpg", ".jpeg", ".png", ".bmp")
|
|
29
|
+
|
|
30
|
+
# Longest permitted image side in pixels. Images whose total pixel count
|
|
31
|
+
# exceeds MAX_IMAGE_DIMENSION ** 2 are rejected from the file header before
|
|
32
|
+
# any decode, so accidental gigapixel inputs cannot exhaust memory.
|
|
33
|
+
MAX_IMAGE_DIMENSION = 15000
|
|
34
|
+
|
|
35
|
+
# Blend spaces accepted by convert_to_duotone and create_duotone_image.
|
|
36
|
+
# 'srgb' preserves the pre-Duotonics implementation behavior exactly;
|
|
37
|
+
# 'linear' and 'oklab' blend over a relative-luminance key instead of the
|
|
38
|
+
# legacy luma key.
|
|
39
|
+
SPACES = ("srgb", "linear", "oklab")
|
|
40
|
+
|
|
41
|
+
# Maximum pixels processed together for the CIEDE2000 metric. The full
|
|
42
|
+
# difference plane is retained for statistics, but Lab arrays stay tile-sized.
|
|
43
|
+
_CIEDE2000_TILE_PIXELS = 1_000_000
|
|
44
|
+
|
|
45
|
+
# Fixed sRGB (IEC 61966-2-1) to XYZ matrix and D65 white point, used by the
|
|
46
|
+
# CIEDE2000 metric only.
|
|
47
|
+
_SRGB_TO_XYZ = np.array((
|
|
48
|
+
(0.4124564, 0.3575761, 0.1804375),
|
|
49
|
+
(0.2126729, 0.7151522, 0.0721750),
|
|
50
|
+
(0.0193339, 0.1191920, 0.9503041),
|
|
51
|
+
), dtype=np.float32)
|
|
52
|
+
_D65_WHITE = np.array((0.95047, 1.0, 1.08883), dtype=np.float32)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _success_message(output_folder: str, count: int) -> str:
|
|
56
|
+
"""Build the completion message shared by the GUI and CLI shells."""
|
|
57
|
+
noun = "variation" if count == 1 else "variations"
|
|
58
|
+
return f"{count} duotone {noun} generated successfully in '{output_folder}'."
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def select_image() -> None:
|
|
62
|
+
"""Open file dialogs to select a source image and output directory, then process."""
|
|
63
|
+
from tkinter import filedialog, messagebox
|
|
64
|
+
|
|
65
|
+
image_path = filedialog.askopenfilename(
|
|
66
|
+
filetypes=[("Image files", " ".join(f"*{e}" for e in SUPPORTED_EXTENSIONS))]
|
|
67
|
+
)
|
|
68
|
+
if not image_path:
|
|
69
|
+
return
|
|
70
|
+
output_dir = filedialog.askdirectory(title="Select output directory")
|
|
71
|
+
if not output_dir:
|
|
72
|
+
return
|
|
73
|
+
# Surface each conversion failure in the GUI rather than hiding it.
|
|
74
|
+
try:
|
|
75
|
+
output_folder, records = convert_to_duotone(image_path, output_dir=output_dir)
|
|
76
|
+
except Exception as e: # noqa: BLE001
|
|
77
|
+
messagebox.showerror("Error", f"An error occurred: {e!s}")
|
|
78
|
+
return
|
|
79
|
+
messagebox.showinfo("Success", _success_message(output_folder, len(records)))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def generate_random_color(rng: random.Random | None = None) -> list[int]:
|
|
83
|
+
"""Generate a random RGB color, optionally from a seeded Random instance."""
|
|
84
|
+
source = rng if rng is not None else random
|
|
85
|
+
return [source.randint(0, 255) for _ in range(3)]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def rgb_to_hex(color: list[int]) -> str:
|
|
89
|
+
"""Convert an RGB list to a hex string."""
|
|
90
|
+
return f"#{color[0]:02X}{color[1]:02X}{color[2]:02X}"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def hex_to_rgb(value: str) -> list[int]:
|
|
94
|
+
"""
|
|
95
|
+
Convert a hex color string to an RGB list.
|
|
96
|
+
|
|
97
|
+
Accepts '#RRGGBB' and 'RRGGBB', case-insensitively.
|
|
98
|
+
Raises ValueError for anything else.
|
|
99
|
+
"""
|
|
100
|
+
text = value.strip().removeprefix("#")
|
|
101
|
+
if re.fullmatch(r"[0-9A-Fa-f]{6}", text) is None:
|
|
102
|
+
raise ValueError(f"Invalid hex color '{value}': expected '#RRGGBB'.")
|
|
103
|
+
return [int(text[i:i + 2], 16) for i in (0, 2, 4)]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def parse_color_pair(spec: str) -> tuple[list[int], list[int]]:
|
|
107
|
+
"""Parse a 'HEX1,HEX2' string into a pair of RGB lists."""
|
|
108
|
+
parts = spec.split(",")
|
|
109
|
+
if len(parts) != 2:
|
|
110
|
+
raise ValueError(f"Invalid color pair '{spec}': expected 'HEX1,HEX2'.")
|
|
111
|
+
return hex_to_rgb(parts[0]), hex_to_rgb(parts[1])
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _validate_color_pairs(colors: list[tuple[list[int], list[int]]]) -> None:
|
|
115
|
+
"""
|
|
116
|
+
Validate explicit color pairs and reject duplicates.
|
|
117
|
+
|
|
118
|
+
Raises ValueError if any color is not three integers in [0, 255], or if
|
|
119
|
+
two pairs are identical: identical pairs map to identical filenames, so
|
|
120
|
+
the second variation would silently overwrite the first.
|
|
121
|
+
"""
|
|
122
|
+
seen = set()
|
|
123
|
+
for pair in colors:
|
|
124
|
+
try:
|
|
125
|
+
pair_len = len(pair)
|
|
126
|
+
except TypeError as exc:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
f"Invalid color pair {pair!r}: expected a pair of two RGB colors."
|
|
129
|
+
) from exc
|
|
130
|
+
if pair_len != 2:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"Invalid color pair {pair!r}: expected exactly two RGB colors."
|
|
133
|
+
)
|
|
134
|
+
color1, color2 = pair
|
|
135
|
+
for color in (color1, color2):
|
|
136
|
+
try:
|
|
137
|
+
color_len = len(color)
|
|
138
|
+
except TypeError as exc:
|
|
139
|
+
raise ValueError(
|
|
140
|
+
f"Invalid RGB color {color!r}: expected three integers in [0, 255]."
|
|
141
|
+
) from exc
|
|
142
|
+
if color_len != 3 or not all(
|
|
143
|
+
isinstance(v, (int, np.integer)) and 0 <= v <= 255 for v in color
|
|
144
|
+
):
|
|
145
|
+
raise ValueError(
|
|
146
|
+
f"Invalid RGB color {color}: expected three integers "
|
|
147
|
+
"in [0, 255]."
|
|
148
|
+
)
|
|
149
|
+
hex_pair = rgb_to_hex(color1), rgb_to_hex(color2)
|
|
150
|
+
if hex_pair in seen:
|
|
151
|
+
raise ValueError(
|
|
152
|
+
f"Duplicate color pair {hex_pair[0]},{hex_pair[1]}: "
|
|
153
|
+
"each pair may appear only once."
|
|
154
|
+
)
|
|
155
|
+
seen.add(hex_pair)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _srgb_to_linear(rgb: np.ndarray) -> np.ndarray:
|
|
159
|
+
"""
|
|
160
|
+
Linearize gamma-encoded sRGB code values in [0, 1].
|
|
161
|
+
|
|
162
|
+
Applies the inverse EOTF of IEC 61966-2-1; see Poynton (2003),
|
|
163
|
+
"Digital Video and HDTV". Returns an array of the same shape.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
rgb: sRGB code values in [0, 1], any shape.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
Linear-light values with the input's shape, float32.
|
|
170
|
+
"""
|
|
171
|
+
x = np.asarray(rgb, dtype=np.float32)
|
|
172
|
+
return np.where(x <= 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _linear_to_srgb(linear: np.ndarray) -> np.ndarray:
|
|
176
|
+
"""
|
|
177
|
+
Encode linear-light values as sRGB code values in [0, 1].
|
|
178
|
+
|
|
179
|
+
Applies the forward EOTF of IEC 61966-2-1; see Poynton (2003).
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
linear: Linear-light values, treated as zero below zero.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
sRGB code values with the input's shape, float32.
|
|
186
|
+
"""
|
|
187
|
+
v = np.maximum(np.asarray(linear, dtype=np.float32), 0.0)
|
|
188
|
+
return np.where(v <= 0.0031308, 12.92 * v, 1.055 * v ** (1 / 2.4) - 0.055)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _rgb_to_oklab(rgb: np.ndarray) -> np.ndarray:
|
|
192
|
+
"""
|
|
193
|
+
Convert gamma-encoded sRGB in [0, 1] to Oklab (Ottosson, 2020).
|
|
194
|
+
|
|
195
|
+
Oklab is a perceptually uniform space; interpolating in it avoids the
|
|
196
|
+
midpoint desaturation and hue drift of gamma-space blending.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
rgb: sRGB code values in [0, 1], shape (..., 3).
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
Oklab values (L, a, b) with the input's shape, float32.
|
|
203
|
+
"""
|
|
204
|
+
linear = _srgb_to_linear(rgb)
|
|
205
|
+
r, g, b = linear[..., 0], linear[..., 1], linear[..., 2]
|
|
206
|
+
lms_l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
|
|
207
|
+
lms_m = 0.2119034980 * r + 0.6806995451 * g + 0.1073969566 * b
|
|
208
|
+
lms_s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
|
|
209
|
+
lms_l, lms_m, lms_s = np.cbrt(lms_l), np.cbrt(lms_m), np.cbrt(lms_s)
|
|
210
|
+
return np.stack((
|
|
211
|
+
0.2104542553 * lms_l + 0.7936177850 * lms_m - 0.0040720468 * lms_s,
|
|
212
|
+
1.9779984951 * lms_l - 2.4285922050 * lms_m + 0.4505937099 * lms_s,
|
|
213
|
+
0.0259040371 * lms_l + 0.7827717662 * lms_m - 0.8086757660 * lms_s,
|
|
214
|
+
), axis=-1).astype(np.float32)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _oklab_to_rgb(lab: np.ndarray) -> np.ndarray:
|
|
218
|
+
"""
|
|
219
|
+
Convert Oklab (Ottosson, 2020) to gamma-encoded sRGB in [0, 1].
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
lab: Oklab values (L, a, b), shape (..., 3).
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
sRGB code values with the input's shape, float32. Values outside
|
|
226
|
+
the sRGB gamut are negative or above 1; callers must clip.
|
|
227
|
+
"""
|
|
228
|
+
L, a, b = lab[..., 0], lab[..., 1], lab[..., 2]
|
|
229
|
+
l_ = L + 0.3963377774 * a + 0.2158037573 * b
|
|
230
|
+
m_ = L - 0.1055613458 * a - 0.0638541728 * b
|
|
231
|
+
s_ = L - 0.0894841775 * a - 1.2914855480 * b
|
|
232
|
+
lms_l, lms_m, lms_s = l_ ** 3, m_ ** 3, s_ ** 3
|
|
233
|
+
rgb_linear = np.stack((
|
|
234
|
+
4.0767416621 * lms_l - 3.3077115913 * lms_m + 0.2309699292 * lms_s,
|
|
235
|
+
-1.2684380036 * lms_l + 2.6097574011 * lms_m - 0.3413193965 * lms_s,
|
|
236
|
+
-0.0041960863 * lms_l - 0.7034186147 * lms_m + 1.7076147010 * lms_s,
|
|
237
|
+
), axis=-1)
|
|
238
|
+
return _linear_to_srgb(rgb_linear).astype(np.float32)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _duotone_rgb(
|
|
242
|
+
key: np.ndarray,
|
|
243
|
+
color1: list[int],
|
|
244
|
+
color2: list[int],
|
|
245
|
+
space: str,
|
|
246
|
+
) -> np.ndarray:
|
|
247
|
+
"""
|
|
248
|
+
Blend color1 -> color2 over key, returning RGB in [0, 1].
|
|
249
|
+
|
|
250
|
+
'srgb' interpolates gamma-encoded values (legacy behavior);
|
|
251
|
+
'linear' interpolates linear light (IEC 61966-2-1; Poynton, 2003);
|
|
252
|
+
'oklab' interpolates in Oklab (Ottosson, 2020) per channel and converts
|
|
253
|
+
back to sRGB.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
key: Blend weight as a float array normalized to [0, 1].
|
|
257
|
+
color1: RGB color mapped to key 0, three integers in [0, 255].
|
|
258
|
+
color2: RGB color mapped to key 1, three integers in [0, 255].
|
|
259
|
+
space: One of SPACES.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
RGB image with the key's height and width in [0, 1], except for
|
|
263
|
+
minor range drift from numeric error. The srgb path retains the
|
|
264
|
+
key dtype for legacy rounding; newer spaces use float32. Callers
|
|
265
|
+
clip.
|
|
266
|
+
"""
|
|
267
|
+
c1 = np.array(color1, dtype=np.float32).reshape(1, 1, 3) / 255
|
|
268
|
+
c2 = np.array(color2, dtype=np.float32).reshape(1, 1, 3) / 255
|
|
269
|
+
w = np.asarray(key)[:, :, np.newaxis]
|
|
270
|
+
if space == "srgb":
|
|
271
|
+
return (1 - w) * c1 + w * c2
|
|
272
|
+
w = w.astype(np.float32, copy=False)
|
|
273
|
+
if space == "linear":
|
|
274
|
+
return _linear_to_srgb(
|
|
275
|
+
(1 - w) * _srgb_to_linear(c1) + w * _srgb_to_linear(c2)
|
|
276
|
+
)
|
|
277
|
+
o1, o2 = _rgb_to_oklab(c1), _rgb_to_oklab(c2)
|
|
278
|
+
return np.clip(_oklab_to_rgb((1 - w) * o1 + w * o2), 0.0, 1.0)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _rgb_to_lab(rgb: np.ndarray) -> np.ndarray:
|
|
282
|
+
"""
|
|
283
|
+
Convert gamma-encoded sRGB in [0, 1] to CIE L*a*b* under D65.
|
|
284
|
+
|
|
285
|
+
Uses the fixed sRGB-to-XYZ matrix and white point assumed by IEC
|
|
286
|
+
61966-2-1. Used only as input to the CIEDE2000 metric.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
rgb: sRGB code values in [0, 1], shape (..., 3).
|
|
290
|
+
|
|
291
|
+
Returns:
|
|
292
|
+
L*a*b* values with the input's shape, float32. L is in [0, 100];
|
|
293
|
+
a and b are unbounded.
|
|
294
|
+
"""
|
|
295
|
+
xyz = _srgb_to_linear(rgb) @ _SRGB_TO_XYZ.T
|
|
296
|
+
ratio = xyz / _D65_WHITE
|
|
297
|
+
delta = 6 / 29
|
|
298
|
+
t = np.where(ratio > delta ** 3, np.cbrt(ratio),
|
|
299
|
+
ratio / (3 * delta ** 2) + 4 / 29)
|
|
300
|
+
L = 116 * t[..., 1] - 16
|
|
301
|
+
a = 500 * (t[..., 0] - t[..., 1])
|
|
302
|
+
b = 200 * (t[..., 1] - t[..., 2])
|
|
303
|
+
return np.stack((L, a, b), axis=-1).astype(np.float32)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _ciede2000(lab1: np.ndarray, lab2: np.ndarray) -> np.ndarray:
|
|
307
|
+
"""
|
|
308
|
+
CIEDE2000 color difference between two arrays of L*a*b* values.
|
|
309
|
+
|
|
310
|
+
Implements the reference formula with the corrections published by
|
|
311
|
+
Sharma, Wu & Dalal (2005), "The CIEDE2000 Color-Difference Formula:
|
|
312
|
+
Implementation Notes, Supplementary Test Data, and Observations".
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
lab1, lab2: L*a*b* arrays of the same shape (..., 3).
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
ΔE00 values with the inputs' leading shape, float32.
|
|
319
|
+
"""
|
|
320
|
+
L1, a1, b1 = lab1[..., 0], lab1[..., 1], lab1[..., 2]
|
|
321
|
+
L2, a2, b2 = lab2[..., 0], lab2[..., 1], lab2[..., 2]
|
|
322
|
+
|
|
323
|
+
C1 = np.hypot(a1, b1)
|
|
324
|
+
C2 = np.hypot(a2, b2)
|
|
325
|
+
C_bar = (C1 + C2) / 2
|
|
326
|
+
G = 0.5 * (1 - np.sqrt(C_bar ** 7 / (C_bar ** 7 + 25 ** 7)))
|
|
327
|
+
a1p, a2p = (1 + G) * a1, (1 + G) * a2
|
|
328
|
+
C1p = np.hypot(a1p, b1)
|
|
329
|
+
C2p = np.hypot(a2p, b2)
|
|
330
|
+
h1p = np.degrees(np.arctan2(b1, a1p)) % 360
|
|
331
|
+
h2p = np.degrees(np.arctan2(b2, a2p)) % 360
|
|
332
|
+
|
|
333
|
+
dLp = L2 - L1
|
|
334
|
+
dCp = C2p - C1p
|
|
335
|
+
# Hue difference folded into (-180, 180] so averaging is continuous.
|
|
336
|
+
dh = h2p - h1p
|
|
337
|
+
dh = np.where(dh > 180, dh - 360, dh)
|
|
338
|
+
dh = np.where(dh < -180, dh + 360, dh)
|
|
339
|
+
dHp = 2 * np.sqrt(C1p * C2p) * np.sin(np.radians(dh) / 2)
|
|
340
|
+
|
|
341
|
+
# Mean hue h_bar; the case branches follow Sharma, Wu & Dalal (2005).
|
|
342
|
+
h_diff = np.abs(h1p - h2p)
|
|
343
|
+
h_sum = h1p + h2p
|
|
344
|
+
h_bar = np.where(
|
|
345
|
+
C1p * C2p == 0,
|
|
346
|
+
h_sum,
|
|
347
|
+
np.where(h_diff <= 180, h_sum / 2,
|
|
348
|
+
np.where(h_sum < 360, (h_sum + 360) / 2, (h_sum - 360) / 2)),
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
T = (1
|
|
352
|
+
- 0.17 * np.cos(np.radians(h_bar - 30))
|
|
353
|
+
+ 0.24 * np.cos(np.radians(2 * h_bar))
|
|
354
|
+
+ 0.32 * np.cos(np.radians(3 * h_bar + 6))
|
|
355
|
+
- 0.20 * np.cos(np.radians(4 * h_bar - 63)))
|
|
356
|
+
L_bar = (L1 + L2) / 2
|
|
357
|
+
S_L = 1 + (0.015 * (L_bar - 50) ** 2) / np.sqrt(20 + (L_bar - 50) ** 2)
|
|
358
|
+
C_barp = (C1p + C2p) / 2
|
|
359
|
+
S_C = 1 + 0.045 * C_barp
|
|
360
|
+
S_H = 1 + 0.015 * C_barp * T
|
|
361
|
+
d_theta = 30 * np.exp(-(((h_bar - 275) / 25) ** 2))
|
|
362
|
+
R_C = 2 * np.sqrt(C_barp ** 7 / (C_barp ** 7 + 25 ** 7))
|
|
363
|
+
R_T = -R_C * np.sin(np.radians(2 * d_theta))
|
|
364
|
+
|
|
365
|
+
dE = ((dLp / S_L) ** 2
|
|
366
|
+
+ (dCp / S_C) ** 2
|
|
367
|
+
+ (dHp / S_H) ** 2
|
|
368
|
+
+ R_T * (dCp / S_C) * (dHp / S_H))
|
|
369
|
+
return np.sqrt(np.maximum(dE, 0.0))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _duotone_delta_e00_tile(
|
|
373
|
+
key: np.ndarray,
|
|
374
|
+
output_bgr: np.ndarray,
|
|
375
|
+
color1: list[int],
|
|
376
|
+
color2: list[int],
|
|
377
|
+
) -> np.ndarray:
|
|
378
|
+
"""Return CIEDE2000 differences for one bounded row tile."""
|
|
379
|
+
output_rgb = output_bgr[:, :, ::-1].astype(np.float32) / 255
|
|
380
|
+
reference_rgb = _duotone_rgb(key, color1, color2, "oklab")
|
|
381
|
+
return _ciede2000(_rgb_to_lab(output_rgb), _rgb_to_lab(reference_rgb))
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def create_duotone_image(
|
|
385
|
+
gray: np.ndarray,
|
|
386
|
+
color1: list[int],
|
|
387
|
+
color2: list[int],
|
|
388
|
+
space: str = "srgb",
|
|
389
|
+
) -> np.ndarray:
|
|
390
|
+
"""
|
|
391
|
+
Create a duotone image from a blend key and two colors.
|
|
392
|
+
|
|
393
|
+
Args:
|
|
394
|
+
gray: Blend key as a float array normalized to [0, 1], with the
|
|
395
|
+
output's height and width. Values come from convert_to_duotone:
|
|
396
|
+
grayscale BT.601 luma for 'srgb' (legacy), or relative
|
|
397
|
+
luminance for 'linear' and 'oklab'.
|
|
398
|
+
color1: First RGB color, three integers in [0, 255]. Maps to key 0.
|
|
399
|
+
color2: Second RGB color, three integers in [0, 255]. Maps to key 1.
|
|
400
|
+
space: Where the interpolation runs: 'srgb' (default) blends
|
|
401
|
+
gamma-encoded sRGB exactly as the pre-Duotonics implementation
|
|
402
|
+
did; 'linear' blends linear light (IEC 61966-2-1; Poynton, 2003);
|
|
403
|
+
'oklab' blends in Oklab (Ottosson, 2020).
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
The duotone image as a uint8 array in OpenCV's BGR channel order,
|
|
407
|
+
ready for cv2.imwrite.
|
|
408
|
+
|
|
409
|
+
Raises:
|
|
410
|
+
ValueError: If space is not one of 'srgb', 'linear', 'oklab'.
|
|
411
|
+
"""
|
|
412
|
+
if space not in SPACES:
|
|
413
|
+
raise ValueError(f"space must be one of {', '.join(SPACES)}, got '{space}'.")
|
|
414
|
+
duotone = np.clip(_duotone_rgb(gray, color1, color2, space), 0.0, 1.0)
|
|
415
|
+
duotone_rgb = np.clip(np.rint(duotone * 255), 0, 255).astype(np.uint8)
|
|
416
|
+
return cv2.cvtColor(duotone_rgb, cv2.COLOR_RGB2BGR)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
_SOF_MARKERS = frozenset({
|
|
420
|
+
0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
|
|
421
|
+
0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
|
|
422
|
+
})
|
|
423
|
+
def _read_image_dimensions(image_path: str, ext: str) -> tuple[int, int]:
|
|
424
|
+
"""
|
|
425
|
+
Return (width, height) by reading only the file header.
|
|
426
|
+
|
|
427
|
+
Reads fixed-size PNG and BMP headers and scans JPEG marker headers
|
|
428
|
+
incrementally. Raises ValueError on truncated or unrecognised headers.
|
|
429
|
+
"""
|
|
430
|
+
try:
|
|
431
|
+
with open(image_path, "rb") as fh:
|
|
432
|
+
if ext == ".png":
|
|
433
|
+
hdr = fh.read(24)
|
|
434
|
+
if len(hdr) < 24 or hdr[:8] != b"\x89PNG\r\n\x1a\n":
|
|
435
|
+
raise ValueError(f"'{image_path}' is not a valid PNG file.")
|
|
436
|
+
width, height = struct.unpack(">II", hdr[16:24])
|
|
437
|
+
return width, height
|
|
438
|
+
|
|
439
|
+
if ext in (".jpg", ".jpeg"):
|
|
440
|
+
if fh.read(2) != b"\xff\xd8":
|
|
441
|
+
raise ValueError(f"'{image_path}' is not a valid JPEG file.")
|
|
442
|
+
while True:
|
|
443
|
+
prefix = fh.read(1)
|
|
444
|
+
if not prefix:
|
|
445
|
+
raise ValueError(
|
|
446
|
+
f"Truncated JPEG header in '{image_path}'."
|
|
447
|
+
)
|
|
448
|
+
if prefix != b"\xff":
|
|
449
|
+
raise ValueError(
|
|
450
|
+
f"Failed to read JPEG dimensions from '{image_path}'."
|
|
451
|
+
)
|
|
452
|
+
while prefix == b"\xff":
|
|
453
|
+
prefix = fh.read(1)
|
|
454
|
+
if not prefix:
|
|
455
|
+
raise ValueError(
|
|
456
|
+
f"Truncated JPEG header in '{image_path}'."
|
|
457
|
+
)
|
|
458
|
+
marker = prefix[0]
|
|
459
|
+
if marker in _SOF_MARKERS:
|
|
460
|
+
header = fh.read(7)
|
|
461
|
+
if len(header) < 7:
|
|
462
|
+
raise ValueError(
|
|
463
|
+
f"Truncated JPEG header in '{image_path}'."
|
|
464
|
+
)
|
|
465
|
+
return struct.unpack(">HH", header[3:7])
|
|
466
|
+
if marker in (0xD9, 0xDA):
|
|
467
|
+
raise ValueError(
|
|
468
|
+
f"Failed to read JPEG dimensions from '{image_path}'."
|
|
469
|
+
)
|
|
470
|
+
if 0xD0 <= marker <= 0xD7 or marker == 0x01:
|
|
471
|
+
continue
|
|
472
|
+
length_bytes = fh.read(2)
|
|
473
|
+
if len(length_bytes) < 2:
|
|
474
|
+
raise ValueError(
|
|
475
|
+
f"Truncated JPEG header in '{image_path}'."
|
|
476
|
+
)
|
|
477
|
+
segment_length = struct.unpack(">H", length_bytes)[0]
|
|
478
|
+
if segment_length < 2:
|
|
479
|
+
raise ValueError(
|
|
480
|
+
f"Invalid JPEG segment length in '{image_path}'."
|
|
481
|
+
)
|
|
482
|
+
fh.seek(segment_length - 2, 1)
|
|
483
|
+
|
|
484
|
+
if ext == ".bmp":
|
|
485
|
+
hdr = fh.read(26)
|
|
486
|
+
if len(hdr) < 26 or hdr[:2] != b"BM":
|
|
487
|
+
raise ValueError(f"'{image_path}' is not a valid BMP file.")
|
|
488
|
+
dib_size = struct.unpack("<I", hdr[14:18])[0]
|
|
489
|
+
if dib_size == 12:
|
|
490
|
+
return struct.unpack("<HH", hdr[18:22])
|
|
491
|
+
if dib_size >= 40:
|
|
492
|
+
width = abs(struct.unpack("<i", hdr[18:22])[0])
|
|
493
|
+
height = abs(struct.unpack("<i", hdr[22:26])[0])
|
|
494
|
+
return width, height
|
|
495
|
+
raise ValueError(
|
|
496
|
+
f"Unsupported DIB header size {dib_size} in '{image_path}'."
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
except OSError as exc:
|
|
500
|
+
raise ValueError(f"Failed to load image '{image_path}': {exc}") from exc
|
|
501
|
+
except struct.error as exc:
|
|
502
|
+
raise ValueError(
|
|
503
|
+
f"Failed to read image dimensions from '{image_path}': {exc}"
|
|
504
|
+
) from exc
|
|
505
|
+
|
|
506
|
+
raise ValueError(f"Unsupported extension '{ext}'.") # unreachable for validated ext
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _load_image(image_path: str) -> np.ndarray:
|
|
510
|
+
"""
|
|
511
|
+
Load an image as a BGR uint8 array.
|
|
512
|
+
|
|
513
|
+
Raises ValueError for unsupported extensions, empty files, images whose
|
|
514
|
+
total pixel count exceeds MAX_IMAGE_DIMENSION ** 2 (checked from the file
|
|
515
|
+
header before any decode), and undecodable content.
|
|
516
|
+
"""
|
|
517
|
+
ext = os.path.splitext(image_path)[1].lower()
|
|
518
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
519
|
+
raise ValueError(
|
|
520
|
+
f"Unsupported image format '{ext or '(none)'}' for "
|
|
521
|
+
f"'{image_path}'. Supported formats: JPEG, PNG, BMP."
|
|
522
|
+
)
|
|
523
|
+
if os.path.isfile(image_path) and os.path.getsize(image_path) == 0:
|
|
524
|
+
raise ValueError(
|
|
525
|
+
f"Failed to load image '{image_path}': the file is empty (0 bytes)."
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
width, height = _read_image_dimensions(image_path, ext)
|
|
529
|
+
if width * height > MAX_IMAGE_DIMENSION ** 2:
|
|
530
|
+
raise ValueError(
|
|
531
|
+
f"Image '{image_path}' is {width}x{height} pixels, exceeding the "
|
|
532
|
+
f"maximum supported dimension of {MAX_IMAGE_DIMENSION} pixels."
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
image = cv2.imread(image_path)
|
|
536
|
+
if image is None:
|
|
537
|
+
raise ValueError(f"Failed to load image '{image_path}'.")
|
|
538
|
+
return image
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _duotone_key(image: np.ndarray, space: str) -> np.ndarray:
|
|
542
|
+
"""
|
|
543
|
+
Return the blend key in [0, 1] used by the given space.
|
|
544
|
+
|
|
545
|
+
'srgb' keeps the legacy key, ITU-R BT.601 luma weights applied to
|
|
546
|
+
gamma-encoded code values, so seeded batches remain byte-identical to
|
|
547
|
+
the pre-Duotonics implementation. 'linear' and 'oklab' use relative
|
|
548
|
+
luminance instead: ITU-R BT.709 weights applied to linearized RGB
|
|
549
|
+
(IEC 61966-2-1; Poynton, 2003).
|
|
550
|
+
|
|
551
|
+
Args:
|
|
552
|
+
image: BGR uint8 image.
|
|
553
|
+
space: One of SPACES.
|
|
554
|
+
|
|
555
|
+
Returns:
|
|
556
|
+
Float32 key array normalized to [0, 1], same height and width as
|
|
557
|
+
the input.
|
|
558
|
+
"""
|
|
559
|
+
if space == "srgb":
|
|
560
|
+
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(np.float32) / 255
|
|
561
|
+
rgb = image[:, :, ::-1].astype(np.float32) / 255
|
|
562
|
+
linear = _srgb_to_linear(rgb)
|
|
563
|
+
return (0.2126 * linear[..., 0]
|
|
564
|
+
+ 0.7152 * linear[..., 1]
|
|
565
|
+
+ 0.0722 * linear[..., 2])
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _open_regular_file(path: str) -> int:
|
|
569
|
+
"""Open a regular file without blocking or following symlinks."""
|
|
570
|
+
flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
571
|
+
try:
|
|
572
|
+
descriptor = os.open(path, flags)
|
|
573
|
+
except OSError as exc:
|
|
574
|
+
raise ValueError(f"Unable to open '{path}' safely: {exc}") from exc
|
|
575
|
+
try:
|
|
576
|
+
regular = stat.S_ISREG(os.fstat(descriptor).st_mode)
|
|
577
|
+
except OSError:
|
|
578
|
+
os.close(descriptor)
|
|
579
|
+
raise
|
|
580
|
+
if not regular:
|
|
581
|
+
os.close(descriptor)
|
|
582
|
+
raise ValueError(f"Unsupported special file in output folder: '{path}'.")
|
|
583
|
+
return descriptor
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _read_previous_manifest(output_folder: str) -> set[str]:
|
|
587
|
+
"""Return filenames owned by the previous batch manifest."""
|
|
588
|
+
manifest_path = os.path.join(output_folder, "colors.csv")
|
|
589
|
+
if not os.path.exists(manifest_path):
|
|
590
|
+
return set()
|
|
591
|
+
owned = {"colors.csv", "metrics.csv"}
|
|
592
|
+
with os.fdopen(_open_regular_file(manifest_path), "r", newline="") as stream:
|
|
593
|
+
reader = csv.DictReader(stream)
|
|
594
|
+
if reader.fieldnames != ["variation", "color_1_hex", "color_2_hex"]:
|
|
595
|
+
raise ValueError(f"Invalid batch manifest '{manifest_path}'.")
|
|
596
|
+
for row in reader:
|
|
597
|
+
try:
|
|
598
|
+
index = int(row["variation"])
|
|
599
|
+
except (TypeError, ValueError):
|
|
600
|
+
raise ValueError(f"Invalid batch manifest '{manifest_path}'.") from None
|
|
601
|
+
if index < 0:
|
|
602
|
+
raise ValueError(f"Invalid batch manifest '{manifest_path}'.")
|
|
603
|
+
color1 = row["color_1_hex"].upper().removeprefix("#")
|
|
604
|
+
color2 = row["color_2_hex"].upper().removeprefix("#")
|
|
605
|
+
if any(
|
|
606
|
+
re.fullmatch(r"[0-9A-F]{6}", color) is None
|
|
607
|
+
for color in (color1, color2)
|
|
608
|
+
):
|
|
609
|
+
raise ValueError(f"Invalid batch manifest '{manifest_path}'.")
|
|
610
|
+
owned.add(f"{index:03d}_{color1}_{color2}.png")
|
|
611
|
+
return owned
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _file_digest(path: str) -> str:
|
|
615
|
+
"""Hash one file's contents to detect same-size, same-mtime edits."""
|
|
616
|
+
digest = hashlib.sha256()
|
|
617
|
+
with os.fdopen(_open_regular_file(path), "rb") as stream:
|
|
618
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
619
|
+
digest.update(chunk)
|
|
620
|
+
return digest.hexdigest()
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _unrelated_snapshot(
|
|
624
|
+
output_folder: str, excluded: set[str]
|
|
625
|
+
) -> dict[str, tuple[str, int, str]]:
|
|
626
|
+
"""Capture unrelated file metadata to detect live-folder changes."""
|
|
627
|
+
snapshot: dict[str, tuple[str, int, str]] = {}
|
|
628
|
+
if not os.path.isdir(output_folder):
|
|
629
|
+
return snapshot
|
|
630
|
+
for directory, directories, filenames in os.walk(output_folder):
|
|
631
|
+
for name in directories + filenames:
|
|
632
|
+
path = os.path.join(directory, name)
|
|
633
|
+
relative = os.path.relpath(path, output_folder)
|
|
634
|
+
if relative in excluded:
|
|
635
|
+
continue
|
|
636
|
+
if os.path.islink(path):
|
|
637
|
+
snapshot[relative] = ("link", 0, os.readlink(path))
|
|
638
|
+
elif os.path.isdir(path):
|
|
639
|
+
snapshot[relative] = (
|
|
640
|
+
"directory", os.lstat(path).st_mtime_ns, ""
|
|
641
|
+
)
|
|
642
|
+
else:
|
|
643
|
+
snapshot[relative] = ("file", 0, _file_digest(path))
|
|
644
|
+
return snapshot
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _assert_no_unowned_conflicts(
|
|
648
|
+
output_folder: str, planned_files: set[str], previous_owned: set[str]
|
|
649
|
+
) -> None:
|
|
650
|
+
"""Reject planned output names that would overwrite unowned files."""
|
|
651
|
+
if not os.path.isdir(output_folder):
|
|
652
|
+
return
|
|
653
|
+
for name in planned_files - previous_owned:
|
|
654
|
+
path = os.path.join(output_folder, name)
|
|
655
|
+
if os.path.exists(path):
|
|
656
|
+
raise ValueError(
|
|
657
|
+
f"Planned output '{path}' conflicts with an unowned file."
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
@contextlib.contextmanager
|
|
662
|
+
def _batch_output_folder(
|
|
663
|
+
output_folder: str, base: str, stem: str, planned_files: set[str]
|
|
664
|
+
) -> Iterator[str]:
|
|
665
|
+
"""Stage a complete batch and publish it with a directory swap."""
|
|
666
|
+
os.makedirs(base or ".", exist_ok=True)
|
|
667
|
+
workdir = tempfile.mkdtemp(prefix=f".{stem}_duotone_", dir=base or ".")
|
|
668
|
+
preserve_workdir = False
|
|
669
|
+
published = False
|
|
670
|
+
try:
|
|
671
|
+
previous_owned = (
|
|
672
|
+
_read_previous_manifest(output_folder)
|
|
673
|
+
if os.path.isdir(output_folder)
|
|
674
|
+
else set()
|
|
675
|
+
)
|
|
676
|
+
_assert_no_unowned_conflicts(output_folder, planned_files, previous_owned)
|
|
677
|
+
excluded = previous_owned | planned_files
|
|
678
|
+
snapshot = _unrelated_snapshot(output_folder, excluded)
|
|
679
|
+
next_folder = os.path.join(workdir, "next")
|
|
680
|
+
if os.path.exists(output_folder):
|
|
681
|
+
if not os.path.isdir(output_folder):
|
|
682
|
+
raise NotADirectoryError(
|
|
683
|
+
f"Output path '{output_folder}' is not a directory."
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
def ignore_previous_batch(directory: str, names: list[str]) -> set[str]:
|
|
687
|
+
if os.path.abspath(directory) != os.path.abspath(output_folder):
|
|
688
|
+
return set()
|
|
689
|
+
return {name for name in names if name in previous_owned}
|
|
690
|
+
|
|
691
|
+
shutil.copytree(
|
|
692
|
+
output_folder,
|
|
693
|
+
next_folder,
|
|
694
|
+
symlinks=True,
|
|
695
|
+
ignore=ignore_previous_batch,
|
|
696
|
+
)
|
|
697
|
+
else:
|
|
698
|
+
os.makedirs(next_folder)
|
|
699
|
+
|
|
700
|
+
yield next_folder
|
|
701
|
+
|
|
702
|
+
_assert_no_unowned_conflicts(output_folder, planned_files, previous_owned)
|
|
703
|
+
if _unrelated_snapshot(output_folder, excluded) != snapshot:
|
|
704
|
+
raise RuntimeError(
|
|
705
|
+
"Output folder changed during generation; previous output was "
|
|
706
|
+
"left unchanged."
|
|
707
|
+
)
|
|
708
|
+
|
|
709
|
+
previous_folder = os.path.join(workdir, "previous")
|
|
710
|
+
try:
|
|
711
|
+
if os.path.exists(output_folder):
|
|
712
|
+
os.replace(output_folder, previous_folder)
|
|
713
|
+
os.replace(next_folder, output_folder)
|
|
714
|
+
published = True
|
|
715
|
+
except (OSError, KeyboardInterrupt):
|
|
716
|
+
if os.path.exists(previous_folder) and not os.path.exists(output_folder):
|
|
717
|
+
try:
|
|
718
|
+
os.replace(previous_folder, output_folder)
|
|
719
|
+
except OSError as rollback_error:
|
|
720
|
+
preserve_workdir = True
|
|
721
|
+
raise OSError(
|
|
722
|
+
f"Failed to publish '{output_folder}'; the previous batch "
|
|
723
|
+
f"is retained at '{previous_folder}'."
|
|
724
|
+
) from rollback_error
|
|
725
|
+
raise
|
|
726
|
+
finally:
|
|
727
|
+
if not preserve_workdir:
|
|
728
|
+
if published:
|
|
729
|
+
try:
|
|
730
|
+
shutil.rmtree(workdir)
|
|
731
|
+
except OSError as cleanup_error:
|
|
732
|
+
warnings.warn(
|
|
733
|
+
f"Batch published at '{output_folder}', but temporary files "
|
|
734
|
+
f"remain at '{workdir}': {cleanup_error}",
|
|
735
|
+
RuntimeWarning,
|
|
736
|
+
stacklevel=2,
|
|
737
|
+
)
|
|
738
|
+
else:
|
|
739
|
+
shutil.rmtree(workdir)
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def convert_to_duotone(
|
|
743
|
+
image_path: str,
|
|
744
|
+
output_dir: str | None = None,
|
|
745
|
+
count: int = DEFAULT_VARIATION_COUNT,
|
|
746
|
+
seed: int | None = None,
|
|
747
|
+
colors: list[tuple[list[int], list[int]]] | None = None,
|
|
748
|
+
space: str = "srgb",
|
|
749
|
+
) -> tuple[str, list[list[int | str]]]:
|
|
750
|
+
"""
|
|
751
|
+
Convert an image to duotone variations and save them to disk.
|
|
752
|
+
|
|
753
|
+
For each variation a color pair is blended over the source's tonal key
|
|
754
|
+
and written as a lossless PNG. Filenames encode both hex color values
|
|
755
|
+
(e.g. '083_2CD2B4_DC1E5A.png'). A 'colors.csv' sidecar lists every
|
|
756
|
+
variation's color pair, and a 'metrics.csv' sidecar reports the mean,
|
|
757
|
+
median, and 95th-percentile CIEDE2000 (Sharma, Wu & Dalal, 2005)
|
|
758
|
+
between each output and its perceptual reference: the same color pair
|
|
759
|
+
blended in Oklab (Ottosson, 2020) over the same key.
|
|
760
|
+
|
|
761
|
+
Args:
|
|
762
|
+
image_path: Absolute or relative path to the source image.
|
|
763
|
+
Supported formats: JPEG, PNG, BMP. Loading uses cv2.imread
|
|
764
|
+
with IMREAD_COLOR, so 16-bit images are downconverted to
|
|
765
|
+
8-bit and alpha channels are dropped.
|
|
766
|
+
output_dir: Directory under which the
|
|
767
|
+
'<image_stem>_duotone_variations' folder is created. When None
|
|
768
|
+
(default) the folder is placed alongside the source image.
|
|
769
|
+
count: Number of random variations to generate
|
|
770
|
+
(default: DEFAULT_VARIATION_COUNT). Ignored when `colors` is given.
|
|
771
|
+
seed: Seed for random color generation. Pass an integer to reproduce
|
|
772
|
+
a batch exactly; None (default) produces a different batch
|
|
773
|
+
every run.
|
|
774
|
+
colors: Explicit color pairs as (color1, color2) RGB lists, one
|
|
775
|
+
variation per pair. When given, `count` and `seed` are unused.
|
|
776
|
+
space: Where the blend runs: 'srgb' (default) interpolates
|
|
777
|
+
gamma-encoded sRGB over the legacy grayscale key, byte-identical
|
|
778
|
+
to the pre-Duotonics implementation; 'linear' and 'oklab'
|
|
779
|
+
interpolate in linear sRGB (IEC 61966-2-1; Poynton, 2003) and
|
|
780
|
+
Oklab (Ottosson, 2020) over an ITU-R BT.709 relative-luminance
|
|
781
|
+
key.
|
|
782
|
+
|
|
783
|
+
Returns:
|
|
784
|
+
A tuple ``(output_folder, color_records)``: the path of the created
|
|
785
|
+
'<image_stem>_duotone_variations' folder and a list of
|
|
786
|
+
``[index, color_1_hex, color_2_hex]`` rows, one per variation.
|
|
787
|
+
|
|
788
|
+
Raises:
|
|
789
|
+
ValueError: If `image_path` has an unsupported extension (supported
|
|
790
|
+
formats: JPEG, PNG, BMP), the file is empty (0 bytes), the image
|
|
791
|
+
cannot be decoded, or its total pixel count exceeds
|
|
792
|
+
MAX_IMAGE_DIMENSION ** 2 (checked from the file header before
|
|
793
|
+
decoding). Also if `count` is below 1, `colors` is an empty list,
|
|
794
|
+
an explicit color is not three integers in [0, 255], two color
|
|
795
|
+
pairs are identical, or `space` is not one of 'srgb', 'linear',
|
|
796
|
+
'oklab'.
|
|
797
|
+
OSError: If a variation file cannot be written to disk.
|
|
798
|
+
|
|
799
|
+
Side effects:
|
|
800
|
+
Creates '<output_dir>/<image_stem>_duotone_variations/' (or a sibling
|
|
801
|
+
folder when output_dir is None) containing one PNG per variation,
|
|
802
|
+
one 'colors.csv' file, and one 'metrics.csv' file. The batch is written
|
|
803
|
+
to a temporary sibling directory before publication. Existing generated
|
|
804
|
+
files listed in the previous batch manifest are replaced, and unrelated
|
|
805
|
+
files are preserved. If generation fails or unrelated files change during
|
|
806
|
+
generation, the previous output remains unchanged.
|
|
807
|
+
"""
|
|
808
|
+
if space not in SPACES:
|
|
809
|
+
raise ValueError(f"space must be one of {', '.join(SPACES)}, got '{space}'.")
|
|
810
|
+
if colors is None:
|
|
811
|
+
if count < 1:
|
|
812
|
+
raise ValueError(f"count must be at least 1, got {count}.")
|
|
813
|
+
elif not colors:
|
|
814
|
+
raise ValueError("colors must contain at least one color pair.")
|
|
815
|
+
else:
|
|
816
|
+
_validate_color_pairs(colors)
|
|
817
|
+
|
|
818
|
+
key = _duotone_key(_load_image(image_path), space)
|
|
819
|
+
|
|
820
|
+
if colors is None:
|
|
821
|
+
# Seeded colors support reproducible art direction, not security.
|
|
822
|
+
rng = random.Random(seed) # nosec B311
|
|
823
|
+
pairs = [
|
|
824
|
+
(generate_random_color(rng), generate_random_color(rng))
|
|
825
|
+
for _ in range(count)
|
|
826
|
+
]
|
|
827
|
+
else:
|
|
828
|
+
pairs = list(colors)
|
|
829
|
+
|
|
830
|
+
stem = os.path.splitext(os.path.basename(image_path))[0]
|
|
831
|
+
base = output_dir if output_dir is not None else os.path.dirname(image_path)
|
|
832
|
+
output_folder = os.path.join(base, f"{stem}_duotone_variations")
|
|
833
|
+
|
|
834
|
+
planned_files = {
|
|
835
|
+
f"{i:03d}_{rgb_to_hex(color1).lstrip('#')}_"
|
|
836
|
+
f"{rgb_to_hex(color2).lstrip('#')}.png"
|
|
837
|
+
for i, (color1, color2) in enumerate(pairs)
|
|
838
|
+
}
|
|
839
|
+
with _batch_output_folder(
|
|
840
|
+
output_folder, base, stem, planned_files
|
|
841
|
+
) as staged_folder:
|
|
842
|
+
color_records: list[list[int | str]] = []
|
|
843
|
+
metric_records: list[list[int | float | str]] = []
|
|
844
|
+
for i, (color1, color2) in enumerate(pairs):
|
|
845
|
+
duotone = create_duotone_image(key, color1, color2, space)
|
|
846
|
+
|
|
847
|
+
hex1 = rgb_to_hex(color1)
|
|
848
|
+
hex2 = rgb_to_hex(color2)
|
|
849
|
+
|
|
850
|
+
filename = f"{i:03d}_{hex1.lstrip('#')}_{hex2.lstrip('#')}.png"
|
|
851
|
+
output_path = os.path.join(staged_folder, filename)
|
|
852
|
+
if not cv2.imwrite(output_path, duotone):
|
|
853
|
+
raise OSError(f"Failed to write '{output_path}'.")
|
|
854
|
+
color_records.append([i, hex1, hex2])
|
|
855
|
+
|
|
856
|
+
# Per-pixel CIEDE2000 (Sharma, Wu & Dalal, 2005) between this
|
|
857
|
+
# variation and its perceptual reference: the same pair blended
|
|
858
|
+
# in Oklab over the same key. In the 'oklab' space this measures
|
|
859
|
+
# only quantization error; in the other spaces it measures the
|
|
860
|
+
# perceptual cost of that blend space.
|
|
861
|
+
height, width = key.shape
|
|
862
|
+
tile_rows = max(1, _CIEDE2000_TILE_PIXELS // width)
|
|
863
|
+
delta_e = np.empty((height, width), dtype=np.float32)
|
|
864
|
+
for row_start in range(0, height, tile_rows):
|
|
865
|
+
row_end = min(row_start + tile_rows, height)
|
|
866
|
+
delta_e[row_start:row_end] = _duotone_delta_e00_tile(
|
|
867
|
+
key[row_start:row_end],
|
|
868
|
+
duotone[row_start:row_end],
|
|
869
|
+
color1,
|
|
870
|
+
color2,
|
|
871
|
+
)
|
|
872
|
+
metric_records.append([
|
|
873
|
+
i, hex1, hex2, space,
|
|
874
|
+
round(float(delta_e.mean()), 4),
|
|
875
|
+
round(float(np.median(delta_e)), 4),
|
|
876
|
+
round(float(np.percentile(delta_e, 95)), 4),
|
|
877
|
+
])
|
|
878
|
+
|
|
879
|
+
csv_path = os.path.join(staged_folder, "colors.csv")
|
|
880
|
+
with open(csv_path, "w", newline="") as f:
|
|
881
|
+
writer = csv.writer(f)
|
|
882
|
+
writer.writerow(["variation", "color_1_hex", "color_2_hex"])
|
|
883
|
+
writer.writerows(color_records)
|
|
884
|
+
|
|
885
|
+
metrics_path = os.path.join(staged_folder, "metrics.csv")
|
|
886
|
+
with open(metrics_path, "w", newline="") as f:
|
|
887
|
+
writer = csv.writer(f)
|
|
888
|
+
writer.writerow(
|
|
889
|
+
["variation", "color_1_hex", "color_2_hex", "space",
|
|
890
|
+
"mean_deltaE00", "median_deltaE00", "p95_deltaE00"]
|
|
891
|
+
)
|
|
892
|
+
writer.writerows(metric_records)
|
|
893
|
+
|
|
894
|
+
return output_folder, color_records
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def main(argv: list[str] | None = None) -> None:
|
|
898
|
+
"""Console entry point: process the image argument, or launch the GUI."""
|
|
899
|
+
parser = argparse.ArgumentParser(
|
|
900
|
+
description="Generate duotone variations of an image."
|
|
901
|
+
)
|
|
902
|
+
parser.add_argument(
|
|
903
|
+
"image",
|
|
904
|
+
nargs="?",
|
|
905
|
+
help="Path to the source image (JPEG, PNG, BMP). "
|
|
906
|
+
"When omitted, file dialogs open instead.",
|
|
907
|
+
)
|
|
908
|
+
parser.add_argument(
|
|
909
|
+
"-o", "--output-dir",
|
|
910
|
+
default=None,
|
|
911
|
+
help="Directory under which the output folder is created "
|
|
912
|
+
"(default: alongside the source image).",
|
|
913
|
+
)
|
|
914
|
+
parser.add_argument(
|
|
915
|
+
"-n", "--count",
|
|
916
|
+
type=int,
|
|
917
|
+
default=None,
|
|
918
|
+
help=f"Number of random variations to generate "
|
|
919
|
+
f"(default: {DEFAULT_VARIATION_COUNT}).",
|
|
920
|
+
)
|
|
921
|
+
parser.add_argument(
|
|
922
|
+
"--seed",
|
|
923
|
+
type=int,
|
|
924
|
+
default=None,
|
|
925
|
+
help="Seed for random color generation; reuse a seed to reproduce "
|
|
926
|
+
"a batch exactly.",
|
|
927
|
+
)
|
|
928
|
+
parser.add_argument(
|
|
929
|
+
"--colors",
|
|
930
|
+
action="append",
|
|
931
|
+
default=None,
|
|
932
|
+
metavar="HEX1,HEX2",
|
|
933
|
+
help="Explicit color pair(s) instead of random ones, e.g. "
|
|
934
|
+
"--colors '#2CD2B4,#DC1E5A'. Repeatable; one variation per pair. "
|
|
935
|
+
"Cannot be combined with --count or --seed.",
|
|
936
|
+
)
|
|
937
|
+
parser.add_argument(
|
|
938
|
+
"--space",
|
|
939
|
+
choices=SPACES,
|
|
940
|
+
default=None,
|
|
941
|
+
help="Color space for the blend: srgb is the legacy gamma-space "
|
|
942
|
+
"blend; linear and oklab blend in linear sRGB and Oklab "
|
|
943
|
+
"(Ottosson, 2020) over a relative-luminance key "
|
|
944
|
+
"(default: srgb).",
|
|
945
|
+
)
|
|
946
|
+
args = parser.parse_args(argv)
|
|
947
|
+
|
|
948
|
+
if not args.image:
|
|
949
|
+
flags_used = (
|
|
950
|
+
args.output_dir is not None
|
|
951
|
+
or args.count is not None
|
|
952
|
+
or args.seed is not None
|
|
953
|
+
or args.colors
|
|
954
|
+
or args.space is not None
|
|
955
|
+
)
|
|
956
|
+
if flags_used:
|
|
957
|
+
parser.error(
|
|
958
|
+
"--output-dir, --count, --seed, --colors and --space require "
|
|
959
|
+
"an image path"
|
|
960
|
+
)
|
|
961
|
+
try:
|
|
962
|
+
select_image()
|
|
963
|
+
except ImportError:
|
|
964
|
+
parser.exit(1, "Error: tkinter is not installed; "
|
|
965
|
+
"pass an image path to use CLI mode.\n")
|
|
966
|
+
return
|
|
967
|
+
|
|
968
|
+
space = args.space or "srgb"
|
|
969
|
+
colors = None
|
|
970
|
+
if args.colors:
|
|
971
|
+
if args.count is not None or args.seed is not None:
|
|
972
|
+
parser.error("--colors cannot be combined with --count or --seed")
|
|
973
|
+
try:
|
|
974
|
+
colors = [parse_color_pair(spec) for spec in args.colors]
|
|
975
|
+
except ValueError as e:
|
|
976
|
+
parser.error(str(e))
|
|
977
|
+
|
|
978
|
+
count = args.count if args.count is not None else DEFAULT_VARIATION_COUNT
|
|
979
|
+
|
|
980
|
+
# Surface each processing failure as a concise CLI error with a nonzero exit.
|
|
981
|
+
try:
|
|
982
|
+
output_folder, records = convert_to_duotone(
|
|
983
|
+
args.image, output_dir=args.output_dir, count=count,
|
|
984
|
+
seed=args.seed, colors=colors, space=space,
|
|
985
|
+
)
|
|
986
|
+
except Exception as e: # noqa: BLE001
|
|
987
|
+
parser.exit(1, f"Error: {e}\n")
|
|
988
|
+
|
|
989
|
+
print(_success_message(output_folder, len(records)))
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
if __name__ == "__main__":
|
|
993
|
+
main()
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: duotonics
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Reproducible duotone image processing with OpenCV and NumPy, available as a Python CLI, library, and tkinter GUI.
|
|
5
|
+
Author: Michail Semoglou
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/MichailSemoglou/duotonics
|
|
8
|
+
Project-URL: Repository, https://github.com/MichailSemoglou/duotonics
|
|
9
|
+
Project-URL: Issues, https://github.com/MichailSemoglou/duotonics/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/MichailSemoglou/duotonics/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: duotone,image-processing,opencv,numpy,color
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: opencv-python-headless<5,>=4.5.5
|
|
28
|
+
Requires-Dist: numpy<3,>=1.22
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# Duotonics
|
|
32
|
+
|
|
33
|
+
[](https://github.com/MichailSemoglou/duotonics/actions/workflows/tests.yml)
|
|
34
|
+
[](https://github.com/MichailSemoglou/duotonics/blob/main/LICENSE)
|
|
35
|
+
|
|
36
|
+
Duotonics is a Python application for reproducible two-color imaging. It blends random or explicit color pairs over a source image's tonal key in gamma-encoded sRGB (legacy), linear sRGB, or Oklab (Ottosson, 2020). It accepts JPEG, PNG, and BMP input and writes a batch of lossless PNGs (100 by default) plus `colors.csv` and `metrics.csv` sidecars. The application is usable through file dialogs, a command-line interface, or as a Python library.
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
|
|
40
|
+
- Image selection via a file dialog
|
|
41
|
+
- Generates 100 duotone variations as lossless **PNG** files (count configurable)
|
|
42
|
+
- Filenames use **hex color codes** in RGB order (e.g. `083_2CD2B4_DC1E5A.png`), ready to paste into Figma, Illustrator, or your design system
|
|
43
|
+
- Produces a **`colors.csv` sidecar** listing every variation's color pair for easy reference and sharing
|
|
44
|
+
- Produces a **`metrics.csv` sidecar** reporting mean, median, and 95th-percentile CIEDE2000 (Sharma, Wu & Dalal, 2005) for every variation against its Oklab-rendered perceptual reference
|
|
45
|
+
- Command-line mode with reproducible batches (`--seed`), configurable variation count (`--count`), explicit color pairs (`--colors`), and blend space (`--space srgb|linear|oklab`)
|
|
46
|
+
- Uses OpenCV for efficient image processing
|
|
47
|
+
|
|
48
|
+
## Example batch
|
|
49
|
+
|
|
50
|
+
One source photograph, 100 duotone variations generated with `--count 100 --seed 42 --space oklab`:
|
|
51
|
+
|
|
52
|
+

|
|
53
|
+
|
|
54
|
+
Source: NASA's photograph of astronaut Eileen Collins, public domain, from the [scikit-image `astronaut` dataset](https://scikit-image.org/docs/stable/api/skimage.data.html#skimage.data.astronaut).
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
Duotonics requires Python 3.9 or higher. Install it from a source checkout:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
git clone https://github.com/MichailSemoglou/duotonics.git
|
|
62
|
+
cd duotonics
|
|
63
|
+
python -m pip install .
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
This installs the `duotonics` command and the `duotone_generator` Python module. After the PyPI release, installation will also be available with `python -m pip install duotonics`.
|
|
67
|
+
|
|
68
|
+
## Usage
|
|
69
|
+
|
|
70
|
+
### Interactive mode
|
|
71
|
+
|
|
72
|
+
Run the command without arguments:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
duotonics
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Direct script execution remains available from a source checkout:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
python3 duotone_generator.py
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
1. A file dialog will open. Select the image you want to process, then choose an output directory.
|
|
85
|
+
|
|
86
|
+
2. The script will generate 100 duotone variations in a new folder named `[original_filename]_duotone_variations`. Each variation is a lossless PNG file named after its two hex color values (e.g. `083_2CD2B4_DC1E5A.png`). A `colors.csv` file is also written to the same folder, listing every variation's color pair.
|
|
87
|
+
|
|
88
|
+
3. A message box will appear when the process is complete, indicating the location of the output folder.
|
|
89
|
+
|
|
90
|
+
### Command-line mode
|
|
91
|
+
|
|
92
|
+
Pass the image path as an argument to run without any dialogs, suitable for scripting and headless environments:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
duotonics path/to/image.png [--output-dir DIR] [--count N] [--seed S] [--colors "HEX1,HEX2"] [--space {srgb,linear,oklab}]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `-o, --output-dir DIR`: place the output folder under DIR instead of alongside the source image.
|
|
99
|
+
- `--count N`: number of random variations (default: 100).
|
|
100
|
+
- `--seed S`: reproduce a batch exactly by reusing its seed.
|
|
101
|
+
- `--colors "#2CD2B4,#DC1E5A"`: apply explicit color pairs instead of random ones; repeatable, one variation per pair. Cannot be combined with `--count` or `--seed`.
|
|
102
|
+
- `--space {srgb,linear,oklab}`: where the blend runs. `srgb` (default) is the legacy gamma-space blend. `linear` blends linear light (IEC 61966-2-1; Poynton, 2003) and `oklab` blends in Oklab (Ottosson, 2020); both derive the key from ITU-R BT.709 relative luminance instead of grayscale luma.
|
|
103
|
+
|
|
104
|
+
The location of the output folder is printed on completion.
|
|
105
|
+
|
|
106
|
+
### Library use
|
|
107
|
+
|
|
108
|
+
The module can be imported and used as a library, without tkinter installed:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from duotone_generator import convert_to_duotone
|
|
112
|
+
|
|
113
|
+
folder, records = convert_to_duotone("photo.png", count=25, seed=42, space="oklab")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
It returns the output folder path and a list of `[index, color_1_hex, color_2_hex]` records, one per variation. Each batch also writes `metrics.csv`, whose rows report the mean, median, and 95th-percentile CIEDE2000 (Sharma, Wu & Dalal, 2005) between that variation and its perceptual reference, defined as the same color pair blended in Oklab over the same key. See the `convert_to_duotone` docstring for all parameters.
|
|
117
|
+
|
|
118
|
+
## Dependencies
|
|
119
|
+
|
|
120
|
+
- OpenCV (cv2)
|
|
121
|
+
- NumPy
|
|
122
|
+
- Tkinter (usually comes pre-installed with Python; only needed for interactive mode)
|
|
123
|
+
|
|
124
|
+
## Requirements
|
|
125
|
+
|
|
126
|
+
- Python 3.9 or higher
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
Install the package in editable mode with its development dependencies, then run the test suite with coverage:
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
python -m pip install -e . -r requirements-dev.txt
|
|
134
|
+
pytest --cov --cov-report=term-missing
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Build and check the wheel and source distribution with:
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
python -m build
|
|
141
|
+
python -m twine check dist/*
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Community
|
|
145
|
+
|
|
146
|
+
- [Contribution guide](https://github.com/MichailSemoglou/duotonics/blob/main/CONTRIBUTING.md)
|
|
147
|
+
- [Code of conduct](https://github.com/MichailSemoglou/duotonics/blob/main/CODE_OF_CONDUCT.md)
|
|
148
|
+
- [Security policy](https://github.com/MichailSemoglou/duotonics/blob/main/SECURITY.md)
|
|
149
|
+
|
|
150
|
+
## License
|
|
151
|
+
|
|
152
|
+
MIT. See the [LICENSE](https://github.com/MichailSemoglou/duotonics/blob/main/LICENSE) file for details.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
duotone_generator.py,sha256=E4lcHB-iq1Giedv_9CPpPIOLEvvdtoHyWB1S9jYSETY,38548
|
|
2
|
+
duotonics-1.0.0.dist-info/licenses/LICENSE,sha256=VT9OJV8STaANXy1u5-BItO4dAduBnmRbGgNph3hOZlw,1073
|
|
3
|
+
duotonics-1.0.0.dist-info/METADATA,sha256=6uhF6VHqp59gJc4isXA3Z782OU3W4DOnU6bHUbxYy0s,7132
|
|
4
|
+
duotonics-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
duotonics-1.0.0.dist-info/entry_points.txt,sha256=V7t4FX-r3F7B_g6oXd2KxHsDOlwCz7cX-bS9JgWnnRU,53
|
|
6
|
+
duotonics-1.0.0.dist-info/top_level.txt,sha256=rLLnsjcfS27gZvGI8uBqGSIfxEqDJZSaXhcqqAsvtJc,18
|
|
7
|
+
duotonics-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michail Semoglou
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
duotone_generator
|