2022-06-12 07:47:30 +08:00
|
|
|
import { RGBA } from '../src/colour';
|
2021-10-14 06:26:26 +08:00
|
|
|
|
2023-09-04 05:51:29 +08:00
|
|
|
export function getAverageColour(image: Uint8ClampedArray): RGBA {
|
2022-02-20 05:50:17 +08:00
|
|
|
let r = 0;
|
|
|
|
let g = 0;
|
|
|
|
let b = 0;
|
2022-06-12 07:47:30 +08:00
|
|
|
let a = 0;
|
|
|
|
let weight = 0;
|
2023-09-04 05:51:29 +08:00
|
|
|
for (let x = 0; x < 16; ++x) {
|
|
|
|
for (let y = 0; y < 16; ++y) {
|
|
|
|
const index = 4 * (16 * y + x);
|
|
|
|
const rgba = image.slice(index, index + 4);
|
2022-06-12 09:20:35 +08:00
|
|
|
const alpha = rgba[3] / 255;
|
|
|
|
r += (rgba[0] / 255) * alpha;
|
|
|
|
g += (rgba[1] / 255) * alpha;
|
|
|
|
b += (rgba[2] / 255) * alpha;
|
|
|
|
a += alpha;
|
|
|
|
weight += alpha;
|
2021-10-14 06:26:26 +08:00
|
|
|
}
|
|
|
|
}
|
2023-09-04 05:51:29 +08:00
|
|
|
const numPixels = 16 * 16;
|
2022-06-12 07:47:30 +08:00
|
|
|
return {
|
2022-06-12 09:20:35 +08:00
|
|
|
r: r / weight,
|
|
|
|
g: g / weight,
|
|
|
|
b: b / weight,
|
|
|
|
a: a / numPixels,
|
2022-06-12 07:47:30 +08:00
|
|
|
};
|
2022-02-20 05:50:17 +08:00
|
|
|
}
|
2022-02-20 08:42:30 +08:00
|
|
|
|
2023-09-04 05:51:29 +08:00
|
|
|
export function getStandardDeviation(image: Uint8ClampedArray, average: RGBA): number {
|
2022-11-05 05:00:17 +08:00
|
|
|
let squaredDist = 0.0;
|
|
|
|
let weight = 0.0;
|
2023-09-04 05:51:29 +08:00
|
|
|
for (let x = 0; x < 16; ++x) {
|
|
|
|
for (let y = 0; y < 16; ++y) {
|
|
|
|
const index = 4 * (16 * y + x);
|
|
|
|
const rgba = image.slice(index, index + 4);
|
2022-11-05 05:00:17 +08:00
|
|
|
const alpha = rgba[3] / 255;
|
|
|
|
weight += alpha;
|
|
|
|
const r = (rgba[0] / 255) * alpha;
|
|
|
|
const g = (rgba[1] / 255) * alpha;
|
|
|
|
const b = (rgba[2] / 255) * alpha;
|
|
|
|
squaredDist += Math.pow(r - average.r, 2) + Math.pow(g - average.g, 2) + Math.pow(b - average.b, 2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Math.sqrt(squaredDist / weight);
|
2023-09-04 05:51:29 +08:00
|
|
|
}
|