Trying to color an image using a palette

Hi.
Im trying to make an sketch that takes an image and an array of five colors and change all pixels and substitute them for the color of the array that have hue and saturation more closer to that point, letting the brightness the same. I´ve used the image of a link that is suposed to already have theese five colors and almos only them. https://yazmin.hoasenda.com/25-paletas-de-colores-de-verano-esta-coleccion-de-combinaciones-de-colores-y-paletas-de-colores-son/ But the result should be almost the same than the original and is not. I cant see the problem. The code is this:

PImage img;
float[] paletah = {217,239,23,34,44};
float[] paletas = {216,225,240,240,237};
void setup(){
 //CARGA IMAGEN
   img = loadImage("imagen.jpg");
   colorMode(HSB, 255);
  noLoop();
  size(2000,2000);
}
void draw(){
  
  int ancho = img.width;
  int alto = img.height;
  PImage newimg = createImage(ancho, alto, HSB);
  newimg.loadPixels();
  for(int i=0;i<ancho;i++){
    for(int j=0;j<alto;j++){
      color c =img.get(i,j);
      float h = hue(c);
      float s = saturation(c);
      float l=brightness(c);
      float cercano = 500000000;
      for (int k =0;k<paletah.length;k++){
        if(pow(paletah[k]-h,2)+pow(paletas[k]-s,2)<cercano){
          cercano=pow(paletah[k]-h,2)+pow(paletas[k]-s,2);
          float nuevoh=paletah[k];
          float nuevos=paletas[k];
          color nuevoc=color(nuevoh,nuevos,l);
          newimg.pixels[j*ancho+i]=nuevoc;
        }
      }      
    }
  }
  newimg.updatePixels();  
  image(newimg, 0, 0);
}
1 Like

You need to cycle through each pixel in your image and compare it to every color in your palette. For each pixel you can create an array that stores the differences between the colors, which each array element corresponding to a different color. After testing, the color with the lowest difference should be the color you set the pixel to.

https://processing.org/reference/set_.html

1 Like

This is what I do. For each pixel, I track the palette array and select the one with the minimum diference. I dont need to create a new array with the diferences because I only have to know the minumum in each case