File size: 6,351 Bytes
6b39eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  buildPaletteLUT,
  HeatmapPaletteDefinition,
} from './heatmapPalettes';

export type DiffVisualMode = 'enhanced' | 'difference' | 'heatmap';

export interface AlignedDiffPair {
  width: number;
  height: number;
  origData: Uint8ClampedArray;
  resData: Uint8ClampedArray;
  meanDiffPercent: number;
  maxDiffPercent: number;
}

export interface DiffRenderOptions {
  mode: DiffVisualMode;
  gain: number; // 1 .. 16
  threshold: number; // 0 .. 40
  palette: HeatmapPaletteDefinition;
  backgroundDim: number; // 0 .. 0.9
}

const loadImageElement = (src: string): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error('Не удалось декодировать изображение'));
    img.src = src;
  });

export async function loadAlignedDiffPair(
  originalUrl: string,
  resizedUrl: string,
  maxCalcSide = 1280
): Promise<AlignedDiffPair> {
  const [origImg, resImg] = await Promise.all([
    loadImageElement(originalUrl),
    loadImageElement(resizedUrl),
  ]);

  const natW = Math.max(1, origImg.naturalWidth || origImg.width);
  const natH = Math.max(1, origImg.naturalHeight || origImg.height);
  const longest = Math.max(natW, natH);
  const scale = longest > maxCalcSide ? maxCalcSide / longest : 1;

  const width = Math.max(1, Math.round(natW * scale));
  const height = Math.max(1, Math.round(natH * scale));

  const canvasA = document.createElement('canvas');
  canvasA.width = width;
  canvasA.height = height;
  const ctxA = canvasA.getContext('2d', { willReadFrequently: true });

  const canvasB = document.createElement('canvas');
  canvasB.width = width;
  canvasB.height = height;
  const ctxB = canvasB.getContext('2d', { willReadFrequently: true });

  if (!ctxA || !ctxB) {
    throw new Error('Canvas 2D недоступен для анализа отличий');
  }

  ctxA.imageSmoothingEnabled = true;
  ctxA.imageSmoothingQuality = 'high';
  ctxA.drawImage(origImg, 0, 0, width, height);
  const origData = ctxA.getImageData(0, 0, width, height).data;

  ctxB.imageSmoothingEnabled = true;
  ctxB.imageSmoothingQuality = 'high';
  ctxB.drawImage(resImg, 0, 0, width, height);
  const resData = ctxB.getImageData(0, 0, width, height).data;

  const pixelCount = width * height;
  let totalDiff = 0;
  let maxDiff = 0;

  for (let i = 0; i < origData.length; i += 4) {
    const dr = Math.abs(origData[i] - resData[i]);
    const dg = Math.abs(origData[i + 1] - resData[i + 1]);
    const db = Math.abs(origData[i + 2] - resData[i + 2]);
    const avg = (dr + dg + db) / 3;
    totalDiff += avg;
    if (avg > maxDiff) maxDiff = avg;
  }

  return {
    width,
    height,
    origData,
    resData,
    meanDiffPercent: (totalDiff / Math.max(1, pixelCount) / 255) * 100,
    maxDiffPercent: (maxDiff / 255) * 100,
  };
}

export async function renderDiffImageBlob(
  pair: AlignedDiffPair,
  options: DiffRenderOptions
): Promise<{ blob: Blob; changedPercent: number }> {
  const { width, height, origData, resData } = pair;
  const { mode, gain, threshold, palette, backgroundDim } = options;

  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('Не удалось создать буфер карты отличий');
  }

  const out = ctx.createImageData(width, height);
  const dst = out.data;
  const lut = mode === 'heatmap' ? buildPaletteLUT(palette) : null;
  const baseBrightness = 1 - Math.min(0.95, Math.max(0, backgroundDim));

  let changedCount = 0;
  const pixelCount = width * height;

  for (let i = 0; i < origData.length; i += 4) {
    const r1 = origData[i];
    const g1 = origData[i + 1];
    const b1 = origData[i + 2];

    const dr = Math.abs(r1 - resData[i]);
    const dg = Math.abs(g1 - resData[i + 1]);
    const db = Math.abs(b1 - resData[i + 2]);
    const maxC = Math.max(dr, dg, db);

    if (maxC > Math.max(1, threshold)) {
      changedCount += 1;
    }

    if (mode === 'difference') {
      dst[i] = dr;
      dst[i + 1] = dg;
      dst[i + 2] = db;
      dst[i + 3] = 255;
    } else if (mode === 'enhanced') {
      if (maxC <= threshold) {
        // Subtle darkened context so spatial location remains recognizable
        dst[i] = Math.round(r1 * 0.14);
        dst[i + 1] = Math.round(g1 * 0.14);
        dst[i + 2] = Math.round(b1 * 0.14);
        dst[i + 3] = 255;
      } else {
        const er = Math.min(255, Math.round(Math.max(0, dr - threshold) * gain));
        const eg = Math.min(255, Math.round(Math.max(0, dg - threshold) * gain));
        const eb = Math.min(255, Math.round(Math.max(0, db - threshold) * gain));
        dst[i] = Math.max(er, Math.round(r1 * 0.18));
        dst[i + 1] = Math.max(eg, Math.round(g1 * 0.18));
        dst[i + 2] = Math.max(eb, Math.round(b1 * 0.18));
        dst[i + 3] = 255;
      }
    } else if (lut) {
      // Heatmap over darkened original photo
      const lum = 0.299 * r1 + 0.587 * g1 + 0.114 * b1;
      const baseGray = lum * baseBrightness;

      const avgDiff = (dr + dg + db) / 3;
      const eff = Math.max(0, avgDiff - threshold);
      const norm = Math.min(1, (eff * gain) / 255);

      if (norm <= 0.015) {
        dst[i] = Math.round(baseGray);
        dst[i + 1] = Math.round(baseGray);
        dst[i + 2] = Math.round(baseGray);
        dst[i + 3] = 255;
      } else {
        const idx = Math.min(255, Math.max(0, Math.round(norm * 255))) * 3;
        const alpha = Math.min(0.92, 0.25 + Math.pow(norm, 0.65) * 0.67);
        const invAlpha = 1 - alpha;
        dst[i] = Math.round(baseGray * invAlpha + lut[idx] * alpha);
        dst[i + 1] = Math.round(baseGray * invAlpha + lut[idx + 1] * alpha);
        dst[i + 2] = Math.round(baseGray * invAlpha + lut[idx + 2] * alpha);
        dst[i + 3] = 255;
      }
    }
  }

  ctx.putImageData(out, 0, 0);

  const blob = await new Promise<Blob>((resolve, reject) => {
    canvas.toBlob(
      (b) => {
        if (b) resolve(b);
        else reject(new Error('Не удалось сформировать карту отличий'));
      },
      'image/png',
      1
    );
  });

  return {
    blob,
    changedPercent: (changedCount / Math.max(1, pixelCount)) * 100,
  };
}