1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Align & Optimize - Explicit Fix</title>
<style>
body { font-family: sans-serif; text-align: center; background: #f5f5f5; margin: 20px; }
canvas { border: 1px solid #333; background: #fff; cursor: grab; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
.panel { background: white; padding: 20px; border-radius: 8px; display: inline-block; border: 1px solid #ccc; margin-bottom: 10px; }
textarea { width: 90%; height: 100px; font-family: monospace; font-size: 11px; margin-top: 10px; }
button { padding: 10px 15px; margin: 5px; cursor: pointer; font-weight: bold; }
#status { color: red; height: 20px; font-weight: bold; }
</style>
</head>
<body>
<h3>Align & Optimize (Asymmetric)</h3>
<div class="panel">
<input type="file" id="f1" accept="image/*">
<input type="file" id="f2" accept="image/*"><br><br>
<button id="opt">Optimize All</button>
<button id="optZoom">Optimize Zoom (Space)</button>
<button id="crop">Prepare Crop</button>
<button id="dl" disabled>Download Images</button>
<br><br>
Iterations: <input type="range" id="iterSlider" min="5" max="50" value="15">
<span id="iterVal">15</span>
</div>
<div id="status"></div>
<div>MSE: <span id="score">-</span> | Overlap: <span id="overlap">-</span></div>
<canvas id="cv"></canvas><br>
<textarea id="cmd" readonly></textarea><br>
<button id="copy">Copy ImageMagick Commands</button>
<script>
const canvas = document.getElementById('cv');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score');
const overlapEl = document.getElementById('overlap');
const statusEl = document.getElementById('status');
const cmdEl = document.getElementById('cmd');
let i1 = new Image(), i2 = new Image(), l1 = 0, l2 = 0;
let name1 = "img1.png", name2 = "img2.png";
let ox = 0, oy = 0, sx = 1, sy = 1;
let mx = 0, my = 0, drag = 0, lx = 0, ly = 0;
let pyr1 = [], pyr2 = [], out1, out2;
const LEVELS = 4;
let optimizing = false;
// --- Pyramid logic ---
function buildPyramid(img) {
let levels = [];
let c = document.createElement('canvas');
c.width = img.width; c.height = img.height;
let x = c.getContext('2d');
x.drawImage(img, 0, 0);
let d = x.getImageData(0, 0, img.width, img.height).data;
let g = new Float32Array(img.width * img.height);
for (let i = 0, j = 0; i < d.length; i += 4, j++)
g[j] = 0.299 * d[i] + 0.587 * d[i+1] + 0.114 * d[i+2];
levels.push({ w: img.width, h: img.height, data: g });
for (let l = 1; l < LEVELS; l++) {
let p = levels[l-1], w2 = Math.floor(p.w / 2), h2 = Math.floor(p.h / 2);
let g2 = new Float32Array(w2 * h2);
for (let y = 0; y < h2; y++) {
for (let xi = 0; xi < w2; xi++) {
let x0 = 2 * xi, x1 = Math.min(2 * xi + 1, p.w - 1);
let y0 = 2 * y, y1 = Math.min(2 * y + 1, p.h - 1);
g2[y * w2 + xi] = (p.data[y0 * p.w + x0] + p.data[y0 * p.w + x1] +
p.data[y1 * p.w + x0] + p.data[y1 * p.w + x1]) * 0.25;
}
}
levels.push({ w: w2, h: h2, data: g2 });
}
return levels;
}
function sample(img, x, y) {
if (x < 0 || y < 0 || x >= img.w || y >= img.h) return NaN;
let x0 = Math.floor(x), y0 = Math.floor(y), x1 = Math.min(x0 + 1, img.w - 1), y1 = Math.min(y0 + 1, img.h - 1);
let dx = x - x0, dy = y - y0;
return (img.data[y0 * img.w + x0] * (1-dx) + img.data[y0 * img.w + x1] * dx) * (1-dy) +
(img.data[y1 * img.w + x0] * (1-dx) + img.data[y1 * img.w + x1] * dx) * dy;
}
function computeMSE(level, tx, ty, tsx, tsy) {
if (!l1 || !l2) return Infinity;
let A = pyr1[level], B = pyr2[level], sF = 1 / (2**level);
let lox = tx * sF, loy = ty * sF;
let ix0 = Math.max(0, Math.ceil(lox)), iy0 = Math.max(0, Math.ceil(loy));
let ix1 = Math.min(A.w, Math.floor(lox + B.w * tsx)), iy1 = Math.min(A.h, Math.floor(loy + B.h * tsy));
if (ix1 <= ix0 || iy1 <= iy0) return Infinity;
let mse = 0, n = 0;
for (let y = iy0; y < iy1; y++) {
for (let x = ix0; x < ix1; x++) {
let v = sample(B, (x - lox) / tsx, (y - loy) / tsy);
if (isNaN(v)) continue;
let d = A.data[y * A.w + x] - v;
mse += d * d; n++;
}
}
if (level === 0) overlapEl.textContent = n > 0 ? (n/(A.w*A.h)*100).toFixed(1) + '%' : '0%';
return n ? mse / n : Infinity;
}
function draw() {
if (!l1) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(i1, 0, 0);
if (l2) {
ctx.save(); ctx.globalAlpha = 0.5;
ctx.translate(ox, oy); ctx.scale(sx, sy);
ctx.drawImage(i2, 0, 0); ctx.restore();
}
scoreEl.textContent = computeMSE(0, ox, oy, sx, sy).toFixed(2);
updateCmd();
}
// --- NEW WHEEL LOGIC (EXPLICIT) ---
canvas.onwheel = function(e) {
if (!l2) return;
e.preventDefault(); // Stop browser zoom
// 1. Identify scroll direction and magnitude
// When Shift is pressed, many browsers move vertical scroll to deltaX
let delta = (Math.abs(e.deltaX) > Math.abs(e.deltaY)) ? e.deltaX : e.deltaY;
let factor = delta < 0 ? 1.05 : 0.95;
// 2. Identify the fixed point (anchor) in image coordinates
// We want the point in i2 that is currently under the mouse to stay there
let imagePointX = (e.offsetX - ox) / sx;
let imagePointY = (e.offsetY - oy) / sy;
// 3. Apply scaling based on modifiers
if (e.shiftKey) {
// Shift + Wheel -> SY ONLY
sy *= factor;
} else if (e.ctrlKey) {
// Ctrl + Wheel -> SX ONLY
sx *= factor;
} else {
// Wheel Only -> UNIFORM
sx *= factor;
sy *= factor;
}
// 4. Update offsets to maintain the anchor point
// Formula: NewOffset = MousePos - (ImagePoint * NewScale)
ox = e.offsetX - (imagePointX * sx);
oy = e.offsetY - (imagePointY * sy);
draw();
};
canvas.onmousedown = e => { drag = 1; lx = e.offsetX; ly = e.offsetY; canvas.style.cursor = "grabbing"; };
canvas.onmouseup = canvas.onmouseleave = () => { drag = 0; canvas.style.cursor = "grab"; };
canvas.onmousemove = e => {
mx = e.offsetX; my = e.offsetY;
if (drag) { ox += (mx - lx); oy += (my - ly); lx = mx; ly = my; draw(); }
};
window.onkeydown = e => { if(e.code === "Space" && !optimizing) { e.preventDefault(); optZoom.click(); } };
// --- Optimizers ---
async function runOpt(mode) {
if (!l1 || !l2) return;
optimizing = true; statusEl.textContent = "OPTIMIZING...";
const iters = parseInt(iterSlider.value);
// For Zoom optimization, we lock the anchor once at the current mouse position
const anchorX = (mx - ox) / sx;
const anchorY = (my - oy) / sy;
for (let l = LEVELS - 1; l >= 0; l--) {
let currentBest = { ox, oy, sx, sy, score: computeMSE(l, ox, oy, sx, sy) };
for (let i = 0; i < iters; i++) {
let stepO = (2 ** l) / (i + 1);
let stepF = 1 + 0.03 / (i + 1);
// Grid search around current parameters
for (let dx of (mode === 'all' ? [-1, 0, 1] : [0])) {
for (let dy of (mode === 'all' ? [-1, 0, 1] : [0])) {
for (let dsx of [-1, 0, 1]) {
for (let dsy of [-1, 0, 1]) {
// Calculate test candidates
let testSX = sx * Math.pow(stepF, dsx);
let testSY = sy * Math.pow(stepF, dsy);
let testOX, testOY;
if (mode === 'zoom') {
// Locked to mouse position
testOX = mx - (anchorX * testSX);
testOY = my - (anchorY * testSY);
} else {
// Free translation
testOX = ox + (dx * stepO);
testOY = oy + (dy * stepO);
}
if (testSX < 0.01 || testSY < 0.01) continue;
let s = computeMSE(l, testOX, testOY, testSX, testSY);
if (s < currentBest.score) {
currentBest = { ox: testOX, oy: testOY, sx: testSX, sy: testSY, score: s };
}
}
}
}
}
// Apply iteration results
ox = currentBest.ox; oy = currentBest.oy; sx = currentBest.sx; sy = currentBest.sy;
draw();
await new Promise(r => setTimeout(r, 0));
}
}
optimizing = false; statusEl.textContent = "";
}
opt.onclick = () => runOpt('all');
optZoom.onclick = () => runOpt('zoom');
// --- I/O ---
f1.onchange = e => {
let f = e.target.files[0]; if (!f) return;
name1 = f.name; i1 = new Image();
i1.onload = () => { l1 = 1; canvas.width = i1.width; canvas.height = i1.height; pyr1 = buildPyramid(i1); draw(); };
i1.src = URL.createObjectURL(f);
};
f2.onchange = e => {
let f = e.target.files[0]; if (!f) return;
name2 = f.name; i2 = new Image();
i2.onload = () => { l2 = 1; pyr2 = buildPyramid(i2); ox = (canvas.width-i2.width)/2; oy = (canvas.height-i2.height)/2; draw(); };
i2.src = URL.createObjectURL(f);
};
crop.onclick = () => {
let x0 = Math.max(0, ox), y0 = Math.max(0, oy);
let w = Math.floor(Math.min(canvas.width, ox + i2.width * sx) - x0);
let h = Math.floor(Math.min(canvas.height, oy + i2.height * sy) - y0);
if (w <= 5 || h <= 5) return alert("Overlap too small!");
out1 = document.createElement('canvas'); out2 = document.createElement('canvas');
out1.width = out2.width = w; out1.height = out2.height = h;
out1.getContext('2d').drawImage(i1, x0, y0, w, h, 0, 0, w, h);
out2.getContext('2d').drawImage(i2, (x0 - ox)/sx, (y0 - oy)/sy, w/sx, h/sy, 0, 0, w, h);
document.getElementById('dl').disabled = false;
};
document.getElementById('dl').onclick = () => {
const s = (c, n) => { let a = document.createElement('a'); a.download = n; a.href = c.toDataURL(); a.click(); };
s(out1, "clipped_" + name1); s(out2, "clipped_" + name2);
};
function updateCmd() {
if (!l1 || !l2) return;
let x0 = Math.max(0, ox), y0 = Math.max(0, oy);
let w = Math.floor(Math.min(canvas.width, ox + i2.width * sx) - x0);
let h = Math.floor(Math.min(canvas.height, oy + i2.height * sy) - y0);
if (w <= 0 || h <= 0) return;
let cr = `${w}x${h}+${Math.round(x0)}+${Math.round(y0)}`;
cmdEl.value = `magick "${name1}" -crop ${cr} +repage "clipped_${name1}"\n` +
`magick "${name2}" -virtual-pixel black -distort AffineProjection "${sx.toFixed(6)},0,0,${sy.toFixed(6)},${ox.toFixed(2)},${oy.toFixed(2)}" -crop ${cr} +repage "clipped_${name2}"`;
}
document.getElementById('copy').onclick = () => { cmdEl.select(); navigator.clipboard.writeText(cmdEl.value); };
iterSlider.oninput = () => document.getElementById('iterVal').textContent = iterSlider.value;
</script>
</body>
</html>
|