# Hybrid Viewing Methods for VMS Folio Analysis

**Context:** Methods developed during the f1r visual analysis session (2026-04-15). Used to extract readable text from RGB scans of degraded vellum at character-level zoom, and to reveal scraped/erased marginal annotations.

**Origin:** The individual image-processing techniques are all standard and well-documented. The assembly into a VMS-folio-specific workflow, the parameter choices, and the coordinate-mapping protocol for progressive zoom are what was built here.

## Stack

- Python 3 + numpy 1.26 + scipy 1.17 + PIL 10.2
- No manuscript-imaging-specific tools (no ImageJ, no AIC-FAIC, no Hokku, no multispectral libraries)

## Source data

- `ZL_ivtff_2b.txt` — Zandbergen/Landini IVTFF transcription (for line-level content reference)
- `0002_1r.jpg` (2000×2534 RGB JPEG) — Yale Beinecke scan of f1r

## Pipeline stages

### 1. Line localization via row variance

For a column-restricted slice of the page greyscale, compute per-row variance. Text rows have higher variance than blank vellum. Smooth with a Gaussian (σ=3-4) and run `scipy.signal.find_peaks` with `distance=40` for ~55px VMS line spacing.

```python
arr = np.array(img.convert('L')).astype(np.float32)
col = arr[:, 350:1800]           # text column, skip margins
row_var = np.var(col, axis=1)
sm = ndimage.gaussian_filter1d(row_var, sigma=3)
peaks, _ = find_peaks(sm, height=280, distance=40)
```

Key choices:
- `x=350:1800` excludes binding edge and outer margin where variance is dominated by damage
- Threshold `height=280` tuned to separate real text rows from vellum texture
- `distance=40` prevents double-detection of ascenders/descenders

### 2. Tight text-band cropping

Each detected peak defines a text baseline. Crop ±17 pixels around it to get just the ink band (not full line spacing). This avoids including blank vellum which dilutes subsequent enhancement.

```python
line = img.crop((340, peak_y - 17, 1870, peak_y + 15))
```

### 3. Difference of Gaussians (character scale)

DoG band-pass tuned to VMS pen-stroke width. Two regimes used:

- **Character-scale text extraction**: σ₁=0.5, σ₂=5. Picks up strokes ~3-15px wide (VMS x-height ~20px in this scan).
- **Margin-annotation scale (larger Latin script)**: σ₁=1, σ₂=10. For erased 4-5mm Latin characters.

```python
B = arr[:,:,2]                    # blue channel — best ink contrast
dog = -(ndimage.gaussian_filter(B, sigma_1) - ndimage.gaussian_filter(B, sigma_2))
```

The **inversion** is important: raw DoG has ink = negative (dark on light), inverted gives ink = positive (bright on dark), which reads better after percentile stretching.

### 4. Percentile stretching

Avoid sensitivity to outliers (holes, damage, binding shadow):

```python
mn, mx = np.percentile(dog, 3), np.percentile(dog, 97)
norm = np.clip((dog - mn) / (mx - mn) * 255, 0, 255).astype(np.uint8)
```

For very faint text use (1, 99). For noisy regions use (5, 95).

### 5. CLAHE-style local contrast (hand-rolled)

When DoG isn't enough — usually for the erased margin annotations, where ink remnants vary in depth across the region. Compute local mean and standard deviation using `uniform_filter`, then normalize:

```python
lm = ndimage.uniform_filter(B, size=sigma)
centered = B - lm
local_std = np.sqrt(ndimage.uniform_filter(centered**2, size=sigma))
local_std = np.maximum(local_std, 0.3)   # prevent div-by-zero
clahe_approx = -(centered / local_std)   # invert so ink is bright
```

Window sizes:
- `size=8-15`: for character-scale features
- `size=25-40`: for broader erased text patches

This is **not** true CLAHE (which uses tile histograms and clipping). It's a continuous approximation that gives similar results without the tile boundaries.

### 6. Hole masking

Vellum holes (wormholes, physical damage) show as extreme values and dominate DoG output. Mask them before filtering:

```python
hole_mask = grey < 20                                      # deep shadow = hole
hole_mask_d = ndimage.binary_dilation(hole_mask, iterations=4)
B_filled = B.copy()
lm = ndimage.uniform_filter(B, size=25)
B_filled[hole_mask_d] = lm[hole_mask_d]                    # fill with local mean
# then apply DoG to B_filled
```

Also mask very bright pixels (`grey > 235`) which are tears showing vellum-backing through-light.

### 7. Differential channel maps

Some scraped/erased ink remnants show more clearly in channel differences than any single channel:

```python
R, G, B = arr[:,:,0], arr[:,:,1], arr[:,:,2]
RminusG = R - G       # often reveals tannin-based inks
RminusB = R - B       # detects warm-vs-cool shifts
```

Pass these through CLAHE-style local contrast same as raw channels.

### 8. False colour composites

Map different enhancement products to R/G/B channels to visually differentiate features:

```python
r_ch = saturation_map                   # erased ink = desaturated
g_ch = clahe_blue_inverted              # iron gall response
b_ch = hessian_frobenius                # linear stroke response
false_colour = np.stack([r_ch, g_ch, b_ch], axis=2).astype(np.uint8)
```

Pen strokes appear cyan/green; vellum stays yellow/orange; damage appears red.

### 9. Progressive zoom + coordinate mapping

VMS folios require zoom beyond the source JPEG's native resolution (2000px wide). Protocol:

1. Crop from source at native resolution
2. Upscale with `Image.LANCZOS` (bicubic with sharper kernel) to 3-8×
3. For sub-regions, crop from the original source (never from upscaled) to avoid compounding interpolation artifacts

Display coordinates communicated to the viewer need a mapping factor. When the viewer reports `"original AxB, displayed at CxD"`, the multiplier is A/C. All subsequent clicks/positions are in display space and must be converted before cropping.

## Working zoom levels (from f1r session)

| Task | Scale | Source size | Output size |
|------|-------|-------------|-------------|
| Full folio overview | 0.4× | 2000×2534 | 800×1013 |
| Wide page region | 0.5× | 1800×600 | 900×300 |
| Full line | 4× | 1530×35 | 6120×140 |
| Single word | 6-10× | ~120×35 | 720×210 to 1200×350 |
| Individual character | 15-20× | ~20×25 | 300×375 to 400×500 |
| Margin annotation (cluster) | 5-7× | 260×430 | 1300×2150 to 1820×3010 |

## Critical failure modes encountered

1. **Coordinate drift**: Cropping upstream of the tight text band and then applying DoG gives a result dominated by vellum noise. Fix: find text y-center first, crop ±17px.

2. **Holes dominate DoG output**: Physical damage registers as bright spots that overwhelm faint ink signal. Fix: hole masking before filtering.

3. **Too-aggressive percentile stretch**: Using (1, 99) on noisy regions creates a noise-amplification floor. Fix: use (3, 97) for character-scale, tighter only for known-high-contrast regions.

4. **Wrong DoG sigma ratio**: σ₂/σ₁ too large = dominated by low-frequency background; too small = just Gaussian blur. For pen strokes, ratio of ~8-10 works (0.5/5 or 1/10).

5. **Blue channel inversion confusion**: Iron gall ink absorbs blue, so ink shows as LOW values in the blue channel. The DoG invert `-(G1 - G2)` is where this gets handled — easy to get the sign wrong and produce inverted-contrast output.

6. **Cross-folio provenance drift**: Derived overlays and screenshots can carry labels like `rosettes`, `atlas`, `Basel`, or `spokes` while actually sitting on a different folio than the one that generated the idea. Fix: bind every derived image to an explicit catalog folio / section and treat filename semantics as non-evidence. If a rosettes-labeled overlay is attached to a non-rosettes folio, quarantine it as drift instead of reasoning from it.

## What works and what doesn't

**Works well:**
- Extracting text from low-contrast but intact regions (all f1r paragraphs)
- Character-scale pen strokes where the ink hasn't been physically removed
- Detecting the presence/absence of specific glyph shapes

**Works partially:**
- Erased margin annotations: revealed structure (letter shapes, row layout) but individual characters remained ambiguous
- Distinguishing between ink layers from different hands

**Does not work:**
- Recovering specific readable text from fully scraped vellum (would need UV/NIR multispectral)
- Extracting red ink from red-ink rubrications when they're faded (red has complex multi-channel behavior)
- Distinguishing pigment types without reference spectra

## When to use what

| Goal | Technique |
|------|-----------|
| Find text line positions | Row variance + `find_peaks` |
| Read faint-but-intact text | DoG σ₁=0.5 σ₂=5, blue channel, percentile (3,97) |
| Read erased annotations | DoG σ₁=1 σ₂=10 + hole masking + CLAHE-style, blue channel |
| Differentiate ink layers | Channel difference maps + false colour composite |
| Detect pen-stroke topology | Hessian Frobenius norm (`order=[0,2]`, `[2,0]`, `[1,1]`) |
| Separate linear marks from texture | Sobel edges + horizontal/vertical decomposition |

## Polar unwrap for circular folios

For folios with circular/radial text (f57v, zodiac folios, rosettes), row-variance line detection cannot read curved text. It must first be **polar-unwrapped** into a linear form.

### Method

1. **Find diagram center** via text-density median or weighted center of high-pass filtered ink pixels.
2. **Sample concentric circles** at each radius using `scipy.ndimage.map_coordinates`:

```python
r_coords = np.arange(max_r).reshape(-1, 1)       # rows = radius
theta = np.linspace(0, 2*np.pi, n_theta).reshape(1, -1)
theta_adj = theta - np.pi/2                       # start at 12 o'clock
xs = cx + r_coords * np.cos(theta_adj)
ys = cy + r_coords * np.sin(theta_adj)
polar = np.zeros((max_r, n_theta, 3), dtype=np.float32)
for ch in range(3):
    polar[:,:,ch] = ndimage.map_coordinates(
        arr[:,:,ch], [ys, xs], order=1, mode='constant', cval=255)
```

3. **Each ring becomes a horizontal strip** in the polar image. Apply row-variance line detection as normal on the polar image to locate rings.

4. **Angular resolution:** `n_theta / 360 ≈ 11` pixels/degree is sufficient for reading VMS text. Use 4000 columns for 360° (or higher if characters are small).

### Parameters proven on f57v

- Center: (935, 910) ± few pixels (found via text-density median)
- `max_r = 800`, `n_theta = 4000`
- Theta offset `-π/2` to start at 12 o'clock (reads naturally)
- DoG σ₁=0.8, σ₂=8 for ring text (slightly larger σ₂ than linear text because curvature introduces local context variation)

### Caveats

- **Angular wrapping:** The polar unwrap creates a discontinuity at θ=0 (12 o'clock). If a word spans the wrap point it will be split between columns 0 and `n_theta-1`. Re-run with `theta_adj = theta - π` (start at 6 o'clock) if a specific word is at the top.
- **Radial stretching:** Inner rings have fewer angular pixels per character than outer rings at the same n_theta setting. Consider sampling more angular points for outer rings if reading them at high zoom.
- **Ring-to-segment mapping is the hard part.** Visual rings don't map 1:1 to IVTFF `Cc` segments because the text follows a spiral that the transcribers broke at specific points. Matching requires character-level alignment.

## Files produced during f1r / f57v sessions

- `enhance_margin.py` — 24-output enhancement battery for the right margin scraped zone
- `enhance_margin2.py` — Round 2 with tighter parameters for upper-margin cluster
- `f1r_17segment_test.py` — 17-period structural test (separate analysis layer, not visual)

Generated enhancement outputs land in `../../../resources/tools/provenance/index.html#s-0f1887390a74e90e` and `/tmp/` during analysis; none of them are checked in.
