If I get the average color using RGB I get this, which looks correct:
But when I try it with HSB, no matter what I try, I can’t get it right.
I have been playing with colorMode(HSB, x, x, x), but I still end up with wrong things.
https://editor.p5js.org/clankill3r/sketches/7UNGJYvGZ
Can someone help me?
function f_of_img(img, f) {
	const buffer = [0,0,0,0]; // the pixels are Uint8ClampedArray, but hue etc. wants a 'normal' array
	const n_pixels = img.pixels.length / 4;
	let p = 0;
	for (let i = 0; i < img.pixels.length; i += 4) {
		buffer[0] = img.pixels[i+0];
		buffer[1] = img.pixels[i+1];
		buffer[2] = img.pixels[i+2];
		buffer[3] = img.pixels[i+3];
		p += f(buffer);
	}
	return p / n_pixels;
}
function hue_of_img(img) {
	return f_of_img(img, hue);
}
function saturation_of_img(img) {
	return f_of_img(img, saturation);
}
function brightness_of_img(img) {
	return f_of_img(img, brightness);
}
function red_of_img(img) {
	return f_of_img(img, red);
}
function green_of_img(img) {
	return f_of_img(img, green);
}
function blue_of_img(img) {
	return f_of_img(img, blue);
}
let img;
let ready = false;
function preload() {
  img = loadImage("https://images.unsplash.com/photo-1573615168235-5b20c7c642ce?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max", (img)=> {
    img.loadPixels();
    ready = true;
  });
}
function setup() {
  createCanvas(400, 400);
  
}
function draw() {
  background(220);
  image(img, 0, 0, width, height);
  if (ready) {
    
//     const _red = red_of_img(img);
// 	   const _green = green_of_img(img);
// 	   const _blue = blue_of_img(img);
//    
//     fill(_red, _green, _blue);
    
    colorMode(HSB);
    
    const _hue = hue_of_img(img);
	const _saturation = saturation_of_img(img);
	const _brightness = brightness_of_img(img);
    
    
    fill(_hue, _saturation, _brightness);
    
    rect(0, 0, 100, 100);
    noLoop();
  }
  
}
            