Trying to color an image using a palette

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. 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(){
   img = loadImage("imagen.jpg");
   colorMode(HSB, 255);
void draw(){
  int ancho = img.width;
  int alto = img.height;
  PImage newimg = createImage(ancho, alto, HSB);
  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++){
          float nuevoh=paletah[k];
          float nuevos=paletas[k];
          color nuevoc=color(nuevoh,nuevos,l);
  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.

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