近似色を探す
実行例
 

ソースコード
TypeScript
解説/アルゴリズム
ある二つの色がどれくらい似ているのか(近い色なのか)を判別するために、RGB 空間上での位置の差を距離として捉え、二点間距離を求める。
その距離が前もって決めておいた、しきい値より小さければ距離が近い、つまり似ている色と判断することが可能になる。
コード例
import * as p5 from "p5";
new p5((p: p5) => {
  let image: p5.Image;
  // しきい値
  const threshold = 100;
  // ベースとなる色
  const br = 205;
  const bg = 78;
  const bb = 129;
  p.preload = () => {
    image = p.loadImage("./0.jpg");
  };
  p.setup = () => {
    p.createCanvas(p.windowWidth, p.windowHeight);
    image.loadPixels();
    // 画像の全ピクセルを走査
    for (let y = 0; y < image.height; y++) {
      for (let x = 0; x < image.width; x++) {
        // 対象のピクセルを取り出す
        const color = getPixel(x, y);
        // 取り出したピクセルからRGBを抽出
        const r = p.red(color);
        const g = p.green(color);
        const b = p.blue(color);
        // ベースとなる色と今取り出したピクセルの色で二点間距離を求める
        const cr = br - r;
        const cg = bg - g;
        const cb = bb - b;
        const v = p.sqrt(cr * cr + cg * cg + cb * cb);
        // 前もって決めておいたしきい値より大きければ似ていないと判断
        // ピクセルの色を背景色に変更する
        if (threshold < v) {
          setPixel(x, y, [0, 0, 255]);
        }
      }
    }
    image.updatePixels();
    p.image(image, 0, 0);
  };
  function getPixel(x: number, y: number): number[] {
    const i = (y * image.width + x) * 4;
    return [
      image.pixels[i],
      image.pixels[i + 1],
      image.pixels[i + 2],
      image.pixels[i + 3],
    ];
  }
  function setPixel(x: number, y: number, color: number[]): void {
    const i = (y * image.width + x) * 4;
    image.pixels[i + 0] = color[0];
    image.pixels[i + 1] = color[1];
    image.pixels[i + 2] = color[2];
  }
});