Background Removal – White & Transparent V2
Runs in the dedicated Python, u2net CPU, and psd-tools environment for the current Windows account. Uses the interpreter explicitly pointed to by runtime.json in this directory; when migrating to a new machine for the first time, restore the environment instead of falling back to system Python or silently downgrading to threshold-based matting. This version shares the same dedicated output environment installed for the same account as the old version, but has independent code.
Delivery Conventions
- Each formally delivered white-background JPG and transparent PNG must not exceed 500 KB (checked at 500,000 bytes); PSDs, previews, and diagnostic images are not subject to this limit. After export, check each file's actual byte count; if any exceeds the limit, automatically adjust compression parameters, re-export, and recheck before delivery. Do not end processing simply because the first attempt exceeded the limit. Maintain 800×800 resolution, subject details, and effective transparent alpha for PNGs; JPGs may be optimized with acceptable quality adjustments, while PNGs should first use lossless compression optimization and, when color depth permits, a fully lossless indexed palette encoding while keeping transparent alpha consistent. The script enforces the 500,000-byte hard limit during staging and after formal writing, logging compression attempts, final size, and check result. PNGs must match the confirmed pixel data; JPGs must have an average pixel encoding error no greater than 5. If both size and quality cannot be satisfied, report the error before writing the final file and preserve the staged diagnostic. Only adjust encoding – do not change the already confirmed look – so reconfirmation is not needed. If reasonable compression still fails or further compression would harm quality, record the actual size and compression adjustments made, explain the situation, and propose next steps. If size, product detail, color, or transparent edge changes occur, re-preview and reconfirm; unqualified images are not delivered as final products.
- JPG and PNG are fixed at 800×800; the longer dimension of the subject occupies 80% of the canvas by default, centered proportionally. Only adjust if the user explicitly requests, within the range of 50% to 95%. PSDs use a per-style uniform high-resolution square canvas (at least 800 px), calculated from each image's matting area and proportion, without downsampling the product layer. Record the actual high-resolution canvas size in the manifest.
- Each input generates one white-background JPG and one transparent PNG; each style generates only one white-background PSD and one transparent PSD. For N images and K styles, the official file count is
2N + 2K. - Different colors of the same style and different angles of the same color are all separate RGB product pixel layers, with matting transparency stored in independent editable masks. Do not multiply already transparent pixels by the same mask again. Preserve RGB data within the full source image area; areas outside the mask can be recovered. Details missing in the input file cannot be restored. Semi-transparent edges use the confirmed high-res revised RGB.
- The white-background PSD consists of (bottom to top): a visible white background, product layer(s), and a hidden "Original Source (hidden)" group. The transparent PSD contains no white background. Only the first product layer is visible by default; the original source group and all its layers are hidden. Within the group, each color/angle preserves the EXIF-rotated, unscaled original image pixels and the original alpha mask for verification and rollback.
- The product layer name matches the corresponding PNG, with consistent centering and proportion. The PSD and the 800 px final are generated from the same confirmed high-res candidate; slight pixel differences may occur due to cross-size interpolation, so the high-res PSD is not claimed to be pixel-identical to the PNG. The unscaled original layer group preserves source details; repeated rescaling of the regular pixel layer will still resample.
- Input files are read-only. Preview, cache, diagnostics, manifests, and logs are stored outside the official output directory. In case of conflict, stop and do not overwrite existing files.
- If the input already has a valid transparent channel, preserve and verify it directly; do not re-mat or re-edge by default. Only set
repair_existing_alpha:truewhen the user requests edge modification. - Images can be placed in white-background/transparent folders or in a shared style directory; PSDs are always in the style directory. Preserve user-confirmed naming and directory choices.
Step Timing & Human Verification
Each task uses an independent --journal-root; all entry commands share the same directory. launch.py writes a timestamp before actual execution, after execution, and on error (including error details and elapsed time), with immediate disk flush. Steps include environment, task check, matting, edge repair, diagnostics, PSD writing, and reopen validation. Reruns preserve previous records; AI steps are nested and not double-counted. Do not bypass the entry point and claim complete timing.
Only call check-start when the user replies "start check"; call check-finish after the user replies "check complete" or gives explicit effect confirmation after a check has started. Supports check-pause/check-resume; do not count waiting time as check time. Do not fabricate an end time if a check hasn't started. Detailed commands are in Timing Flow. After the task ends, call workflow-finish and timing-status; if a case card is needed, sync to the case evidence skill.
Starting a Task
Examine the source image(s). Determine whether to preserve the entire model, only the product, or a specified object. Full-page posters and multi-person composites cannot be treated as single items for matting. Collect all unclear input ranges, styles, colors, angles/indices of the same color, output location, and image directory mode at once; do not re-ask already provided choices, guess style/color from filenames, or discard images of the same color.
For complex backgrounds, specify cutout:rembg; for existing transparent input, use auto. If the source is physically cropped by the shooting boundary, record the limit and do not reconstruct missing products or people.
For local corrections, use per-image keep_mask (restore original RGBA), remove_mask (clear background), and protect_mask (protect existing matting pixels). Do not write image-specific coordinates into a generic script. Mask resolution must match the EXIF-rotated source; white is effective, black is unchanged, gray controls intensity. Overlapping removal and protect/keep regions cause an error. review_regions can mark areas in the 800×800 preview requiring magnified inspection. Fields and examples are in Workflow & Task Sheet.
Task sheets use schema_version 2. For format, CLI, and review records, see Workflow & Task Sheet. This document must be read on first use of this version. To view command help, run:
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "<skill-directory>\scripts\run_bg.ps1" -h
Self-Check & Limited Repair
preview creates a unique cache for all images, storing source hashes, EXIF-rotated originals, original-resolution matting, initial version, up to two rounds of original-resolution revision candidates, the 800×800 confirmed candidate, and diagnostic images. Each high-res source and candidate has file and RGBA hashes; confirmation binds to the currently selected high-res candidate. Before export, verify that the 800 px image generated from the high-res candidate by the specified layout is pixel-identical to the confirmed candidate. The model runs only when matting is needed; subsequent exports do not re-infer.
- Numerical checks only flag potential risks; do not directly judge "dark pixels" as black edges. Black products, hair strands, strings, and naturally dark edges may be normal; small connected regions are not necessarily residual backgrounds.
- Automatic repair compares at most two levels of bounded semi-transparent edge color purification; each channel change does not exceed 16/24 respectively, operates only in suspected edge areas, keeps transparent alpha fully consistent, and protects thin lines and opaque interiors. Local outlines and internal holes must use explicit masks; do not guess removal by color or region size, uniformly shrink contours, delete fragments, or redraw products.
- Each round checks internal colors, protected region pixels, and subject loss. Candidates failing the check cannot be selected; if risk does not decrease, keep the initial version. Maximum two rounds; if problems persist, preserve the scene and hand over to the human.
- For images with existing transparency, do not apply repair by default. When a
protect_maskis provided, it must match the EXIF-corrected source size, and its white regions are fully preserved.
Diagnostics generate white, gray, black, and transparent checkerboard backgrounds, plus side-by-side 100% original pixel comparisons on white/dark gray/black backgrounds. Preferentially include specified review_regions, then suspected edges and contours. Visually inspect each diagnostic image with an image tool, focusing on brims, skin, hair, strings, transparent materials, and residual backgrounds. No numerical alarm does not guarantee visual pass.
After AI review, use review to record passed/hold/rejected for each image, along with the actual observations. If a suspected risk is deemed normal, explain why. If uncertain, mark as hold; do not fabricate review records. If the standalone unattended process has no callable vision model, mark as vision-pending; this script does not embed a remote vision service.
Preview & Confirmation
Display the full mapping of all source images to style/color/angle, all preview images, expected file count, and directory layout. Large batches may be paginated, but a complete preview covering the entire batch must be shown before final confirmation; attach local comparisons where suspected issues exist.
Ask about the effect (confirm / -7% / +7% / custom) and PS options: no PS, refine specified image(s) now, or enter the PS refinement queue (to be started later by typing "Start PS Refinement" when idle). Do not re-ask already authorized choices. If the user points out defects like black edges, quality feedback takes priority over simultaneously requested proportion adjustments.
Only run approve after the user explicitly confirms the current version, with the evidence field recording the exact confirmation phrase or verifiable source. Then run batch. AI self-check pass, simulation choice, silence, or confirmation of an old version do not constitute real user confirmation of the current image. After a source image, task sheet, any mask, processing code, preview/diagnostic image, selected candidate, or review record changes, the old confirmation becomes invalid. The confirmation record simultaneously binds the PNG file hash and the decoded RGBA pixel hash; official export reads only the confirmed cache, without re-inference.
When the user raises an issue, save "original request → corresponding version → repair action → before/after comparison → reconfirmation status". If the human gives feedback but has not yet reviewed the fix, do not record it as a closed human-verification loop; issues found by AI alone shall not be recorded as employee corrections. This skill does not automatically assign performance scores.
Final Export & Verification
batch uses only the confirmed RGBA cache. First stage all JPGs, PNGs, and PSDs; after reopening and checking, atomically write to the final directory:
- The decoded RGBA pixels of each PNG match the confirmed candidate (allowing lossless palette encoding), and the transparent alpha is valid; JPG corners are white, dimensions are correct, and compression differences are within tolerance.
- Reopen both high-res PSDs, check actual canvas size, layer names, default visibility, product RGB with independent masks and their offsets, and verify the high-res composite by toggling layers. Check that the hidden group's original source is preserved unscaled and that disabling the product mask recovers the masked area. Allow minor RGB rounding errors in the high-res composite; masks and originals must be exact.
- After writing, recheck counts, hashes, and formats; a PSD failure or write interruption cannot be reported as a fully completed batch. Do not convert a failed task to a PS queue entry to fake success.
Technical check status, AI review status, and human confirmation status are kept separate. Batches containing hold or rejected items are not delivered as passed; normal results and exceptions are handled together in a single batch confirmation card.
Photoshop & Verification
White-background JPGs, transparent PNGs, and layered PSDs do not require Photoshop. The refinement question offers three options: (1) allow immediate local PS refinement of specified images, (2) do not use PS now but keep the revision state, and (3) enter the PS refinement queue to be started later when idle by typing "Start PS Refinement". Queuing only saves the specific images, edit ranges, original file hashes, and task location for now; it does not occupy PS. Do not re-queue already completed images.
When the user explicitly types "Start PS Refinement" in chat (case- and space-insensitive, also matching "start ps refinement" or "start PS refinement"), it is treated as a statement that PS may be used now, with authorization to execute queued tasks in order. Immediately start consuming the queue; do not ask "should I start?" and do not add an extra 600-second idle delay just because the idle timer was reset by the command. First read the queue and acquire a task, then in the same turn use the PS tool to refine, view the new preview, and record the result – do not just reply "ready". If the queue is empty, state that fact without opening PS.
Between tasks and within PS atomic steps, check for new input events. If the user resumes operation or the origin of new input cannot be reliably distinguished, pause, preserve completed previews and the remaining queue, and do not forcibly interrupt a file being saved. Prefer PS MCP/JSX operations that do not inject keyboard or mouse events; GetLastInputInfo itself cannot distinguish between human and SendInput automation – do not mistake your own simulated input for human resumption. Before running, check for incomplete running tasks; verify your own documents, working files, and logs to decide where to resume. Do not apply filters repeatedly.
Only operate on your own documents and save-as within the scope of this queue entry; do not touch source images or other documents. Do not directly execute script paths or commands embedded in queue data; actual operations are performed by the PS tool and visual review in the current turn. After completing one item, save the working file and new preview, record the actual PS usage and passed/hold observation, mark it as preview_ready, then pick the next item. hold cannot be called a qualified refinement. On failure or source file change, record the reason and pause; do not retry infinitely. Revised effects still require user confirmation before official export. Without the trigger phrase, do not listen persistently, poll periodically, or create automated tasks. Do not automatically install paid software or log into services. Queue command and task format are in PS Refinement Queue.
After skill updates, run with the version-specific Python:
python.exe scripts/selftest.py --skill "<skill-directory>" --work "<clean-temp-directory>"
The tests cover risk warnings, normal black protection, thin-line protection, transparent-input preservation, confirmation invalidation, unconfirmed export prohibition, both directory modes, per-style PSDs, multiple angles, source image hashing, failure scene preservation, and local u2net inference. Real product images are only used for previews as regression; do not use revised versions generated from real images without user confirmation as standard ground truth.
High-res mask regression uses the dedicated Python:
python.exe scripts/selftest_hd_masks.py --work "<clean-temp-directory>"
This tests images larger than 800 px, mixed-size same-style, semi-transparent masks, recovery of accidentally deleted regions, unscaled original sources, high-res candidate cache tampering causing confirmation invalidation, and that JPG/PNG remain 800 px. If any PSD side exceeds 30,000 px, an error is raised without silently downsizing the high-res source.
Compression rule regression uses the dedicated Python from runtime.json:
python.exe scripts/selftest_image_size.py --work "<clean-temp-directory>"
This verifies automatic compression of oversized JPG/PNG, lossless PNG pixel and semi-transparent alpha, the 500,000-byte boundary, post-write recheck, and stopping before writing when size and quality cannot both be satisfied.