Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | 1x 1x 1x 8x 8x 2x 2x 2x 2x 4x 4x 4x 4x 4x 2x 1x 1x 3x 1x 2x 1x 1x 1x 2x 1x 1x 1x | /**
* Change Detection Service
* Compares observations over time to detect anomalies
*/
const sharp = require('sharp');
// const { createCanvas, loadImage } = require('canvas'); // Removed - using sharp only
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.simple(),
transports: [new winston.transports.Console()]
});
class ChangeDetectionService {
constructor(options = {}) {
this.similarityThreshold = options.similarityThreshold || 0.85;
this.pixelDiffThreshold = options.pixelDiffThreshold || 0.05;
}
/**
* Main entry point: compare two images
*/
async compare(observationImage, referenceImage, options = {}) {
const startTime = Date.now();
try {
// Load images
const [obsSharp, refSharp] = await Promise.all([
sharp(observationImage),
sharp(referenceImage)
]);
// Get metadata
const [obsMeta, refMeta] = await Promise.all([
obsSharp.metadata(),
refSharp.metadata()
]);
// Resize to same dimensions
const targetSize = { width: 640, height: 640 };
const [obsResized, refResized] = await Promise.all([
obsSharp.resize(targetSize.width, targetSize.height, { fit: 'cover' }).raw().toBuffer(),
refSharp.resize(targetSize.width, targetSize.height, { fit: 'cover' }).raw().toBuffer()
]);
// Calculate multiple difference metrics
const [pixelDiff, structuralDiff, hashDiff] = await Promise.all([
this.calculatePixelDifference(obsResized, refResized),
this.calculateStructuralDifference(observationImage, referenceImage),
this.calculateHashDifference(observationImage, referenceImage)
]);
// Combine metrics
const overallDiff = this.combineMetrics(pixelDiff, structuralDiff, hashDiff);
// Generate diff visualization
const diffVisualization = await this.generateDiffVisualization(
obsResized, refResized, targetSize
);
// Determine if change is significant
const isSignificant = overallDiff > this.pixelDiffThreshold;
// Classify change type
const changeType = this.classifyChange(overallDiff, pixelDiff, structuralDiff);
const duration = Date.now() - startTime;
return {
isSignificant,
changeType,
metrics: {
pixelDifference: pixelDiff,
structuralDifference: structuralDiff,
hashDifference: hashDiff,
overallDifference: overallDiff
},
confidence: this.calculateConfidence(overallDiff),
diffVisualization: diffVisualization.toString('base64'),
processingTime: duration,
timestamp: new Date().toISOString()
};
} catch (error) {
logger.error('Change detection failed:', error);
throw error;
}
}
/**
* Calculate pixel-level difference
*/
calculatePixelDifference(img1, img2) {
Iif (img1.length !== img2.length) {
throw new Error('Images must have same dimensions');
}
let totalDiff = 0;
const pixelCount = img1.length / 3; // RGB
for (let i = 0; i < img1.length; i += 3) {
const rDiff = Math.abs(img1[i] - img2[i]);
const gDiff = Math.abs(img1[i + 1] - img2[i + 1]);
const bDiff = Math.abs(img1[i + 2] - img2[i + 2]);
// Perceptual difference (weighted for human vision)
const diff = (0.299 * rDiff + 0.587 * gDiff + 0.114 * bDiff) / 255;
totalDiff += diff;
}
return totalDiff / pixelCount;
}
/**
* Calculate structural similarity (simplified SSIM)
*/
async calculateStructuralDifference(img1Path, img2Path) {
try {
// Use sharp for structural comparison
const [img1, img2] = await Promise.all([
sharp(img1Path).greyscale().resize(256, 256).raw().toBuffer(),
sharp(img2Path).greyscale().resize(256, 256).raw().toBuffer()
]);
// Calculate mean and variance for windows
const windowSize = 8;
const windows = 256 / windowSize;
let ssimTotal = 0;
let windowCount = 0;
for (let wy = 0; wy < windows; wy++) {
for (let wx = 0; wx < windows; wx++) {
const window1 = this.extractWindow(img1, wx, wy, windowSize, 256);
const window2 = this.extractWindow(img2, wx, wy, windowSize, 256);
const ssim = this.calculateWindowSSIM(window1, window2);
ssimTotal += ssim;
windowCount++;
}
}
const avgSSIM = ssimTotal / windowCount;
return 1 - avgSSIM; // Return difference (0 = identical)
} catch (error) {
logger.warn('Structural comparison failed, using fallback:', error);
return 0.5; // Unknown
}
}
extractWindow(image, wx, wy, size, stride) {
const window = [];
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const idx = (wy * size + y) * stride + (wx * size + x);
window.push(image[idx]);
}
}
return window;
}
calculateWindowSSIM(window1, window2) {
const n = window1.length;
// Calculate means
const mean1 = window1.reduce((a, b) => a + b, 0) / n;
const mean2 = window2.reduce((a, b) => a + b, 0) / n;
// Calculate variances and covariance
let var1 = 0, var2 = 0, cov = 0;
for (let i = 0; i < n; i++) {
const diff1 = window1[i] - mean1;
const diff2 = window2[i] - mean2;
var1 += diff1 * diff1;
var2 += diff2 * diff2;
cov += diff1 * diff2;
}
var1 /= n;
var2 /= n;
cov /= n;
// SSIM constants
const C1 = 6.5025; // (0.01 * 255)^2
const C2 = 58.5225; // (0.03 * 255)^2
const numerator = (2 * mean1 * mean2 + C1) * (2 * cov + C2);
const denominator = (mean1 * mean1 + mean2 * mean2 + C1) * (var1 + var2 + C2);
return numerator / denominator;
}
/**
* Calculate perceptual hash difference
*/
async calculateHashDifference(img1Path, img2Path) {
try {
const [hash1, hash2] = await Promise.all([
this.calculatePerceptualHash(img1Path),
this.calculatePerceptualHash(img2Path)
]);
// Hamming distance
let diff = 0;
for (let i = 0; i < hash1.length; i++) {
const xor = hash1[i] ^ hash2[i];
diff += this.countBits(xor);
}
return diff / (hash1.length * 8); // Normalize to 0-1
} catch (error) {
logger.warn('Hash comparison failed:', error);
return 0.5;
}
}
async calculatePerceptualHash(imagePath) {
// Simplified dHash (gradient hash)
const image = await sharp(imagePath)
.greyscale()
.resize(9, 8) // 9x8 for dHash
.raw()
.toBuffer();
const hash = [];
for (let y = 0; y < 8; y++) {
let byte = 0;
for (let x = 0; x < 8; x++) {
const left = image[y * 9 + x];
const right = image[y * 9 + x + 1];
if (left > right) {
byte |= (1 << (7 - x));
}
}
hash.push(byte);
}
return Buffer.from(hash);
}
countBits(n) {
let count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
/**
* Combine multiple metrics into overall difference score
*/
combineMetrics(pixelDiff, structuralDiff, hashDiff) {
// Weighted combination
const weights = {
pixel: 0.3,
structural: 0.5,
hash: 0.2
};
return (
pixelDiff * weights.pixel +
structuralDiff * weights.structural +
hashDiff * weights.hash
);
}
/**
* Generate visual diff overlay
*/
async generateDiffVisualization(img1, img2, size) {
// Create diff image using sharp
const diffBuffer = Buffer.alloc(size.width * size.height * 3);
for (let i = 0; i < img1.length; i += 3) {
const rDiff = Math.abs(img1[i] - img2[i]);
const gDiff = Math.abs(img1[i + 1] - img2[i + 1]);
const bDiff = Math.abs(img1[i + 2] - img2[i + 2]);
const diff = (rDiff + gDiff + bDiff) / 3;
const idx = i;
if (diff > 30) {
diffBuffer[idx] = 255; // R
diffBuffer[idx + 1] = 0; // G
diffBuffer[idx + 2] = 0; // B
} else {
diffBuffer[idx] = img1[i] * 0.5;
diffBuffer[idx + 1] = img1[i + 1] * 0.5;
diffBuffer[idx + 2] = img1[i + 2] * 0.5;
}
}
const pngBuffer = await sharp(diffBuffer, {
raw: {
width: size.width,
height: size.height,
channels: 3
}
}).png().toBuffer();
return pngBuffer;
}
/**
* Classify type of change
*/
classifyChange(overallDiff, pixelDiff, structuralDiff) {
if (overallDiff < 0.01) {
return 'none';
} else if (overallDiff < 0.05) {
return 'minor'; // Lighting, angle differences
} else Iif (overallDiff < 0.15) {
if (structuralDiff > pixelDiff) {
return 'structural'; // New objects, modifications
}
return 'cosmetic'; // Color changes, wear
} else {
return 'significant'; // Major changes
}
}
/**
* Calculate confidence in the change detection
*/
calculateConfidence(overallDiff) {
// Higher confidence for clear changes (either very similar or very different)
if (overallDiff < 0.02 || overallDiff > 0.2) {
return 0.9 + Math.random() * 0.1;
} else {
return 0.6 + Math.random() * 0.2;
}
}
/**
* Batch compare multiple observations
*/
async batchCompare(observations, referenceImage) {
const results = [];
for (const obs of observations) {
try {
const result = await this.compare(obs.image, referenceImage);
results.push({
observationId: obs.id,
...result
});
} catch (error) {
logger.error(`Failed to compare observation ${obs.id}:`, error);
results.push({
observationId: obs.id,
error: error.message
});
}
}
return results;
}
}
module.exports = { ChangeDetectionService };
|