Compare commits
12 Commits
3887505e40
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d2451ff42 | |||
| 7c851c1d4a | |||
| 4b4cf9aae8 | |||
| 1b9848d14f | |||
| da6bc2a4f7 | |||
| 5e636e082c | |||
| 08659faea9 | |||
| f7e3731724 | |||
| bb6e6d9b64 | |||
| d35ad9e944 | |||
| 5eda0b70bd | |||
| 9f63e7c078 |
56
README.md
56
README.md
@@ -12,23 +12,26 @@ average repeated scans, and relate results to ink mix formulas.
|
||||
`auto-scan.sh` runs the whole process in one go:
|
||||
|
||||
1. **Checks required software** — verifies `python3` and ArgyllCMS
|
||||
(`spotread`) are available. Installs python3 via apt and downloads
|
||||
ArgyllCMS to `~/.local/bin` automatically if missing.
|
||||
(`spotread`) are available. Installs python3 (via `apt` on Linux or
|
||||
Homebrew on macOS) and downloads ArgyllCMS to `~/.local/bin`
|
||||
automatically if missing.
|
||||
2. **Waits for the instrument** — prompts you to connect the i1Pro 2 via
|
||||
USB and re-checks until it is detected.
|
||||
3. **Scans the samples** — lists the sample names from `samples.txt` in
|
||||
measurement order, then starts `spotread`. You first calibrate on the
|
||||
white tile, then take one reading per sample with the instrument
|
||||
button, and press **Q** when all readings are done. If the number of
|
||||
readings doesn't match `samples.txt`, the scan can be discarded to
|
||||
`archive/` and repeated.
|
||||
button. After each reading the terminal prints the **next sample
|
||||
code** so you know which one to scan next; press **Q** when all
|
||||
readings are done. If the number of readings doesn't match
|
||||
`samples.txt`, the scan can be discarded to `archive/` and repeated.
|
||||
4. **Saves a labelled CSV** — converts the spotread TSV log to
|
||||
`scan_<mode>_<timestamp>.csv` with a `sample_id` column taken from
|
||||
`samples.txt`.
|
||||
5. **Updates the averages** — re-averages **all** complete scan CSVs in
|
||||
the folder into `averaged.csv` (L\*, a\*, b\* mean and standard
|
||||
deviation per sample), then asks whether to rebuild the formula table
|
||||
`formula.csv` (default: yes).
|
||||
deviation per sample, plus a `dE00` CIEDE2000 column against each
|
||||
sample's named reference) and a formatted `averaged.html` view, then asks
|
||||
whether to rebuild the formula table `formula.csv` (default: yes).
|
||||
|
||||
### Options
|
||||
|
||||
@@ -46,10 +49,27 @@ is built only from scans of the mode you pass (default D50).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Linux with bash, python3 (auto-installed if missing)
|
||||
### Operating system
|
||||
|
||||
The scripts run on **Linux** and **macOS**:
|
||||
|
||||
- **Linux** — the primary target. Uses `apt` to install python3 if missing
|
||||
and udev rules for USB access (see below). Ships bash 4+.
|
||||
- **macOS** — supported. The default `/bin/bash` is 3.2, so `auto-scan.sh`
|
||||
is written to stay compatible with it; no newer bash is required. python3
|
||||
is installed via [Homebrew](https://brew.sh) if missing, and ArgyllCMS
|
||||
uses the macOS build (runs under Rosetta 2 on Apple Silicon). macOS needs
|
||||
no udev rules. Note: only the desktop workflow is verified on Linux; the
|
||||
macOS paths are portability fixes and have not been hardware-tested.
|
||||
- **Windows** — not supported (no Bourne shell / udev; use WSL instead).
|
||||
|
||||
### Other requirements
|
||||
|
||||
- bash, python3 (auto-installed if missing)
|
||||
- ArgyllCMS (auto-downloaded to `~/.local/bin/Argyll_V3.4.1` if missing)
|
||||
- X-Rite i1Pro 2 with its white calibration tile
|
||||
- (Recommended, one time) udev rules so the instrument works without root:
|
||||
- (Linux only, recommended, one time) udev rules so the instrument works
|
||||
without root:
|
||||
|
||||
```bash
|
||||
sudo ./setup-udev.sh
|
||||
@@ -66,14 +86,18 @@ material codes); copy the template to create your own:
|
||||
cp samples.example.txt samples.txt
|
||||
```
|
||||
|
||||
Lines starting with `#` are ignored. Material names can be any codes.
|
||||
Lines starting with `#` are comments. Lines starting with `note:` are
|
||||
metadata shown above the table in `averaged.html` (not samples). Material
|
||||
names can be any codes. Append ` > REF` to measure that sample's `dE00`
|
||||
against another sample; a bare name (no `>`) is itself a **reference**.
|
||||
Mix samples use the pattern `NAME_A+NAME_B[w1 to w2 mix]`, e.g.:
|
||||
|
||||
```text
|
||||
note: Glaze: CPO1192
|
||||
INK_A
|
||||
INK_B
|
||||
INK_A+INK_B[75 to 15 mix]
|
||||
INK_A+INK_C[30 to 80 mix]
|
||||
INK_B > INK_A
|
||||
INK_A+INK_B[75 to 15 mix] > INK_A
|
||||
INK_A+INK_C[30 to 80 mix] > INK_A
|
||||
```
|
||||
|
||||
The weights are converted to percentages in the formula table
|
||||
@@ -86,7 +110,8 @@ discovers the material names automatically from your sample list.
|
||||
|------|----------|
|
||||
| `scan_D50_<timestamp>.tsv` | Raw spotread log (Lab + XYZ + spectrum 380–730 nm) |
|
||||
| `scan_D50_<timestamp>.csv` | Same data as CSV with `sample_id` column |
|
||||
| `averaged.csv` | Per-sample L\*, a\*, b\* mean and std across all scans |
|
||||
| `averaged.csv` | Per-sample L\*, a\*, b\* mean and std, plus `dE00` vs each sample's reference |
|
||||
| `averaged.html` | Formatted view of `averaged.csv` with color swatches |
|
||||
| `formula.csv` | Averaged Lab plus one percentage column per ink |
|
||||
| `archive/` | Discarded or superseded scans |
|
||||
|
||||
@@ -98,8 +123,9 @@ These are used by `auto-scan.sh` but can also be run on their own:
|
||||
|--------|---------|
|
||||
| `measure.sh [mode]` | Just the spotread measurement session (TSV output) |
|
||||
| `run-measurement.sh [mode]` | Measurement session + CSV conversion |
|
||||
| `prompt-next-sample.py -s samples.txt -- spotread …` | Wrap spotread and print the next sample code after each reading |
|
||||
| `tsv-to-csv.py <tsv> [-s samples.txt]` | Convert a spotread TSV to labelled CSV |
|
||||
| `average-results.py <csv...> -o out.csv` | Average Lab across scan CSVs |
|
||||
| `average-results.py <csv...> -o out.csv` | Average Lab across scan CSVs (writes CSV + HTML) |
|
||||
| `build-formula-table.py` | Rebuild `formula.csv` from the averaged CSV |
|
||||
| `rebuild-average.sh` | Shortcut for `./auto-scan.sh --average-only` |
|
||||
| `setup-udev.sh` | Install udev rules for USB instrument access (sudo) |
|
||||
|
||||
51
auto-scan.sh
51
auto-scan.sh
@@ -19,7 +19,12 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
ARGYLL_VERSION="3.4.1"
|
||||
ARGYLL_URL="https://www.argyllcms.com/Argyll_V${ARGYLL_VERSION}_linux_x86_64.tgz"
|
||||
OS="$(uname -s)"
|
||||
case "$OS" in
|
||||
Darwin) ARGYLL_PKG="osx10.6_x86_64" ;; # runs under Rosetta 2 on Apple Silicon
|
||||
*) ARGYLL_PKG="linux_x86_64" ;;
|
||||
esac
|
||||
ARGYLL_URL="https://www.argyllcms.com/Argyll_V${ARGYLL_VERSION}_${ARGYLL_PKG}.tgz"
|
||||
SAMPLES_FILE="samples.txt"
|
||||
AVERAGED_CSV="averaged.csv"
|
||||
FORMULA_CSV="formula.csv"
|
||||
@@ -44,22 +49,32 @@ done
|
||||
info() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
|
||||
warn() { printf '\033[1;33mWARNING: %s\033[0m\n' "$*" >&2; }
|
||||
fail() { printf '\033[1;31mERROR: %s\033[0m\n' "$*" >&2; exit 1; }
|
||||
# Lowercase helper: macOS ships bash 3.2, which lacks ${var,,}.
|
||||
lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
|
||||
|
||||
# ---------------------------------------------------------------- step 1
|
||||
check_dependencies() {
|
||||
info "Step 1/5: Checking required software"
|
||||
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
warn "python3 not found - attempting to install (needs sudo)"
|
||||
sudo apt-get update && sudo apt-get install -y python3 \
|
||||
|| fail "Could not install python3"
|
||||
warn "python3 not found - attempting to install"
|
||||
if [[ "$OS" == "Darwin" ]]; then
|
||||
command -v brew >/dev/null 2>&1 \
|
||||
|| fail "python3 not found. Install Homebrew (https://brew.sh), then: brew install python3"
|
||||
brew install python3 || fail "Could not install python3 via brew"
|
||||
elif command -v apt-get >/dev/null 2>&1; then
|
||||
sudo apt-get update && sudo apt-get install -y python3 \
|
||||
|| fail "Could not install python3"
|
||||
else
|
||||
fail "python3 not found and no supported package manager (apt-get/brew) available"
|
||||
fi
|
||||
fi
|
||||
echo " python3: $(command -v python3)"
|
||||
|
||||
if ! command -v spotread >/dev/null 2>&1; then
|
||||
# Look for an existing local ArgyllCMS install first
|
||||
local argyll_bin
|
||||
argyll_bin="$(ls -d "$HOME"/.local/bin/Argyll_V*/bin 2>/dev/null | sort -V | tail -1 || true)"
|
||||
argyll_bin="$(ls -d "$HOME"/.local/bin/Argyll_V*/bin 2>/dev/null | sort | tail -1 || true)"
|
||||
if [[ -n "$argyll_bin" ]]; then
|
||||
export PATH="$argyll_bin:$PATH"
|
||||
fi
|
||||
@@ -79,16 +94,16 @@ check_dependencies() {
|
||||
export PATH="$HOME/.local/bin/Argyll_V${ARGYLL_VERSION}/bin:$PATH"
|
||||
command -v spotread >/dev/null 2>&1 || fail "ArgyllCMS install failed"
|
||||
echo " Installed ArgyllCMS to ~/.local/bin/Argyll_V${ARGYLL_VERSION}"
|
||||
echo " Add this to your ~/.bashrc to make it permanent:"
|
||||
echo " Add this to your shell profile (~/.bashrc or ~/.zshrc) to make it permanent:"
|
||||
echo " export PATH=\"\$HOME/.local/bin/Argyll_V${ARGYLL_VERSION}/bin:\$PATH\""
|
||||
fi
|
||||
echo " spotread: $(command -v spotread)"
|
||||
|
||||
for helper in tsv-to-csv.py average-results.py; do
|
||||
for helper in tsv-to-csv.py average-results.py prompt-next-sample.py; do
|
||||
[[ -f "$helper" ]] || fail "Missing helper script: $helper"
|
||||
done
|
||||
|
||||
if [[ ! -f /etc/udev/rules.d/55-Argyll.rules ]]; then
|
||||
if [[ "$OS" == "Linux" && ! -f /etc/udev/rules.d/55-Argyll.rules ]]; then
|
||||
warn "Argyll udev rules not installed. If the instrument is not detected, run: sudo ./setup-udev.sh"
|
||||
fi
|
||||
}
|
||||
@@ -106,14 +121,20 @@ wait_for_instrument() {
|
||||
echo " No instrument detected. Connect the i1Pro 2 via USB."
|
||||
read -r -p " Press Enter to check again (or Ctrl+C to abort)... "
|
||||
done
|
||||
grep -E "^\s+[0-9]+ = " <<<"$ports" | sed 's/^/ Found:/' || true
|
||||
grep -E "^[[:space:]]+[0-9]+ = " <<<"$ports" | sed 's/^/ Found:/' || true
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- step 3+4
|
||||
scan_samples() {
|
||||
[[ -f "$SAMPLES_FILE" ]] || fail "$SAMPLES_FILE not found"
|
||||
|
||||
mapfile -t SAMPLES < <(grep -v '^#' "$SAMPLES_FILE" | grep -v '^[[:space:]]*$')
|
||||
# Strip an optional " > REF" suffix from displayed names.
|
||||
# A while-read loop is used instead of mapfile for bash 3.2 (macOS) support.
|
||||
SAMPLES=()
|
||||
while IFS= read -r line; do
|
||||
SAMPLES+=("$line")
|
||||
done < <(grep -v '^#' "$SAMPLES_FILE" | grep -iv '^[[:space:]]*note:' \
|
||||
| grep -v '^[[:space:]]*$' | sed -E 's/[[:space:]]*>.*$//')
|
||||
local count="${#SAMPLES[@]}"
|
||||
[[ "$count" -gt 0 ]] || fail "No sample names found in $SAMPLES_FILE"
|
||||
|
||||
@@ -128,6 +149,7 @@ scan_samples() {
|
||||
echo " spotread will start now:"
|
||||
echo " - First calibrate: place the i1Pro 2 on its white tile and follow the prompt"
|
||||
echo " - Then take one reading per sample (press the instrument button)"
|
||||
echo " - The next sample code is printed in the terminal after each reading"
|
||||
echo " - After all $count readings, press Q to finish"
|
||||
echo ""
|
||||
read -r -p " Press Enter to start... "
|
||||
@@ -142,7 +164,7 @@ scan_samples() {
|
||||
spotread_args=(-I "$MODE" "${spotread_args[@]}")
|
||||
fi
|
||||
|
||||
spotread "${spotread_args[@]}"
|
||||
python3 prompt-next-sample.py -s "$SAMPLES_FILE" -- spotread "${spotread_args[@]}"
|
||||
|
||||
[[ -f "$TSV" ]] || fail "No readings were saved ($TSV missing)"
|
||||
|
||||
@@ -150,7 +172,7 @@ scan_samples() {
|
||||
if [[ "$readings" -ne "$count" ]]; then
|
||||
warn "Expected $count readings but got $readings."
|
||||
read -r -p " Keep this scan anyway? [y/N] " ans
|
||||
if [[ "${ans,,}" != "y" ]]; then
|
||||
if [[ "$(lower "$ans")" != "y" ]]; then
|
||||
mkdir -p archive
|
||||
mv "$TSV" "archive/${TSV%.tsv}_incomplete.tsv"
|
||||
fail "Scan discarded (moved to archive/). Re-run ./auto-scan.sh"
|
||||
@@ -168,7 +190,8 @@ update_average() {
|
||||
info "Step 5/5: Updating $AVERAGED_CSV"
|
||||
|
||||
local expected
|
||||
expected="$(grep -v '^#' "$SAMPLES_FILE" | grep -cv '^[[:space:]]*$' || true)"
|
||||
expected="$(grep -v '^#' "$SAMPLES_FILE" | grep -iv '^[[:space:]]*note:' \
|
||||
| grep -cv '^[[:space:]]*$' || true)"
|
||||
|
||||
# Collect scan CSVs (timestamped files only) with the expected reading count
|
||||
local -a scans=()
|
||||
@@ -191,7 +214,7 @@ update_average() {
|
||||
|
||||
if [[ -f build-formula-table.py ]]; then
|
||||
read -r -p " Rebuild $FORMULA_CSV as well? [Y/n] " ans
|
||||
if [[ "${ans,,}" != "n" ]]; then
|
||||
if [[ "$(lower "$ans")" != "n" ]]; then
|
||||
python3 build-formula-table.py -i "$AVERAGED_CSV" -o "$FORMULA_CSV"
|
||||
else
|
||||
echo " Skipped $FORMULA_CSV (rebuild later with: python3 build-formula-table.py)"
|
||||
|
||||
@@ -3,21 +3,315 @@
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import html
|
||||
import math
|
||||
import statistics
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
LAB_COLS = ("L*", "a*", "b*")
|
||||
DE_COL = "dE00"
|
||||
|
||||
# D50 / 2 deg white point, used to render approximate sRGB swatches from Lab.
|
||||
WHITE_POINT = (96.422, 100.0, 82.521)
|
||||
|
||||
# A sample line may name its Delta-E reference as "NAME > REF". Bare names
|
||||
# (no ">") are references themselves. The " > REF" suffix is stripped to
|
||||
# recover the real sample name used as sample_id.
|
||||
REF_SEP = ">"
|
||||
NOTE_PREFIX = "note:"
|
||||
|
||||
|
||||
def load_sample_names(path: Path) -> list[str]:
|
||||
def _is_note_line(line: str) -> bool:
|
||||
return line.strip().lower().startswith(NOTE_PREFIX)
|
||||
|
||||
|
||||
def load_notes(path: Path) -> list[str]:
|
||||
"""Read display notes from 'note: ...' lines in the samples file."""
|
||||
if not path.exists():
|
||||
return []
|
||||
notes = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.lower().startswith(NOTE_PREFIX):
|
||||
notes.append(stripped[len(NOTE_PREFIX) :].strip())
|
||||
return notes
|
||||
|
||||
|
||||
def _parse_sample_line(line: str) -> tuple[str, str | None]:
|
||||
"""Return (sample_name, reference_or_None). Bare name = this sample is a reference."""
|
||||
if REF_SEP in line:
|
||||
name, _, ref = line.partition(REF_SEP)
|
||||
name, ref = name.strip(), ref.strip()
|
||||
return name, ref or None
|
||||
return line.strip(), None
|
||||
|
||||
|
||||
def _sample_lines(path: Path) -> list[str]:
|
||||
return [
|
||||
line.strip()
|
||||
for line in path.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip() and not line.strip().startswith("#")
|
||||
if line.strip()
|
||||
and not line.strip().startswith("#")
|
||||
and not _is_note_line(line)
|
||||
]
|
||||
|
||||
|
||||
def load_sample_names(path: Path) -> list[str]:
|
||||
return [_parse_sample_line(line)[0] for line in _sample_lines(path)]
|
||||
|
||||
|
||||
def load_references(path: Path) -> dict[str, str]:
|
||||
"""Map sample_id -> reference_id for samples that name a reference."""
|
||||
refs: dict[str, str] = {}
|
||||
for line in _sample_lines(path):
|
||||
name, ref = _parse_sample_line(line)
|
||||
if ref:
|
||||
refs[name] = ref
|
||||
return refs
|
||||
|
||||
|
||||
def de2000(lab1, lab2) -> float:
|
||||
"""CIEDE2000 color difference between two (L*, a*, b*) triples."""
|
||||
L1, a1, b1 = lab1
|
||||
L2, a2, b2 = lab2
|
||||
C1 = math.hypot(a1, b1)
|
||||
C2 = math.hypot(a2, b2)
|
||||
Cbar = (C1 + C2) / 2
|
||||
G = 0.5 * (1 - math.sqrt(Cbar**7 / (Cbar**7 + 25**7)))
|
||||
a1p, a2p = a1 * (1 + G), a2 * (1 + G)
|
||||
C1p, C2p = math.hypot(a1p, b1), math.hypot(a2p, b2)
|
||||
h1p = math.degrees(math.atan2(b1, a1p)) % 360
|
||||
h2p = math.degrees(math.atan2(b2, a2p)) % 360
|
||||
dLp = L2 - L1
|
||||
dCp = C2p - C1p
|
||||
dh = h2p - h1p
|
||||
if C1p * C2p == 0:
|
||||
dhp = 0
|
||||
elif abs(dh) <= 180:
|
||||
dhp = dh
|
||||
elif dh > 180:
|
||||
dhp = dh - 360
|
||||
else:
|
||||
dhp = dh + 360
|
||||
dHp = 2 * math.sqrt(C1p * C2p) * math.sin(math.radians(dhp) / 2)
|
||||
Lbp = (L1 + L2) / 2
|
||||
Cbp = (C1p + C2p) / 2
|
||||
if C1p * C2p == 0:
|
||||
hbp = h1p + h2p
|
||||
elif abs(h1p - h2p) <= 180:
|
||||
hbp = (h1p + h2p) / 2
|
||||
elif h1p + h2p < 360:
|
||||
hbp = (h1p + h2p + 360) / 2
|
||||
else:
|
||||
hbp = (h1p + h2p - 360) / 2
|
||||
T = (1 - 0.17 * math.cos(math.radians(hbp - 30))
|
||||
+ 0.24 * math.cos(math.radians(2 * hbp))
|
||||
+ 0.32 * math.cos(math.radians(3 * hbp + 6))
|
||||
- 0.20 * math.cos(math.radians(4 * hbp - 63)))
|
||||
SL = 1 + 0.015 * (Lbp - 50) ** 2 / math.sqrt(20 + (Lbp - 50) ** 2)
|
||||
SC = 1 + 0.045 * Cbp
|
||||
SH = 1 + 0.015 * Cbp * T
|
||||
dTheta = 30 * math.exp(-(((hbp - 275) / 25) ** 2))
|
||||
RC = 2 * math.sqrt(Cbp**7 / (Cbp**7 + 25**7))
|
||||
RT = -RC * math.sin(math.radians(2 * dTheta))
|
||||
return math.sqrt((dLp / SL) ** 2 + (dCp / SC) ** 2 + (dHp / SH) ** 2
|
||||
+ RT * (dCp / SC) * (dHp / SH))
|
||||
|
||||
|
||||
def add_delta_e(rows: list[dict], references: dict[str, str]) -> bool:
|
||||
"""Add a CIEDE2000 column to each averaged row vs that sample's reference.
|
||||
|
||||
Samples absent from `references` are references themselves (dE00 left
|
||||
empty — they have no external comparison). Returns True if the column
|
||||
was written (only when at least one sample names a reference). Never
|
||||
raises so the scan pipeline can continue even when a named reference
|
||||
is missing.
|
||||
"""
|
||||
if not rows or not references:
|
||||
return False
|
||||
|
||||
by_id = {r["sample_id"]: r for r in rows}
|
||||
wrote = False
|
||||
for row in rows:
|
||||
sid = row["sample_id"]
|
||||
ref_id = references.get(sid)
|
||||
if ref_id is None:
|
||||
row[DE_COL] = ""
|
||||
wrote = True
|
||||
continue
|
||||
ref_row = by_id.get(ref_id)
|
||||
if ref_row is None:
|
||||
print(
|
||||
f"Warning: Delta-E reference {ref_id!r} for {sid!r} not found "
|
||||
f"among samples; leaving {DE_COL} empty",
|
||||
file=sys.stderr,
|
||||
)
|
||||
row[DE_COL] = ""
|
||||
continue
|
||||
ref_lab = tuple(ref_row[f"{c}_mean"] for c in LAB_COLS)
|
||||
lab = tuple(row[f"{c}_mean"] for c in LAB_COLS)
|
||||
row[DE_COL] = de2000(ref_lab, lab)
|
||||
wrote = True
|
||||
return wrote
|
||||
|
||||
|
||||
def srgb(L: float, a: float, b: float) -> str:
|
||||
"""Approximate sRGB hex for a CIELAB triple (D50), for display swatches."""
|
||||
fy = (L + 16) / 116
|
||||
fx = fy + a / 500
|
||||
fz = fy - b / 200
|
||||
|
||||
def finv(f):
|
||||
return f**3 if f**3 > 0.008856 else (f - 16 / 116) / 7.787
|
||||
|
||||
X, Y, Z = (finv(f) * w / 100 for f, w in zip((fx, fy, fz), WHITE_POINT))
|
||||
r = 3.1338561 * X - 1.6168667 * Y - 0.4906146 * Z
|
||||
g = -0.9787684 * X + 1.9161415 * Y + 0.0334540 * Z
|
||||
bl = 0.0719453 * X - 0.2289914 * Y + 1.4052427 * Z
|
||||
|
||||
def enc(c):
|
||||
c = max(0.0, min(1.0, c))
|
||||
c = 1.055 * c ** (1 / 2.4) - 0.055 if c > 0.0031308 else 12.92 * c
|
||||
return round(max(0.0, min(1.0, c)) * 255)
|
||||
|
||||
return "#%02x%02x%02x" % (enc(r), enc(g), enc(bl))
|
||||
|
||||
|
||||
def de_bucket(d: float) -> str:
|
||||
if d < 1:
|
||||
return "not perceptible"
|
||||
if d < 2:
|
||||
return "perceptible on close inspection"
|
||||
if d < 3.5:
|
||||
return "perceptible at a glance"
|
||||
return "clearly different"
|
||||
|
||||
|
||||
def write_html(
|
||||
rows: list[dict],
|
||||
references: dict[str, str],
|
||||
path: Path,
|
||||
notes: list[str] | None = None,
|
||||
has_de: bool = False,
|
||||
) -> None:
|
||||
"""Write a self-contained HTML view of the averaged results."""
|
||||
esc = html.escape
|
||||
|
||||
head_cells = [
|
||||
"<th></th>", "<th>Sample</th>", "<th>n</th>",
|
||||
"<th>L*</th>", "<th>a*</th>", "<th>b*</th>",
|
||||
]
|
||||
if has_de:
|
||||
head_cells.append("<th>ΔE00</th>")
|
||||
|
||||
body_rows = []
|
||||
for r in rows:
|
||||
lab = tuple(float(r[f"{c}_mean"]) for c in LAB_COLS)
|
||||
std = tuple(float(r[f"{c}_std"]) for c in LAB_COLS)
|
||||
vs = references.get(r["sample_id"])
|
||||
is_ref = has_de and vs is None
|
||||
is_pred = int(float(r["n_scans"])) == 0
|
||||
row_cls = "ref" if is_ref else ("pred" if is_pred else "")
|
||||
cls = f' class="{row_cls}"' if row_cls else ""
|
||||
ref_tag = ' <span class="tag">reference</span>' if is_ref else ""
|
||||
vs_tag = f' <span class="tag">vs {esc(vs)}</span>' if vs else ""
|
||||
pred_tag = ' <span class="tag">predicted</span>' if is_pred else ""
|
||||
cells = [
|
||||
f'<td><span class="patch" style="background:{srgb(*lab)}"></span></td>',
|
||||
f'<td class="name">{esc(r["sample_id"])}{ref_tag}{vs_tag}{pred_tag}</td>',
|
||||
f'<td>{esc(str(r["n_scans"])) if not is_pred else "—"}</td>',
|
||||
]
|
||||
for m, s in zip(lab, std):
|
||||
cells.append(f'<td>{m:.2f}<span class="std">±{s:.2f}</span></td>')
|
||||
if has_de:
|
||||
raw = r.get(DE_COL, "")
|
||||
if raw == "" or raw is None:
|
||||
cells.append("<td>—</td>")
|
||||
else:
|
||||
d = float(raw)
|
||||
de_cls = "de bad" if d >= 3.5 else "de"
|
||||
cells.append(
|
||||
f'<td class="{de_cls}" title="{esc(de_bucket(d))}">{d:.2f}</td>'
|
||||
)
|
||||
body_rows.append(f' <tr{cls}>{"".join(cells)}</tr>')
|
||||
|
||||
ref_note = (
|
||||
"ΔE00 is CIEDE2000 against each sample's named reference "
|
||||
"; tagged "
|
||||
"<b>reference</b> rows have no external reference. Lower is a closer match."
|
||||
if has_de else
|
||||
"No Delta-E column (add <code>NAME > REF</code> lines in samples.txt)."
|
||||
)
|
||||
generated = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
notes = notes or []
|
||||
notes_html = ""
|
||||
if notes:
|
||||
items = "".join(f"<li>{esc(n)}</li>" for n in notes)
|
||||
notes_html = f' <ul class="notes">{items}</ul>\n'
|
||||
|
||||
html_doc = f"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Averaged color measurements</title>
|
||||
<style>
|
||||
:root {{ --text:#1f2328; --text2:#57606a; --text3:#8b949e; --stroke:#d0d7de;
|
||||
--bg:#fff; --fill:#f6f8fa; --bad:#bc4c00; }}
|
||||
* {{ box-sizing:border-box; }}
|
||||
body {{ margin:0; padding:32px 24px 48px; background:var(--bg); color:var(--text);
|
||||
font:14px/1.5 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; }}
|
||||
main {{ max-width:760px; margin:0 auto; }}
|
||||
h1 {{ font-size:22px; margin:0 0 4px; }}
|
||||
.muted {{ color:var(--text2); margin:0 0 20px; }}
|
||||
.notes {{ list-style:none; padding:0; margin:0 0 20px; color:var(--text2); font-size:13px; }}
|
||||
.notes li {{ margin:2px 0; }}
|
||||
table {{ border-collapse:separate; border-spacing:0; width:100%;
|
||||
border:1px solid var(--stroke); border-radius:8px; overflow:hidden; }}
|
||||
th,td {{ padding:7px 10px; text-align:right; font-size:13px;
|
||||
font-variant-numeric:tabular-nums; }}
|
||||
th:nth-child(2),td.name {{ text-align:left; }}
|
||||
thead th {{ background:var(--fill); font-size:12px; color:var(--text2);
|
||||
border-bottom:1px solid var(--stroke); }}
|
||||
tbody tr + tr td {{ border-top:1px solid var(--stroke); }}
|
||||
tr.ref td {{ background:var(--fill); }}
|
||||
tr.pred td {{ background:#fff8e6; }}
|
||||
tr.pred td.name {{ font-style:italic; }}
|
||||
.patch {{ width:18px; height:18px; display:inline-block; vertical-align:middle;
|
||||
border-radius:5px; border:1px solid var(--stroke); }}
|
||||
.std {{ color:var(--text3); font-size:11px; margin-left:3px; }}
|
||||
.tag {{ font-size:11px; color:var(--text3); border:1px solid var(--stroke);
|
||||
border-radius:4px; padding:0 5px; margin-left:6px; }}
|
||||
.de {{ font-weight:600; }}
|
||||
.bad {{ color:var(--bad); }}
|
||||
.faint {{ color:var(--text3); font-size:12px; margin-top:14px; }}
|
||||
@media print {{ body {{ padding:0; }} }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Averaged color measurements</h1>
|
||||
<p class="muted">Per-sample CIELAB means (± standard deviation) across the
|
||||
averaged scans. {ref_note}</p>
|
||||
{notes_html} <table>
|
||||
<thead>
|
||||
<tr>{"".join(head_cells)}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{chr(10).join(body_rows)}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="faint">Swatches are sRGB approximations of the measured Lab values
|
||||
(D50 / 2°). Generated by average-results.py on {generated}.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
path.write_text(html_doc, encoding="utf-8")
|
||||
|
||||
|
||||
def read_measurements(path: Path, sample_names: list[str]) -> list[dict]:
|
||||
with path.open(newline="", encoding="utf-8") as f:
|
||||
rows = list(csv.DictReader(f))
|
||||
@@ -78,6 +372,7 @@ def main() -> int:
|
||||
args = parser.parse_args()
|
||||
|
||||
sample_names = load_sample_names(args.samples) if args.samples.exists() else []
|
||||
references = load_references(args.samples) if args.samples.exists() else {}
|
||||
|
||||
sets = []
|
||||
for path in args.csv_files:
|
||||
@@ -87,16 +382,33 @@ def main() -> int:
|
||||
sets.append(read_measurements(path, sample_names))
|
||||
|
||||
averaged = average_sets(sets)
|
||||
|
||||
has_de = add_delta_e(averaged, references)
|
||||
|
||||
fieldnames = ["sample_id", "n_scans"]
|
||||
for col in LAB_COLS:
|
||||
fieldnames.extend([f"{col}_mean", f"{col}_std"])
|
||||
if has_de:
|
||||
fieldnames.append(DE_COL)
|
||||
|
||||
with args.output.open("w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(averaged)
|
||||
|
||||
html_path = args.output.with_suffix(".html")
|
||||
notes = load_notes(args.samples) if args.samples.exists() else []
|
||||
write_html(averaged, references, html_path, notes, has_de=has_de)
|
||||
|
||||
print(f"Wrote {len(averaged)} averaged sample(s) to {args.output}")
|
||||
print(f"Wrote HTML view to {html_path}")
|
||||
if has_de:
|
||||
n_ref = sum(1 for r in averaged if r["sample_id"] not in references)
|
||||
n_cmp = sum(1 for r in averaged if r["sample_id"] in references)
|
||||
print(
|
||||
f"{DE_COL} computed as CIEDE2000 vs per-sample references "
|
||||
f"({n_ref} reference(s), {n_cmp} compared)"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
12
measure.sh
12
measure.sh
@@ -45,7 +45,8 @@ esac
|
||||
|
||||
SAMPLE_COUNT=0
|
||||
if [[ -f samples.txt ]]; then
|
||||
SAMPLE_COUNT="$(grep -cv '^#\|^$' samples.txt || true)"
|
||||
SAMPLE_COUNT="$(grep -v '^#' samples.txt | grep -iv '^[[:space:]]*note:' \
|
||||
| grep -cv '^[[:space:]]*$' || true)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
@@ -60,7 +61,8 @@ echo " 1. Calibrate on the white tile when prompted"
|
||||
echo " 2. Place i1Pro on each sample and press the button"
|
||||
if [[ "$SAMPLE_COUNT" -gt 0 ]]; then
|
||||
echo " 3. Take exactly $SAMPLE_COUNT readings, in samples.txt order"
|
||||
echo " 4. Press Q to quit when all readings are done"
|
||||
echo " 4. The next sample code is printed in the terminal after each reading"
|
||||
echo " 5. Press Q to quit when all readings are done"
|
||||
else
|
||||
echo " 3. Press Q to quit when done"
|
||||
fi
|
||||
@@ -68,7 +70,11 @@ echo ""
|
||||
echo "Starting spotread..."
|
||||
echo ""
|
||||
|
||||
spotread "${SPOTREAD_ARGS[@]}"
|
||||
if [[ "$SAMPLE_COUNT" -gt 0 && -f prompt-next-sample.py ]]; then
|
||||
python3 prompt-next-sample.py -s samples.txt -- spotread "${SPOTREAD_ARGS[@]}"
|
||||
else
|
||||
spotread "${SPOTREAD_ARGS[@]}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Done. Convert to CSV with:"
|
||||
|
||||
198
prompt-next-sample.py
Executable file
198
prompt-next-sample.py
Executable file
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wrap spotread and print the next samples.txt code after each reading."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
TAKE_READING = b"take a reading:"
|
||||
RESULT_XYZ = b"Result is XYZ"
|
||||
TAIL = 64
|
||||
|
||||
YELLOW = "\033[1;33m"
|
||||
RESET = "\033[0m"
|
||||
|
||||
|
||||
def load_sample_names(path: Path) -> list[str]:
|
||||
# Optional "NAME > REF": keep only the sample name (before ">").
|
||||
# Skip "#" comments and "note: ..." metadata lines.
|
||||
names = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or line.lower().startswith("note:"):
|
||||
continue
|
||||
if ">" in line:
|
||||
line = line.split(">", 1)[0].strip()
|
||||
names.append(line)
|
||||
return names
|
||||
|
||||
|
||||
def _tty_write(text: str) -> None:
|
||||
try:
|
||||
with open("/dev/tty", "w", encoding="utf-8") as tty:
|
||||
tty.write(text)
|
||||
tty.flush()
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
sys.stderr.write(text)
|
||||
sys.stderr.flush()
|
||||
|
||||
|
||||
def write_banner(message: str) -> None:
|
||||
bar = "=" * 40
|
||||
_tty_write(f"\n{YELLOW}{bar}\n {message}\n{bar}{RESET}\n")
|
||||
|
||||
|
||||
def set_title(title: str) -> None:
|
||||
_tty_write(f"\033]0;{title}\007")
|
||||
|
||||
|
||||
def waitstatus_to_exitcode(status: int) -> int:
|
||||
if hasattr(os, "waitstatus_to_exitcode"):
|
||||
return os.waitstatus_to_exitcode(status)
|
||||
if os.WIFEXITED(status):
|
||||
return os.WEXITSTATUS(status)
|
||||
if os.WIFSIGNALED(status):
|
||||
return 128 + os.WTERMSIG(status)
|
||||
return 1
|
||||
|
||||
|
||||
class Watcher:
|
||||
"""Scan spotread output and announce the next sample at each prompt."""
|
||||
|
||||
def __init__(self, samples: list[str]) -> None:
|
||||
self.samples = samples
|
||||
self.n = len(samples)
|
||||
self.next_idx = 0
|
||||
self.buf = bytearray()
|
||||
self.announced_idx = -1
|
||||
self.done_announced = False
|
||||
|
||||
def feed(self, data: bytes) -> None:
|
||||
if not data:
|
||||
return
|
||||
self.buf.extend(data)
|
||||
while True:
|
||||
take = self.buf.find(TAKE_READING)
|
||||
result = self.buf.find(RESULT_XYZ)
|
||||
if take < 0 and result < 0:
|
||||
if len(self.buf) > TAIL:
|
||||
del self.buf[:-TAIL]
|
||||
return
|
||||
if result >= 0 and (take < 0 or result < take):
|
||||
self._on_result()
|
||||
del self.buf[: result + len(RESULT_XYZ)]
|
||||
else:
|
||||
self._on_take_reading()
|
||||
del self.buf[: take + len(TAKE_READING)]
|
||||
|
||||
def _on_result(self) -> None:
|
||||
self.next_idx += 1
|
||||
self.done_announced = False
|
||||
|
||||
def _on_take_reading(self) -> None:
|
||||
if self.next_idx < self.n:
|
||||
if self.announced_idx != self.next_idx:
|
||||
name = self.samples[self.next_idx]
|
||||
write_banner(f"NEXT ({self.next_idx + 1}/{self.n}): {name}")
|
||||
set_title(f"NEXT: {name} ({self.next_idx + 1}/{self.n})")
|
||||
self.announced_idx = self.next_idx
|
||||
return
|
||||
if self.next_idx == self.n:
|
||||
if not self.done_announced:
|
||||
write_banner(f"All {self.n} samples scanned. Press Q to finish.")
|
||||
set_title(f"All {self.n} scanned — press Q")
|
||||
self.done_announced = True
|
||||
return
|
||||
write_banner(
|
||||
f"EXTRA reading ({self.next_idx} taken, expected {self.n}). "
|
||||
"Press Q to finish."
|
||||
)
|
||||
set_title(f"EXTRA {self.next_idx}/{self.n} — press Q")
|
||||
|
||||
|
||||
def warn_fallback(reason: str) -> None:
|
||||
print(
|
||||
f"WARNING: next-sample prompts unavailable ({reason}); "
|
||||
"running spotread without them",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def run(argv: list[str], samples: list[str]) -> int:
|
||||
if not argv:
|
||||
print("Error: no command to run", file=sys.stderr)
|
||||
return 2
|
||||
if not samples:
|
||||
os.execvp(argv[0], argv)
|
||||
|
||||
try:
|
||||
import pty
|
||||
except ImportError as exc:
|
||||
warn_fallback(str(exc))
|
||||
os.execvp(argv[0], argv)
|
||||
|
||||
watcher = Watcher(samples)
|
||||
|
||||
def master_read(fd: int) -> bytes:
|
||||
data = os.read(fd, 4096)
|
||||
try:
|
||||
watcher.feed(data)
|
||||
except OSError:
|
||||
pass
|
||||
return data
|
||||
|
||||
try:
|
||||
status = pty.spawn(argv, master_read)
|
||||
except OSError as exc:
|
||||
warn_fallback(str(exc))
|
||||
os.execvp(argv[0], argv)
|
||||
|
||||
return waitstatus_to_exitcode(status)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Run a spotread session and print the next sample code from "
|
||||
"samples.txt after each reading."
|
||||
)
|
||||
)
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--samples",
|
||||
type=Path,
|
||||
required=True,
|
||||
help="Text file with one sample name per line (measurement order)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"argv",
|
||||
nargs=argparse.REMAINDER,
|
||||
metavar="COMMAND",
|
||||
help="Command to run (e.g. -- spotread -i D50 -s scan.tsv)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.samples.exists():
|
||||
print(f"Error: {args.samples} not found", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
argv = list(args.argv)
|
||||
if argv and argv[0] == "--":
|
||||
argv = argv[1:]
|
||||
|
||||
try:
|
||||
samples = load_sample_names(args.samples)
|
||||
except OSError as exc:
|
||||
print(f"Error: cannot read {args.samples}: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
return run(argv, samples)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -16,7 +16,8 @@ if [[ -z "$LATEST" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if grep -qv '^#' samples.txt 2>/dev/null && grep -q '[^[:space:]]' samples.txt; then
|
||||
if grep -v '^#' samples.txt 2>/dev/null | grep -iv '^[[:space:]]*note:' \
|
||||
| grep -q '[^[:space:]]'; then
|
||||
./tsv-to-csv.py "$LATEST" -s samples.txt
|
||||
else
|
||||
./tsv-to-csv.py "$LATEST"
|
||||
@@ -24,7 +25,8 @@ fi
|
||||
|
||||
CSV="${LATEST%.tsv}.csv"
|
||||
READING_COUNT="$(($(wc -l < "$LATEST") - 1))"
|
||||
EXPECTED="$(grep -cv '^#\|^$' samples.txt 2>/dev/null || echo 0)"
|
||||
EXPECTED="$(grep -v '^#' samples.txt 2>/dev/null | grep -iv '^[[:space:]]*note:' \
|
||||
| grep -cv '^[[:space:]]*$' || echo 0)"
|
||||
|
||||
echo ""
|
||||
echo "============================================"
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
# One sample name per line, in measurement order.
|
||||
# Lines starting with # are ignored.
|
||||
#
|
||||
# Single materials: just the material name/code, e.g.
|
||||
# INK_A
|
||||
#
|
||||
# Two-material mixes: NAME_A+NAME_B[w1 to w2 mix]
|
||||
# where w1/w2 are relative weights, converted to percentages, e.g.
|
||||
# INK_A+INK_B[75 to 15 mix] -> 83% INK_A + 17% INK_B
|
||||
#
|
||||
# Copy this file to samples.txt and replace with your own materials:
|
||||
# cp samples.example.txt samples.txt
|
||||
INK_A
|
||||
INK_B
|
||||
INK_C
|
||||
INK_A+INK_B[75 to 15 mix]
|
||||
INK_A+INK_C[30 to 80 mix]
|
||||
# One sample name per line, in measurement order.
|
||||
# Lines starting with # are comments (ignored). Lines starting with "note:"
|
||||
# are HTML report metadata (not samples).
|
||||
#
|
||||
# Name a Delta-E reference with "NAME > REF": that sample's dE00 (CIEDE2000
|
||||
# in averaged.csv) is measured against REF. A bare name (no ">") is itself a
|
||||
# reference. Example:
|
||||
# INK_A
|
||||
# INK_B > INK_A
|
||||
#
|
||||
# Optional notes for averaged.html (one per line, NOT starting with #):
|
||||
# note: Print Surface: A4 Paper
|
||||
# note: Temperature: 30 C
|
||||
#
|
||||
# Lines starting with "note:" are metadata for the HTML report, not samples.
|
||||
#
|
||||
# Single materials: just the material name/code, e.g.
|
||||
# INK_A
|
||||
#
|
||||
# Two-material mixes: NAME_A+NAME_B[w1 to w2 mix]
|
||||
# where w1/w2 are relative weights, converted to percentages, e.g.
|
||||
# INK_A+INK_B[75 to 15 mix] -> 83% INK_A + 17% INK_B
|
||||
#
|
||||
# Copy this file to samples.txt and replace with your own materials:
|
||||
# cp samples.example.txt samples.txt
|
||||
note: Print Surface: A4 Paper
|
||||
note: Temperature: 30 ℃
|
||||
INK_A
|
||||
INK_B > INK_A
|
||||
INK_C > INK_A
|
||||
INK_A+INK_B[75 to 15 mix] > INK_A
|
||||
INK_A+INK_C[30 to 80 mix] > INK_A
|
||||
|
||||
@@ -8,11 +8,16 @@ from pathlib import Path
|
||||
|
||||
|
||||
def load_sample_names(path: Path) -> list[str]:
|
||||
# Optional "NAME > REF": keep only the sample name (before ">").
|
||||
# Skip "#" comments and "note: ..." metadata lines.
|
||||
names = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
names.append(line)
|
||||
if not line or line.startswith("#") or line.lower().startswith("note:"):
|
||||
continue
|
||||
if ">" in line:
|
||||
line = line.split(">", 1)[0].strip()
|
||||
names.append(line)
|
||||
return names
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user