Improve edge-aware thin-feature fidelity
This commit is contained in:
parent
a61a160d09
commit
c9c51d5f27
8 changed files with 440 additions and 102 deletions
|
|
@ -21,7 +21,7 @@ Implemented:
|
|||
|
||||
Verified:
|
||||
- local editable install in a dedicated venv
|
||||
- full test suite currently passing
|
||||
- full test suite currently passing on the last completed pass
|
||||
- compare-mode smoke run against a real emblem image
|
||||
- focused real-fixture probe on `tests/fixtures/real/ai-badge-cleaned.png` now beats naive resize on source-lattice consistency under the selected lattice (`0.0832` final vs `0.1304` naive with the current `126x126` / `(0.0, -0.2)` pick)
|
||||
|
||||
|
|
@ -38,7 +38,7 @@ What that fixed:
|
|||
- the solver no longer regresses relative to its own snap stage on the added thin-feature regression case
|
||||
|
||||
What is still provisional:
|
||||
- the cleaned badge still lands on the conservative `126x126` lattice candidate, just with a much lower confidence than before; that means candidate selection and weight tuning are improved but not “done”
|
||||
- the cleaned badge still lands on the conservative `126x126` lattice candidate, just with a much lower confidence than before; that means candidate selection and weight tuning are improved but not "done"
|
||||
- tuning has not been rerun yet against the new source-first hyperparameters, so the benchmark/tuning baseline should be treated as stale until the next sweep
|
||||
- the baked-checkerboard version of the badge remains a separate background-suppression problem
|
||||
|
||||
|
|
@ -48,12 +48,25 @@ The current implementation should be treated as a strong experimental baseline,
|
|||
|
||||
The most provisional areas are:
|
||||
- lattice inference on real, messy generated imagery
|
||||
- the exact loss weighting in the continuous stage
|
||||
- the strength and shape of discrete cleanup heuristics
|
||||
- edge-cell reliability and candidate coverage in the continuous stage
|
||||
- low-confidence reranking once multiple plausible lattice sizes survive the new soft penalty
|
||||
- compare-mode metrics as a proxy for actual visual quality
|
||||
|
||||
## Near-term priorities
|
||||
|
||||
### Active pass
|
||||
|
||||
This is the next solver-focused pass after the adjacency-first rewrite.
|
||||
|
||||
In scope now:
|
||||
- make source reliability edge-aware instead of dispersion-only so high-contrast thin features are not downweighted just because they are locally messy
|
||||
- expand snap/refine candidate generation beyond fixed offset grids by injecting sharp per-cell exemplars, edge peaks, and gradient-guided offsets
|
||||
|
||||
Next after that:
|
||||
- rerank low-confidence top lattice candidates with short real solver probes instead of relying only on the cheapest preview
|
||||
- rerun tuning after the edge-aware/source-guided behavior lands
|
||||
- evaluate coordinated local moves when single-cell refinement still breaks thin contours
|
||||
|
||||
## High-value regression cases
|
||||
|
||||
### AI badge emblem with baked checkerboard background
|
||||
|
|
@ -72,10 +85,10 @@ Current failure modes:
|
|||
- the right-hand guard wing loses short dark-light-dark adjacency motifs and collapses into a chunky gold slab
|
||||
- some guard closeups look nearly identical across `snap`, `relaxed`, and `final`, which suggests the wrong local motif is often chosen before later refinement even starts
|
||||
|
||||
Current status after this pass:
|
||||
Current status after the adjacency-first pass:
|
||||
- on the cleaned fixture, `snap`, `relaxed`, and `final` now all preserve source-lattice structure substantially better than the old baseline, with `final` currently landing at `0.0832` source-fidelity score in the reproducible probe under `artifacts/badge-final-probe/`
|
||||
- that is a meaningful improvement over both the previous documented `0.1494` final score and the naive resize score under the same selected lattice
|
||||
- the remaining weakness is candidate choice confidence, not a collapse inside the snap/refine handoff
|
||||
- the remaining weakness is edge-cell trust and candidate coverage, not the old snap/refine handoff collapse
|
||||
|
||||
Important note:
|
||||
- the checkerboard is baked into the source image, not transparency
|
||||
|
|
@ -84,21 +97,18 @@ Important note:
|
|||
- it is still a problem, because the background is treated as real source structure and can contaminate local scoring near the blade
|
||||
|
||||
What future work should improve here:
|
||||
- better weighting of thin local outline/motif preservation relative to high-contrast cell transitions
|
||||
- edge-aware source reliability so high-dispersion but high-contrast cells keep trusting source evidence
|
||||
- richer candidate generation so snap/refine can reach sharp exemplars, cell edge peaks, and gradient-guided offsets instead of only a fixed local grid
|
||||
- short top-k refine probes for low-confidence lattice candidates before the final rerank decision
|
||||
- a retuning sweep after the edge-aware/source-guided changes land
|
||||
- some form of coordinated local relaxation so nearby cells can move together toward a globally better contour
|
||||
- optional background suppression or de-weighting when a baked checkerboard is clearly not semantic content
|
||||
|
||||
Current optimizer diagnosis:
|
||||
- a lot of the so-called `source_*` terms in the solver are still measured against the smoothed representative lattice, not raw source-side candidate evidence
|
||||
- that means the optimizer often "preserves" a softened, already-collapsed interpretation of the source instead of the sharper local adjacency patterns we actually care about
|
||||
- snap is still especially guilty here: its base match and neighbor deltas are dominated by the representative lattice, so the wrong local motif can be locked in before relaxation or hard refinement even starts
|
||||
- relaxation can often descend to a much lower expected energy basin, but the hardening/refine handoff then projects that soft solution back into a worse discrete assignment
|
||||
- diagonal structure is also underrepresented in the final structure score, which is a bad fit for curved one-pixel outlines and hooks
|
||||
|
||||
Most likely next fixes:
|
||||
- rerun tuning so the new source-first weights are benchmarked against the corpus instead of being judged only by defaults
|
||||
- keep pressure on low-confidence badge-like cases where larger lattice candidates have better support but still lose on the combined rerank score
|
||||
- evaluate whether the compare-mode summary should surface per-stage source-fidelity directly, not only the final output metrics
|
||||
- the shared source-lattice reference, source-first snap/refine scoring, and relaxed-mode handoff are now in place, so the biggest remaining losses are no longer caused by the old representative-lattice collapse
|
||||
- the current weak spot is that difficult thin features often live in high-dispersion cells, which still makes the solver partially distrust the source exactly where the contrast is most informative
|
||||
- candidate search is also still too centered on the regular UV neighborhood; if the right edge pixel never enters the candidate set, the solver can preserve the wrong motif very consistently
|
||||
- low-confidence reranking is softer than before, but it still relies on cheap probes, so larger lattice candidates can remain underexplored even when they support thin contours better
|
||||
|
||||
Repository fixtures:
|
||||
- `tests/fixtures/real/ai-badge-cleaned.png` is the manually cleaned transparent version of the same emblem
|
||||
|
|
@ -129,15 +139,15 @@ Next improvements should focus on:
|
|||
- stronger penalties against oversized candidate grids
|
||||
- confidence calibration that reflects ambiguity more honestly
|
||||
|
||||
### 3. Strengthen the discrete cleanup stage
|
||||
### 3. Improve edge-cell reconstruction
|
||||
|
||||
Current cleanup is local and generic.
|
||||
The next quality gap is no longer generic cleanup; it is preserving thin, high-contrast local structure.
|
||||
|
||||
Next version should add:
|
||||
- stronger outline continuity rules
|
||||
- better preservation of highlight bands
|
||||
- better handling of metallic or gem-like materials
|
||||
- smarter alpha-edge cleanup for transparent icons
|
||||
- edge-aware source reliability overrides for thin outlines and hard transitions
|
||||
- source-guided candidate pools that are not limited to a uniform local offset lattice
|
||||
- richer diagnostics for which candidate families win on real fixtures
|
||||
- later, coordinated block or contour moves when single-cell greedy updates still break lines
|
||||
|
||||
### 4. Make compare mode more trustworthy
|
||||
|
||||
|
|
@ -159,15 +169,15 @@ Next work should:
|
|||
|
||||
### Milestone 2: Solver tuning pass
|
||||
|
||||
- tune continuous-stage loss weights against the benchmark corpus
|
||||
- test more robust anti-speckle and cluster-preservation behavior
|
||||
- reduce cases where the solver underperforms the naive baseline
|
||||
- tune continuous-stage loss weights against the benchmark corpus after the edge-aware/candidate-guided pass lands
|
||||
- test more robust thin-feature and contour preservation behavior
|
||||
- reduce cases where the solver still underperforms the naive baseline or settles on the wrong low-confidence lattice
|
||||
|
||||
### Milestone 3: Better cleanup heuristics
|
||||
### Milestone 3: Coordinated contour moves
|
||||
|
||||
- add contour-aware cleanup
|
||||
- add material-sensitive smoothing for highlights and trim
|
||||
- reduce the number of visually good-but-metric-weak outputs
|
||||
- add contour-aware multi-cell refinement moves
|
||||
- protect short dark-light-dark edge motifs during block updates
|
||||
- reduce cases where locally correct cells still fail to form a globally smooth outline
|
||||
|
||||
### Milestone 4: Human-in-the-loop v2 planning
|
||||
|
||||
|
|
|
|||
|
|
@ -6,12 +6,17 @@ from pathlib import Path
|
|||
import numpy as np
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from repixelizer.analysis import analyze_source
|
||||
from repixelizer.continuous import (
|
||||
_build_candidate_positions,
|
||||
_discrete_refine_output,
|
||||
_build_source_reliability,
|
||||
_cluster_boundary_map,
|
||||
_edge_gradient_maps,
|
||||
_make_patch_offsets,
|
||||
_make_regular_uv,
|
||||
_relax_candidate_selection,
|
||||
_reference_match_energy,
|
||||
_representative_colors,
|
||||
_require_torch,
|
||||
_resolve_device,
|
||||
|
|
@ -92,6 +97,7 @@ def _build_focus_states(
|
|||
source = load_rgba(input_path)
|
||||
solver_params = SolverHyperParams()
|
||||
inference = infer_lattice(source, None, device=device)
|
||||
analysis = analyze_source(source, seed=7)
|
||||
|
||||
torch, F = _require_torch()
|
||||
resolved_device = _resolve_device(torch, device)
|
||||
|
|
@ -113,6 +119,8 @@ def _build_focus_states(
|
|||
offsets_t = torch.from_numpy(
|
||||
_make_patch_offsets(height=height, width=width, target_height=inference.target_height, target_width=inference.target_width)
|
||||
).to(device=resolved_device, dtype=torch.float32)
|
||||
edge = np.maximum(analysis.edge_map, _cluster_boundary_map(analysis.cluster_map))
|
||||
edge_grad_x, edge_grad_y = _edge_gradient_maps(edge)
|
||||
source_lattice_reference = build_source_lattice_reference(
|
||||
source,
|
||||
target_width=inference.target_width,
|
||||
|
|
@ -120,6 +128,9 @@ def _build_focus_states(
|
|||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
alpha_threshold=solver_params.alpha_transparent_threshold,
|
||||
edge_hint=edge,
|
||||
edge_grad_x_hint=edge_grad_x,
|
||||
edge_grad_y_hint=edge_grad_y,
|
||||
)
|
||||
initial_patches = _sample_cell_patches(F, source_t, uv0_t, offsets_t)
|
||||
representative_t, _ = _representative_colors(initial_patches, solver_params)
|
||||
|
|
@ -128,7 +139,7 @@ def _build_focus_states(
|
|||
device=resolved_device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
source_reliability_t = torch.from_numpy(_build_source_reliability(source_lattice_reference)[None, ...]).to(
|
||||
source_reliability_t = torch.from_numpy(_build_source_reliability(source_lattice_reference, solver_params)[None, ...]).to(
|
||||
device=resolved_device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
|
|
@ -160,6 +171,7 @@ def _build_focus_states(
|
|||
representative_t,
|
||||
source_reference_t,
|
||||
source_reliability_t,
|
||||
source_lattice_reference,
|
||||
solver_params,
|
||||
cell_x=cell_x,
|
||||
cell_y=cell_y,
|
||||
|
|
@ -180,33 +192,34 @@ def _build_focus_states(
|
|||
if candidate_levels % 2 == 0:
|
||||
candidate_levels += 1
|
||||
candidate_extent = max(0.05, float(solver_params.refine_candidate_extent))
|
||||
fractions = torch.tensor(
|
||||
np.linspace(-candidate_extent, candidate_extent, candidate_levels, dtype=np.float32),
|
||||
device=uv.device,
|
||||
dtype=uv.dtype,
|
||||
fraction_values = np.linspace(-candidate_extent, candidate_extent, candidate_levels, dtype=np.float32)
|
||||
candidate_x, candidate_y, candidate_offset_x, candidate_offset_y = _build_candidate_positions(
|
||||
torch,
|
||||
uv,
|
||||
source_lattice_reference,
|
||||
solver_params,
|
||||
width=width,
|
||||
height=height,
|
||||
cell_x=cell_x,
|
||||
cell_y=cell_y,
|
||||
base_fraction_values=fraction_values,
|
||||
)
|
||||
offset_y, offset_x = torch.meshgrid(fractions, fractions, indexing="ij")
|
||||
offset_x = (offset_x.reshape(-1) * cell_x).to(dtype=uv.dtype)
|
||||
offset_y = (offset_y.reshape(-1) * cell_y).to(dtype=uv.dtype)
|
||||
|
||||
xs = (uv[..., 0] + 1.0) * 0.5 * max(1.0, float(width - 1))
|
||||
ys = (uv[..., 1] + 1.0) * 0.5 * max(1.0, float(height - 1))
|
||||
candidate_x = torch.round(xs[..., None] + offset_x).clamp(0, max(0, width - 1)).to(dtype=torch.long)
|
||||
candidate_y = torch.round(ys[..., None] + offset_y).clamp(0, max(0, height - 1)).to(dtype=torch.long)
|
||||
candidate_colors = source_hw[candidate_y, candidate_x]
|
||||
anchor_energy = (candidate_colors - anchor[..., None, :]).abs().mean(dim=-1)
|
||||
rep_energy = (candidate_colors - representative[..., None, :]).abs().mean(dim=-1)
|
||||
source_reference_energy = (candidate_colors - source_reference_t[0][..., None, :]).abs().mean(dim=-1)
|
||||
alpha_energy = (candidate_colors[..., 3] - anchor[..., None, 3]).abs()
|
||||
distance_energy = ((offset_x / max(cell_x, 1e-4)) ** 2 + (offset_y / max(cell_y, 1e-4)) ** 2).reshape(1, 1, -1)
|
||||
distance_energy = (candidate_offset_x / max(cell_x, 1e-4)).square() + (candidate_offset_y / max(cell_y, 1e-4)).square()
|
||||
match_energy = _reference_match_energy(
|
||||
rep_energy,
|
||||
source_reference_energy,
|
||||
source_reliability_t[0],
|
||||
representative_weight=solver_params.refine_representative_match_weight,
|
||||
source_weight=solver_params.refine_source_match_weight,
|
||||
)
|
||||
relax_base_energy = (
|
||||
anchor_energy * solver_params.refine_anchor_weight * solver_params.relax_anchor_scale
|
||||
+ (
|
||||
source_reference_energy * solver_params.refine_source_match_weight
|
||||
+ rep_energy * solver_params.refine_representative_match_weight
|
||||
)
|
||||
/ max(solver_params.refine_source_match_weight + solver_params.refine_representative_match_weight, 1e-4)
|
||||
* solver_params.refine_representative_weight
|
||||
+ match_energy * solver_params.refine_representative_weight
|
||||
+ alpha_energy * solver_params.refine_alpha_weight
|
||||
+ distance_energy * solver_params.refine_distance_weight
|
||||
)
|
||||
|
|
@ -248,6 +261,7 @@ def _build_focus_states(
|
|||
representative_t,
|
||||
source_reference_t,
|
||||
source_reliability_t,
|
||||
source_lattice_reference,
|
||||
snap_t,
|
||||
source_delta_x_t,
|
||||
source_delta_y_t,
|
||||
|
|
@ -258,32 +272,34 @@ def _build_focus_states(
|
|||
cell_y=cell_y,
|
||||
iterations=steps,
|
||||
)
|
||||
fidelity = {
|
||||
"snap": source_lattice_consistency_breakdown(
|
||||
source,
|
||||
snap_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
),
|
||||
"relaxed": source_lattice_consistency_breakdown(
|
||||
source,
|
||||
relaxed_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
),
|
||||
"final": source_lattice_consistency_breakdown(
|
||||
source,
|
||||
final_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
),
|
||||
}
|
||||
fidelity = {}
|
||||
fidelity["snap"] = source_lattice_consistency_breakdown(
|
||||
source,
|
||||
snap_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
)
|
||||
fidelity["relaxed"] = source_lattice_consistency_breakdown(
|
||||
source,
|
||||
relaxed_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
)
|
||||
fidelity["final"] = source_lattice_consistency_breakdown(
|
||||
source,
|
||||
final_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
)
|
||||
if fidelity["final"]["score"] > fidelity["snap"]["score"] + 1e-6:
|
||||
final_rgba = snap_rgba
|
||||
fidelity["final"] = fidelity["snap"]
|
||||
return source, snap_rgba, relaxed_rgba, final_rgba, (cell_x, cell_y), fidelity
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from __future__ import annotations
|
|||
import numpy as np
|
||||
|
||||
from .io import premultiply, unpremultiply
|
||||
from .metrics import source_lattice_consistency_breakdown
|
||||
from .params import SolverHyperParams
|
||||
from .source_reference import build_source_lattice_reference
|
||||
from .types import InferenceResult, SolverArtifacts, SourceAnalysis
|
||||
|
|
@ -53,6 +54,20 @@ def _cluster_boundary_map(cluster_map: np.ndarray) -> np.ndarray:
|
|||
return boundary
|
||||
|
||||
|
||||
def _edge_gradient_maps(edge_map: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
||||
grad_x = np.zeros_like(edge_map, dtype=np.float32)
|
||||
grad_y = np.zeros_like(edge_map, dtype=np.float32)
|
||||
if edge_map.shape[1] > 1:
|
||||
grad_x[:, 1:-1] = (edge_map[:, 2:] - edge_map[:, :-2]) * 0.5
|
||||
grad_x[:, 0] = edge_map[:, 1] - edge_map[:, 0]
|
||||
grad_x[:, -1] = edge_map[:, -1] - edge_map[:, -2]
|
||||
if edge_map.shape[0] > 1:
|
||||
grad_y[1:-1, :] = (edge_map[2:, :] - edge_map[:-2, :]) * 0.5
|
||||
grad_y[0, :] = edge_map[1, :] - edge_map[0, :]
|
||||
grad_y[-1, :] = edge_map[-1, :] - edge_map[-2, :]
|
||||
return grad_x.astype(np.float32), grad_y.astype(np.float32)
|
||||
|
||||
|
||||
def _make_patch_offsets(height: int, width: int, target_height: int, target_width: int) -> np.ndarray:
|
||||
cell_x = width / max(1, target_width)
|
||||
cell_y = height / max(1, target_height)
|
||||
|
|
@ -316,14 +331,95 @@ def _blend_reference_delta(primary_delta, secondary_delta, secondary_weight: flo
|
|||
return primary_delta * primary_weight + secondary_delta * secondary_weight
|
||||
|
||||
|
||||
def _build_source_reliability(reference) -> np.ndarray:
|
||||
def _build_source_reliability(reference, solver_params: SolverHyperParams) -> np.ndarray:
|
||||
baseline_dispersion = max(reference.dispersion, 1e-4)
|
||||
dispersion_scale = reference.cell_dispersion / baseline_dispersion
|
||||
dispersion_confidence = np.exp(-np.maximum(0.0, dispersion_scale - 1.0))
|
||||
support_confidence = np.clip(reference.cell_support, 0.0, 1.0)
|
||||
alpha_confidence = np.clip(np.maximum(reference.cell_alpha_max, reference.sharp_rgba[..., 3]), 0.0, 1.0)
|
||||
edge_confidence = np.clip(reference.edge_strength * solver_params.source_edge_reliability_gain, 0.0, 1.0)
|
||||
dispersion_confidence = np.maximum(dispersion_confidence, edge_confidence * 0.9)
|
||||
reliability = np.clip(0.2 + support_confidence * 0.5 + alpha_confidence * 0.3, 0.0, 1.0)
|
||||
return (reliability * dispersion_confidence).astype(np.float32)
|
||||
edge_override = np.clip(
|
||||
solver_params.source_edge_reliability_floor + edge_confidence * (1.0 - solver_params.source_edge_reliability_floor),
|
||||
0.0,
|
||||
1.0,
|
||||
) * np.clip(
|
||||
solver_params.source_edge_alpha_floor + alpha_confidence * (1.0 - solver_params.source_edge_alpha_floor),
|
||||
0.0,
|
||||
1.0,
|
||||
)
|
||||
return np.maximum(reliability * dispersion_confidence, edge_override).astype(np.float32)
|
||||
|
||||
|
||||
def _build_candidate_positions(
|
||||
torch,
|
||||
uv,
|
||||
source_reference,
|
||||
solver_params: SolverHyperParams,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
cell_x: float,
|
||||
cell_y: float,
|
||||
base_fraction_values: np.ndarray,
|
||||
):
|
||||
xs = (uv[..., 0] + 1.0) * 0.5 * max(1.0, float(width - 1))
|
||||
ys = (uv[..., 1] + 1.0) * 0.5 * max(1.0, float(height - 1))
|
||||
|
||||
candidates_x = []
|
||||
candidates_y = []
|
||||
|
||||
fractions = torch.tensor(base_fraction_values, device=uv.device, dtype=uv.dtype)
|
||||
offset_y, offset_x = torch.meshgrid(fractions, fractions, indexing="ij")
|
||||
offset_x = (offset_x.reshape(1, 1, -1) * cell_x).to(dtype=uv.dtype)
|
||||
offset_y = (offset_y.reshape(1, 1, -1) * cell_y).to(dtype=uv.dtype)
|
||||
candidates_x.append(torch.round(xs[..., None] + offset_x))
|
||||
candidates_y.append(torch.round(ys[..., None] + offset_y))
|
||||
|
||||
sharp_x = torch.from_numpy(source_reference.sharp_x).to(device=uv.device, dtype=uv.dtype)
|
||||
sharp_y = torch.from_numpy(source_reference.sharp_y).to(device=uv.device, dtype=uv.dtype)
|
||||
edge_peak_x = torch.from_numpy(source_reference.edge_peak_x).to(device=uv.device, dtype=uv.dtype)
|
||||
edge_peak_y = torch.from_numpy(source_reference.edge_peak_y).to(device=uv.device, dtype=uv.dtype)
|
||||
edge_strength = torch.from_numpy(source_reference.edge_strength).to(device=uv.device, dtype=uv.dtype)
|
||||
edge_grad_x = torch.from_numpy(source_reference.edge_grad_x).to(device=uv.device, dtype=uv.dtype)
|
||||
edge_grad_y = torch.from_numpy(source_reference.edge_grad_y).to(device=uv.device, dtype=uv.dtype)
|
||||
grad_norm = (edge_grad_x.square() + edge_grad_y.square()).sqrt()
|
||||
valid_grad = grad_norm > 1e-4
|
||||
unit_grad_x = torch.where(valid_grad, edge_grad_x / grad_norm.clamp_min(1e-4), torch.zeros_like(edge_grad_x))
|
||||
unit_grad_y = torch.where(valid_grad, edge_grad_y / grad_norm.clamp_min(1e-4), torch.zeros_like(edge_grad_y))
|
||||
|
||||
candidates_x.append(sharp_x[..., None])
|
||||
candidates_y.append(sharp_y[..., None])
|
||||
candidates_x.append(edge_peak_x[..., None])
|
||||
candidates_y.append(edge_peak_y[..., None])
|
||||
|
||||
edge_gate = (edge_strength > solver_params.guided_candidate_edge_threshold) & valid_grad
|
||||
guided_scales = (
|
||||
-solver_params.guided_candidate_outer_scale,
|
||||
-solver_params.guided_candidate_inner_scale,
|
||||
solver_params.guided_candidate_inner_scale,
|
||||
solver_params.guided_candidate_outer_scale,
|
||||
)
|
||||
for scale in guided_scales:
|
||||
guided_x = torch.where(
|
||||
edge_gate,
|
||||
edge_peak_x + unit_grad_x * (cell_x * scale),
|
||||
xs + unit_grad_x * (cell_x * scale * 0.5),
|
||||
)
|
||||
guided_y = torch.where(
|
||||
edge_gate,
|
||||
edge_peak_y + unit_grad_y * (cell_y * scale),
|
||||
ys + unit_grad_y * (cell_y * scale * 0.5),
|
||||
)
|
||||
candidates_x.append(torch.round(guided_x)[..., None])
|
||||
candidates_y.append(torch.round(guided_y)[..., None])
|
||||
|
||||
candidate_x = torch.cat(candidates_x, dim=2).clamp(0, max(0, width - 1)).to(dtype=torch.long)
|
||||
candidate_y = torch.cat(candidates_y, dim=2).clamp(0, max(0, height - 1)).to(dtype=torch.long)
|
||||
offset_from_uv_x = candidate_x.to(dtype=uv.dtype) - xs[..., None]
|
||||
offset_from_uv_y = candidate_y.to(dtype=uv.dtype) - ys[..., None]
|
||||
return candidate_x, candidate_y, offset_from_uv_x, offset_from_uv_y
|
||||
|
||||
|
||||
def _reference_match_energy(
|
||||
|
|
@ -746,6 +842,7 @@ def _snap_output_to_source_pixels(
|
|||
representative_t,
|
||||
source_reference_t,
|
||||
source_reliability_t,
|
||||
source_reference_np,
|
||||
solver_params: SolverHyperParams,
|
||||
*,
|
||||
cell_x: float,
|
||||
|
|
@ -761,15 +858,17 @@ def _snap_output_to_source_pixels(
|
|||
output_height = representative.shape[0]
|
||||
output_width = representative.shape[1]
|
||||
|
||||
fractions = torch.tensor([-0.42, -0.21, 0.0, 0.21, 0.42], device=uv.device, dtype=uv.dtype)
|
||||
offset_y, offset_x = torch.meshgrid(fractions, fractions, indexing="ij")
|
||||
offset_x = (offset_x.reshape(-1) * cell_x).to(dtype=uv.dtype)
|
||||
offset_y = (offset_y.reshape(-1) * cell_y).to(dtype=uv.dtype)
|
||||
|
||||
xs = (uv[..., 0] + 1.0) * 0.5 * max(1.0, float(width - 1))
|
||||
ys = (uv[..., 1] + 1.0) * 0.5 * max(1.0, float(height - 1))
|
||||
candidate_x = torch.round(xs[..., None] + offset_x).clamp(0, max(0, width - 1)).to(dtype=torch.long)
|
||||
candidate_y = torch.round(ys[..., None] + offset_y).clamp(0, max(0, height - 1)).to(dtype=torch.long)
|
||||
candidate_x, candidate_y, _, _ = _build_candidate_positions(
|
||||
torch,
|
||||
uv,
|
||||
source_reference_np,
|
||||
solver_params,
|
||||
width=width,
|
||||
height=height,
|
||||
cell_x=cell_x,
|
||||
cell_y=cell_y,
|
||||
base_fraction_values=np.asarray([-0.42, -0.21, 0.0, 0.21, 0.42], dtype=np.float32),
|
||||
)
|
||||
candidate_colors = source_hw[candidate_y, candidate_x]
|
||||
|
||||
representative_match = (candidate_colors - representative[..., None, :]).abs().mean(dim=-1)
|
||||
|
|
@ -1005,6 +1104,7 @@ def _discrete_refine_output(
|
|||
representative_t,
|
||||
source_reference_t,
|
||||
source_reliability_t,
|
||||
source_reference_np,
|
||||
anchor_t,
|
||||
source_delta_x_t,
|
||||
source_delta_y_t,
|
||||
|
|
@ -1032,21 +1132,23 @@ def _discrete_refine_output(
|
|||
candidate_levels += 1
|
||||
candidate_extent = max(0.05, float(solver_params.refine_candidate_extent))
|
||||
fraction_values = np.linspace(-candidate_extent, candidate_extent, candidate_levels, dtype=np.float32)
|
||||
fractions = torch.tensor(fraction_values, device=uv.device, dtype=uv.dtype)
|
||||
offset_y, offset_x = torch.meshgrid(fractions, fractions, indexing="ij")
|
||||
offset_x = (offset_x.reshape(-1) * cell_x).to(dtype=uv.dtype)
|
||||
offset_y = (offset_y.reshape(-1) * cell_y).to(dtype=uv.dtype)
|
||||
|
||||
xs = (uv[..., 0] + 1.0) * 0.5 * max(1.0, float(width - 1))
|
||||
ys = (uv[..., 1] + 1.0) * 0.5 * max(1.0, float(height - 1))
|
||||
candidate_x = torch.round(xs[..., None] + offset_x).clamp(0, max(0, width - 1)).to(dtype=torch.long)
|
||||
candidate_y = torch.round(ys[..., None] + offset_y).clamp(0, max(0, height - 1)).to(dtype=torch.long)
|
||||
candidate_x, candidate_y, candidate_offset_x, candidate_offset_y = _build_candidate_positions(
|
||||
torch,
|
||||
uv,
|
||||
source_reference_np,
|
||||
solver_params,
|
||||
width=width,
|
||||
height=height,
|
||||
cell_x=cell_x,
|
||||
cell_y=cell_y,
|
||||
base_fraction_values=fraction_values,
|
||||
)
|
||||
candidate_colors = source_hw[candidate_y, candidate_x]
|
||||
anchor_energy = (candidate_colors - anchor[..., None, :]).abs().mean(dim=-1)
|
||||
rep_energy = (candidate_colors - representative[..., None, :]).abs().mean(dim=-1)
|
||||
source_reference_energy = (candidate_colors - source_reference[..., None, :]).abs().mean(dim=-1)
|
||||
alpha_energy = (candidate_colors[..., 3] - anchor[..., None, 3]).abs()
|
||||
distance_energy = ((offset_x / max(cell_x, 1e-4)) ** 2 + (offset_y / max(cell_y, 1e-4)) ** 2).reshape(1, 1, -1)
|
||||
distance_energy = (candidate_offset_x / max(cell_x, 1e-4)).square() + (candidate_offset_y / max(cell_y, 1e-4)).square()
|
||||
match_energy = _reference_match_energy(
|
||||
rep_energy,
|
||||
source_reference_energy,
|
||||
|
|
@ -1268,6 +1370,7 @@ def optimize_uv_field(
|
|||
cell_y = height / max(1, inference.target_height)
|
||||
source_t = torch.from_numpy(source.transpose(2, 0, 1)[None, ...]).to(device=device, dtype=torch.float32)
|
||||
edge = np.maximum(analysis.edge_map, _cluster_boundary_map(analysis.cluster_map))
|
||||
edge_grad_x, edge_grad_y = _edge_gradient_maps(edge)
|
||||
edge_t = torch.from_numpy(edge[None, None, ...]).to(device=device, dtype=torch.float32)
|
||||
uv0 = _make_regular_uv(
|
||||
height=height,
|
||||
|
|
@ -1289,6 +1392,9 @@ def optimize_uv_field(
|
|||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
alpha_threshold=solver_params.alpha_transparent_threshold,
|
||||
edge_hint=edge,
|
||||
edge_grad_x_hint=edge_grad_x,
|
||||
edge_grad_y_hint=edge_grad_y,
|
||||
)
|
||||
initial_patches = _sample_cell_patches(F, source_t, uv0_t, offsets_t)
|
||||
initial_representative_t, _ = _representative_colors(initial_patches, solver_params)
|
||||
|
|
@ -1297,7 +1403,7 @@ def optimize_uv_field(
|
|||
device=device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
source_reliability_t = torch.from_numpy(_build_source_reliability(source_lattice_reference)[None, ...]).to(
|
||||
source_reliability_t = torch.from_numpy(_build_source_reliability(source_lattice_reference, solver_params)[None, ...]).to(
|
||||
device=device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
|
|
@ -1328,6 +1434,7 @@ def optimize_uv_field(
|
|||
initial_representative_t,
|
||||
initial_source_reference_t,
|
||||
source_reliability_t,
|
||||
source_lattice_reference,
|
||||
solver_params,
|
||||
cell_x=cell_x,
|
||||
cell_y=cell_y,
|
||||
|
|
@ -1345,6 +1452,7 @@ def optimize_uv_field(
|
|||
initial_representative_t,
|
||||
initial_source_reference_t,
|
||||
source_reliability_t,
|
||||
source_lattice_reference,
|
||||
snap_t,
|
||||
source_delta_x_t,
|
||||
source_delta_y_t,
|
||||
|
|
@ -1355,6 +1463,27 @@ def optimize_uv_field(
|
|||
cell_y=cell_y,
|
||||
iterations=steps,
|
||||
)
|
||||
snap_score = source_lattice_consistency_breakdown(
|
||||
rgba,
|
||||
snap_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
alpha_threshold=solver_params.alpha_transparent_threshold,
|
||||
)["score"]
|
||||
target_score = source_lattice_consistency_breakdown(
|
||||
rgba,
|
||||
target_rgba,
|
||||
target_width=inference.target_width,
|
||||
target_height=inference.target_height,
|
||||
phase_x=inference.phase_x,
|
||||
phase_y=inference.phase_y,
|
||||
alpha_threshold=solver_params.alpha_transparent_threshold,
|
||||
)["score"]
|
||||
if target_score > snap_score + 1e-6:
|
||||
target_rgba = snap_rgba
|
||||
loss_history.append(float(snap_score))
|
||||
initial_rgba = snap_rgba
|
||||
uv_np = uv0_t.detach().cpu().numpy()[0]
|
||||
guidance = guide_small[0, 0].detach().cpu().numpy()
|
||||
|
|
|
|||
|
|
@ -6,6 +6,9 @@ from dataclasses import asdict, dataclass
|
|||
@dataclass(slots=True)
|
||||
class SolverHyperParams:
|
||||
representative_softmax_scale: float = 18.0
|
||||
source_edge_reliability_gain: float = 1.6
|
||||
source_edge_reliability_floor: float = 0.25
|
||||
source_edge_alpha_floor: float = 0.45
|
||||
boundary_probe_scale: float = 0.22
|
||||
boundary_signed_weight: float = 0.55
|
||||
boundary_direction_weight: float = 0.30
|
||||
|
|
@ -31,6 +34,9 @@ class SolverHyperParams:
|
|||
refine_relaxed_mode_weight: float = 0.14
|
||||
refine_candidate_extent: float = 0.70
|
||||
refine_candidate_levels: int = 7
|
||||
guided_candidate_edge_threshold: float = 0.06
|
||||
guided_candidate_inner_scale: float = 0.32
|
||||
guided_candidate_outer_scale: float = 0.60
|
||||
relax_iterations: int = 24
|
||||
relax_start_temperature: float = 0.95
|
||||
relax_end_temperature: float = 0.18
|
||||
|
|
@ -66,5 +72,5 @@ class SolverHyperParams:
|
|||
phase_rerank_max_size_delta_ratio: float = 0.40
|
||||
phase_rerank_margin: float = 0.004
|
||||
|
||||
def to_dict(self) -> dict[str, float]:
|
||||
def to_dict(self) -> dict[str, float | int]:
|
||||
return asdict(self)
|
||||
|
|
|
|||
|
|
@ -42,10 +42,15 @@ def build_source_lattice_reference(
|
|||
phase_x: float,
|
||||
phase_y: float,
|
||||
alpha_threshold: float = 0.05,
|
||||
edge_hint: np.ndarray | None = None,
|
||||
edge_grad_x_hint: np.ndarray | None = None,
|
||||
edge_grad_y_hint: np.ndarray | None = None,
|
||||
) -> SourceLatticeReference:
|
||||
height = source_rgba.shape[0]
|
||||
width = source_rgba.shape[1]
|
||||
indices = lattice_indices(
|
||||
height=source_rgba.shape[0],
|
||||
width=source_rgba.shape[1],
|
||||
height=height,
|
||||
width=width,
|
||||
target_width=target_width,
|
||||
target_height=target_height,
|
||||
phase_x=phase_x,
|
||||
|
|
@ -79,6 +84,24 @@ def build_source_lattice_reference(
|
|||
else:
|
||||
dispersion = float(np.mean(pixel_diff)) if pixel_diff.size else 0.0
|
||||
|
||||
cell_x = width / max(1, target_width)
|
||||
cell_y = height / max(1, target_height)
|
||||
default_x = np.clip(
|
||||
np.rint((np.arange(target_width, dtype=np.float32) + 0.5 + phase_x) * cell_x - 0.5),
|
||||
0,
|
||||
max(0, width - 1),
|
||||
)
|
||||
default_y = np.clip(
|
||||
np.rint((np.arange(target_height, dtype=np.float32) + 0.5 + phase_y) * cell_y - 0.5),
|
||||
0,
|
||||
max(0, height - 1),
|
||||
)
|
||||
sharp_x_flat = np.tile(default_x[None, :], (target_height, 1)).reshape(-1).astype(np.int32)
|
||||
sharp_y_flat = np.tile(default_y[:, None], (1, target_width)).reshape(-1).astype(np.int32)
|
||||
|
||||
pixel_y, pixel_x = np.indices((height, width), dtype=np.int32)
|
||||
flat_x = pixel_x.reshape(-1)
|
||||
flat_y = pixel_y.reshape(-1)
|
||||
exemplar_cost = pixel_diff + np.maximum(0.0, per_pixel_mean[:, 3] - flat_premul[:, 3]) * 1e-3
|
||||
order = np.lexsort((exemplar_cost.astype(np.float32), flat_idx.astype(np.int64)))
|
||||
sharp_premul_flat = mean_premul_flat.copy()
|
||||
|
|
@ -88,6 +111,8 @@ def build_source_lattice_reference(
|
|||
best_order = order[first_positions]
|
||||
best_cells = flat_idx[best_order]
|
||||
sharp_premul_flat[best_cells] = flat_premul[best_order]
|
||||
sharp_x_flat[best_cells] = flat_x[best_order]
|
||||
sharp_y_flat[best_cells] = flat_y[best_order]
|
||||
sharp_premul = sharp_premul_flat.reshape(target_height, target_width, premul.shape[-1])
|
||||
sharp_rgba = unpremultiply(sharp_premul)
|
||||
|
||||
|
|
@ -95,16 +120,54 @@ def build_source_lattice_reference(
|
|||
np.maximum.at(cell_alpha_max, flat_idx, flat_alpha)
|
||||
expected_pixels_per_cell = float(source_rgba.shape[0] * source_rgba.shape[1]) / float(cell_count)
|
||||
cell_support = (counts / max(expected_pixels_per_cell, 1.0)).reshape(target_height, target_width)
|
||||
edge_peak_x_flat = sharp_x_flat.copy()
|
||||
edge_peak_y_flat = sharp_y_flat.copy()
|
||||
edge_strength_flat = np.zeros(cell_count, dtype=np.float32)
|
||||
edge_grad_x_flat = np.zeros(cell_count, dtype=np.float32)
|
||||
edge_grad_y_flat = np.zeros(cell_count, dtype=np.float32)
|
||||
|
||||
if edge_hint is not None:
|
||||
flat_edge = edge_hint.reshape(-1).astype(np.float32)
|
||||
edge_score = flat_edge + flat_alpha.astype(np.float32) * 0.05
|
||||
edge_order = np.lexsort((-edge_score.astype(np.float32), flat_idx.astype(np.int64)))
|
||||
if edge_order.size > 0:
|
||||
sorted_edge_cells = flat_idx[edge_order]
|
||||
first_edge_positions = np.concatenate(([0], np.flatnonzero(np.diff(sorted_edge_cells)) + 1))
|
||||
best_edge_order = edge_order[first_edge_positions]
|
||||
best_edge_cells = flat_idx[best_edge_order]
|
||||
edge_peak_x_flat[best_edge_cells] = flat_x[best_edge_order]
|
||||
edge_peak_y_flat[best_edge_cells] = flat_y[best_edge_order]
|
||||
edge_strength_flat[best_edge_cells] = flat_edge[best_edge_order]
|
||||
if edge_grad_x_hint is not None:
|
||||
edge_grad_x_flat[best_edge_cells] = edge_grad_x_hint.reshape(-1)[best_edge_order].astype(np.float32)
|
||||
if edge_grad_y_hint is not None:
|
||||
edge_grad_y_flat[best_edge_cells] = edge_grad_y_hint.reshape(-1)[best_edge_order].astype(np.float32)
|
||||
|
||||
np.maximum.at(edge_strength_flat, flat_idx, flat_edge)
|
||||
if edge_grad_x_hint is not None or edge_grad_y_hint is not None:
|
||||
edge_peak_index_flat = edge_peak_y_flat * width + edge_peak_x_flat
|
||||
if edge_grad_x_hint is not None:
|
||||
edge_grad_x_flat = edge_grad_x_hint.reshape(-1)[edge_peak_index_flat].astype(np.float32)
|
||||
if edge_grad_y_hint is not None:
|
||||
edge_grad_y_flat = edge_grad_y_hint.reshape(-1)[edge_peak_index_flat].astype(np.float32)
|
||||
|
||||
delta_x, delta_y, delta_diag, delta_anti = _reference_deltas(sharp_premul)
|
||||
return SourceLatticeReference(
|
||||
mean_rgba=mean_rgba.astype(np.float32),
|
||||
sharp_rgba=sharp_rgba.astype(np.float32),
|
||||
dispersion=dispersion,
|
||||
lattice_indices=indices.astype(np.int32),
|
||||
cell_dispersion=cell_dispersion.astype(np.float32),
|
||||
cell_counts=counts.reshape(target_height, target_width).astype(np.float32),
|
||||
cell_support=cell_support.astype(np.float32),
|
||||
cell_alpha_max=cell_alpha_max.reshape(target_height, target_width).astype(np.float32),
|
||||
sharp_x=sharp_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
sharp_y=sharp_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_peak_x=edge_peak_x_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_peak_y=edge_peak_y_flat.reshape(target_height, target_width).astype(np.int32),
|
||||
edge_strength=edge_strength_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
edge_grad_x=edge_grad_x_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
edge_grad_y=edge_grad_y_flat.reshape(target_height, target_width).astype(np.float32),
|
||||
delta_x=delta_x.astype(np.float32) if delta_x is not None else None,
|
||||
delta_y=delta_y.astype(np.float32) if delta_y is not None else None,
|
||||
delta_diag=delta_diag.astype(np.float32) if delta_diag is not None else None,
|
||||
|
|
|
|||
|
|
@ -41,10 +41,18 @@ class SourceLatticeReference:
|
|||
mean_rgba: np.ndarray
|
||||
sharp_rgba: np.ndarray
|
||||
dispersion: float
|
||||
lattice_indices: np.ndarray
|
||||
cell_dispersion: np.ndarray
|
||||
cell_counts: np.ndarray
|
||||
cell_support: np.ndarray
|
||||
cell_alpha_max: np.ndarray
|
||||
sharp_x: np.ndarray
|
||||
sharp_y: np.ndarray
|
||||
edge_peak_x: np.ndarray
|
||||
edge_peak_y: np.ndarray
|
||||
edge_strength: np.ndarray
|
||||
edge_grad_x: np.ndarray
|
||||
edge_grad_y: np.ndarray
|
||||
delta_x: np.ndarray | None
|
||||
delta_y: np.ndarray | None
|
||||
delta_diag: np.ndarray | None
|
||||
|
|
|
|||
|
|
@ -4,8 +4,17 @@ import numpy as np
|
|||
import torch
|
||||
|
||||
from repixelizer.analysis import analyze_source
|
||||
from repixelizer.continuous import _exemplar_colors, _line_pattern_loss, optimize_uv_field
|
||||
from repixelizer.continuous import (
|
||||
_build_candidate_positions,
|
||||
_build_source_reliability,
|
||||
_exemplar_colors,
|
||||
_line_pattern_loss,
|
||||
_make_regular_uv,
|
||||
optimize_uv_field,
|
||||
)
|
||||
from repixelizer.metrics import source_lattice_consistency_breakdown
|
||||
from repixelizer.params import SolverHyperParams
|
||||
from repixelizer.source_reference import build_source_lattice_reference
|
||||
from repixelizer.synthetic import fake_pixelize
|
||||
from repixelizer.types import InferenceResult
|
||||
|
||||
|
|
@ -48,6 +57,75 @@ def test_exemplar_colors_selects_an_actual_patch_sample() -> None:
|
|||
assert any(torch.allclose(exemplar, option) for option in options)
|
||||
|
||||
|
||||
def test_source_reliability_stays_high_for_high_contrast_edge_cells() -> None:
|
||||
source = np.zeros((8, 8, 4), dtype=np.float32)
|
||||
source[..., 3] = 1.0
|
||||
source[:, 1, :3] = 1.0
|
||||
|
||||
analysis = analyze_source(source, seed=3)
|
||||
reference = build_source_lattice_reference(
|
||||
source,
|
||||
target_width=4,
|
||||
target_height=4,
|
||||
phase_x=0.0,
|
||||
phase_y=0.0,
|
||||
edge_hint=analysis.edge_map,
|
||||
edge_grad_x_hint=np.gradient(analysis.edge_map, axis=1).astype(np.float32),
|
||||
edge_grad_y_hint=np.gradient(analysis.edge_map, axis=0).astype(np.float32),
|
||||
)
|
||||
|
||||
reliability = _build_source_reliability(reference, SolverHyperParams())
|
||||
|
||||
assert reference.cell_dispersion[1, 0] > reference.dispersion
|
||||
assert reference.edge_strength[1, 0] > 0.0
|
||||
assert reliability[1, 0] >= 0.7
|
||||
|
||||
|
||||
def test_candidate_positions_include_sharp_and_edge_guided_samples() -> None:
|
||||
source = np.zeros((6, 6, 4), dtype=np.float32)
|
||||
source[..., 3] = 1.0
|
||||
source[1:5, 2, :3] = 1.0
|
||||
|
||||
edge_hint = np.zeros((6, 6), dtype=np.float32)
|
||||
edge_hint[1:5, 2] = 1.0
|
||||
edge_grad_x = np.zeros((6, 6), dtype=np.float32)
|
||||
edge_grad_x[1:5, 2] = 1.0
|
||||
edge_grad_y = np.zeros((6, 6), dtype=np.float32)
|
||||
|
||||
reference = build_source_lattice_reference(
|
||||
source,
|
||||
target_width=2,
|
||||
target_height=2,
|
||||
phase_x=0.0,
|
||||
phase_y=0.0,
|
||||
edge_hint=edge_hint,
|
||||
edge_grad_x_hint=edge_grad_x,
|
||||
edge_grad_y_hint=edge_grad_y,
|
||||
)
|
||||
uv = torch.from_numpy(_make_regular_uv(6, 6, 2, 2, 0.0, 0.0)).to(dtype=torch.float32)
|
||||
|
||||
candidate_x, candidate_y, _, _ = _build_candidate_positions(
|
||||
torch,
|
||||
uv,
|
||||
reference,
|
||||
SolverHyperParams(),
|
||||
width=6,
|
||||
height=6,
|
||||
cell_x=3.0,
|
||||
cell_y=3.0,
|
||||
base_fraction_values=np.asarray([0.0], dtype=np.float32),
|
||||
)
|
||||
|
||||
cell_candidates = {
|
||||
(int(y), int(x))
|
||||
for y, x in zip(candidate_y[0, 0].cpu().tolist(), candidate_x[0, 0].cpu().tolist())
|
||||
}
|
||||
|
||||
assert (int(reference.sharp_y[0, 0]), int(reference.sharp_x[0, 0])) in cell_candidates
|
||||
assert (int(reference.edge_peak_y[0, 0]), int(reference.edge_peak_x[0, 0])) in cell_candidates
|
||||
assert len(cell_candidates) > 2
|
||||
|
||||
|
||||
def test_optimize_uv_field_does_not_regress_from_snap_on_thin_feature_case() -> None:
|
||||
source = np.zeros((16, 16, 4), dtype=np.float32)
|
||||
source[4:12, 8] = np.asarray([0.95, 0.95, 0.95, 1.0], dtype=np.float32)
|
||||
|
|
|
|||
|
|
@ -35,3 +35,31 @@ def test_source_lattice_reference_recovers_stable_cell_colors_and_deltas() -> No
|
|||
assert np.allclose(reference.delta_x, expected_premul[:, 1:, :] - expected_premul[:, :-1, :], atol=1e-5)
|
||||
assert np.allclose(reference.delta_y, expected_premul[1:, :, :] - expected_premul[:-1, :, :], atol=1e-5)
|
||||
assert reference.dispersion >= 0.0
|
||||
|
||||
|
||||
def test_source_lattice_reference_tracks_edge_peaks_and_gradients() -> None:
|
||||
source = np.zeros((6, 6, 4), dtype=np.float32)
|
||||
source[..., 3] = 1.0
|
||||
source[:, 2, :3] = 1.0
|
||||
|
||||
edge_hint = np.zeros((6, 6), dtype=np.float32)
|
||||
edge_hint[:, 2] = 1.0
|
||||
edge_grad_x = np.zeros((6, 6), dtype=np.float32)
|
||||
edge_grad_x[:, 2] = 1.0
|
||||
edge_grad_y = np.zeros((6, 6), dtype=np.float32)
|
||||
|
||||
reference = build_source_lattice_reference(
|
||||
source,
|
||||
target_width=2,
|
||||
target_height=2,
|
||||
phase_x=0.0,
|
||||
phase_y=0.0,
|
||||
edge_hint=edge_hint,
|
||||
edge_grad_x_hint=edge_grad_x,
|
||||
edge_grad_y_hint=edge_grad_y,
|
||||
)
|
||||
|
||||
assert np.all(reference.edge_peak_x[:, 0] == 2)
|
||||
assert np.all(reference.edge_strength[:, 0] == 1.0)
|
||||
assert np.all(reference.edge_grad_x[:, 0] == 1.0)
|
||||
assert np.all(reference.edge_grad_y[:, 0] == 0.0)
|
||||
|
|
|
|||
Loading…
Reference in a new issue