Photoshot Retouch development journal · 04

Vibe coding Photoshot Retouch, Part 4 — An engine and layer format that preserve the original

Vibe coding an editable retouch starts with deciding what the code may change. In this episode of Photoshot Retouch, the engine turns an ordered tool request into RGB patches and masks that can be placed over the original photo.

Run the same checkpoint

Unzip the lab and open PowerShell in its lab folder. The verified environment is Windows x64, Python 3.10.6, NumPy 2.2.6 and OpenCV 5.0.0. Node is unnecessary for this run.

py -3.10 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-lock.txt
.\.venv\Scripts\python.exe finished\reproduce_engine.py

The script generates four 24 × 16 PNG inputs, paired masks, and a 1,600 × 900 proxy test. Expect verification/engine-checks.json, the layer manifests and binary assets, and two reconstructed PNGs per input. The three-pixel prediction exercise is in start/predict.txt. The frozen branch of the exercise is under finished/. Download the lab · Measurements and runtime notes

1. Define exactly what enters the engine

Part 3 selected where retouching could reach using landmarks and masks. Part 4 carries that shared analysis into the image engine. Follow service/api.py from validate(), upload() and commit() to the worker in service/jobs.py, then read service/engine.py · process() and inspect result() and asset() for the return path. Series introduction and checklist source

Retouch4me documents a layered ZIP with editable outputs and blend instructions. That observable behavior informed the series checklist. This chapter follows existing items 52, 53, 55 and 56 for order, separate patches, merged output and blending. The Photoshot source and experiments below establish its own behavior. Retouch4me layer examples

FieldContract
Dimensions and orderInterleaved row-major height × width × channels, with RGB or RGBA. A job accepts 16 to 12,000 pixels per dimension and at most 18 megapixels. Supply an ordered list of unique tools and request layers or merged.
RGB sample values8-bit unsigned or 16-bit little-endian unsigned, normalized to float32 in [0,1]. The API accepts raw bytes. The Photoshop capture code requests sRGB and full-range samples. The engine declares sRGB IEC61966-2.1 in the manifest and expects its caller to supply pixels in that space.
Alpha protects the sourceWith RGBA, alpha == maximum marks pixels eligible for correction. Alpha zero and partially transparent pixels both receive zero mask. An RGB patch carries no alpha channel, so replay leaves the base image's alpha in place.

2. Analyze a smaller image and apply a full-size correction

Analysis starts with an original-image proxy. The long edge is capped at 1,400 and smaller images are used at their existing size. For a proxy tool, process() downsamples the current RGB with OpenCV area resampling. It restores the difference between candidate and input, and the mask, with linear interpolation. Think of the difference as an instruction to change the original-sized pixel by a certain amount.

Eye Vessels, Eye Brilliance, Fabric, Stray Hairs and Glasses Glare compute their corrections at the source resolution while sharing the proxy analysis. Behind the scenes each tool reads the result of applying the previous visible correction.

52 · Run the selected tools in order

  1. Inputservice/api.py · validate()
    Ordered tools, validated settings and interleaved source samples
  2. Processingservice/engine.py · process()
    Analyze the source proxy. Give each operation the latest current image at its working resolution.
  3. Outputservice/engine.py · process()
    Updated full-resolution current; the next tool reads it.
OpenCV provides downsampling and interpolation. Photoshot decides which operations receive the original-resolution image.
native_detail = key in {"eyeVessels", "eyeBrilliance", "fabric", "strayHairs", "glassesGlare"}
base = current if native_detail else small(current)
# In the correction branch
candidate, small_mask = spec["operation"](base, region, settings)
delta = candidate - base if native_detail else full(candidate - base)
mask = np.clip(small_mask if native_detail else full(small_mask), 0, 1)

Predict one pixel before running it

Take an 8-bit channel with a current value of 80 and an encoded patch value of 120. The rule is current + (patch − current) × mask. At full mask the result is 120. For mask 0.5, the engine stores byte 128, then uses 128/255, yielding about 100.08 before the final round to 100. A zero mask yields 80. The lab asserts all three values.

56 · Blend the correction with the original

  1. Inputservice/engine.py · process()
    candidate - base, a float mask and the fully opaque pixel map
  2. Processingservice/engine.py · full() / encode()
    Restore source dimensions, clear protected pixels, round patch and mask to wire precision, then blend.
  3. Outputservice/engine.py · process()
    Source-sized updated RGB. plugin/photoshop.js · apply() requests Normal layers.
In this engine, the mask is the weight in a Normal blend. A mask value of zero leaves the current pixel unchanged.
if opaque is not None:
    mask *= opaque
mask *= np.max(np.abs(delta), axis=2) >= 0.002
mask = encode(mask, 8).astype(np.float32) / 255
patch = encode(current + delta, depth).astype(np.float32) / maximum
# After recording the layer, if a mask remains
current += (patch - current) * mask[..., None]

3. Return enough information to rebuild the layers

The manifest contains its version, image dimensions, bit depth, sRGB profile, operation summaries and layer list. Each patch has an asset ID, tool, label, group, x, y, width, height, Normal blending and visibility. It carries three packed RGB samples per crop pixel at the job depth and one 8-bit mask byte per crop pixel at either depth. A correction with an empty mask is skipped.

53 · Return each visible correction as a patch

  1. Inputservice/engine.py · process()
    Correction RGB and mask in source coordinates
  2. Processingservice/engine.py · record()
    OpenCV findNonZero() and boundingRect() find the crop.
  3. Outputservice/api.py · result() / asset()
    Versioned position and size, plus packed RGB and an 8-bit mask. plugin/photoshop.js · paint() offsets both by the source bounds.
The Skin Mask shares the format and is emitted with visible set to false. In the editor the RGB crop and its user mask share the same placement.
points = cv.findNonZero(np.uint8(mask >= 1 / 255))
if points is None:
    return False
x, y, w, h = cv.boundingRect(points)
region_slice = np.s_[y:y+h, x:x+w]

With layers, each applied correction gets a visible layer. With merged, the engine compares final encoded RGB with the source and emits a single visible correction wherever they differ. Either path can also return a hidden Skin Mask utility. Hiding this layer keeps it out of the rendered reconstruction.

55 · Return an accumulated correction

  1. Inputservice/engine.py · process()
    The last full-resolution current image and original encoded RGB
  2. Processingservice/engine.py · encode() / record()
    Compare encoded channels, create a binary change mask and crop the changed area.
  3. Outputservice/api.py · result() / asset()
    One visible merged correction where final RGB changed. A requested hidden Skin Mask is a separate utility.
The replay reads saved assets, skips hidden layers, applies Normal blending in manifest order and compares final integer codes.
if job["output"] == "merged":
    changes = np.any(encode(current, depth) != raw[..., :3], axis=2).astype(np.float32)
    record("merged", "Merged Retouch", "보정", current, changes)

The editor integration requests sRGB with imaging.getPixels(). Its apply path places the pixel crop with putPixels() and the user mask with putLayerMask(), using the same offset. These calls were traced in plugin/photoshop.js. Adobe Photoshop Imaging API

4. Check the files and pixels you can measure

Local checkObserved
8- and 16-bit RGB/RGBAAll four fixtures reconstructed from layered and merged assets with a maximum difference of 0 final integer codes. The lab allows up to one code for this round trip.
Mask placement and alphaThe small crop was x=4, y=3, width=6, height=5. It held 30 active pixels for RGB and 28 for RGBA. The fully transparent and partially transparent samples were unchanged, as were pixels outside the crop. Each original input remained byte-for-byte intact.
Proxy and detailA 1,600 × 900 source used a 1,400 × 788 analysis image. The five detail branches still received 1,600 × 900 RGB. The large proxy patch was placed at x=308, y=113 with a 218 × 59 crop.
Empty and hidden outputsMask zero and a delta below 0.002 yielded zero patches in their trials. A Skin Mask-only job created one hidden utility layer and left the visible image intact.
Real worker and existing testsThe repo's 127 Python tests passed. A local API smoke test submitted 14 actual tools on the NASA astronaut sample and got 12 layers. A separate 16-bit RGBA Dust request returned a merged layer below the half-transparent region, and a zero-strength request returned no corrections.
Synthetic gray RGBA input with two protected pixels
Source with partial and zero alpha
White six-by-five patch rectangle on a black background
Expected affected region
Reconstructed image with a slightly darker correction over its source
Replayed merged result

The controlled inputs substitute deterministic tool operations to isolate the engine contract. The local API test runs the actual operations and checks the response contract. The measurements here cover the Python engine, binary assets and loopback API. Photoshop PSD save, reopen and Undo are editor release checks with their own evidence.

OpenCV supplies interpolation and the crop. NumPy supplies data types, masks and rounding. MediaPipe supplies the shared analysis interface discussed in Part 3. The Photoshot engine joins these pieces with its own patch format and sequencing. OpenCV source · NumPy source · MediaPipe source

Part 5 follows the Heal tool and asks how it can distinguish a red blemish from a darker spot.