MCPcopy Create free account
hub / github.com/32comic/image2pixel-web / calculateBlockVariance

Method calculateBlockVariance

pixelizer.js:439–471  ·  view source on GitHub ↗
(data, width, startX, startY, blockSize)

Source from the content-addressed store, hash-verified

437 }
438
439 calculateBlockVariance(data, width, startX, startY, blockSize) {
440 const pixels = [];
441
442 for (let y = startY; y < startY + blockSize; y++) {
443 for (let x = startX; x < startX + blockSize; x++) {
444 const index = (y * width + x) * 4;
445 pixels.push({
446 r: data[index],
447 g: data[index + 1],
448 b: data[index + 2],
449 a: data[index + 3]
450 });
451 }
452 }
453
454 if (pixels.length === 0) return 0;
455
456 // 计算颜色方差
457 const avgR = pixels.reduce((sum, p) => sum + p.r, 0) / pixels.length;
458 const avgG = pixels.reduce((sum, p) => sum + p.g, 0) / pixels.length;
459 const avgB = pixels.reduce((sum, p) => sum + p.b, 0) / pixels.length;
460 const avgA = pixels.reduce((sum, p) => sum + p.a, 0) / pixels.length;
461
462 const variance = pixels.reduce((sum, p) => {
463 return sum +
464 Math.pow(p.r - avgR, 2) +
465 Math.pow(p.g - avgG, 2) +
466 Math.pow(p.b - avgB, 2) +
467 Math.pow(p.a - avgA, 2);
468 }, 0) / pixels.length;
469
470 return variance;
471 }
472
473 calculateSuggestedWidth(imageData) {
474 const { width, height } = imageData;

Callers 1

validateBlockSizeMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected