< Back

画像から日本の伝統色を取り出してみるライブラリ作った

画像から日本の伝統色を取り出してみる

はじめに

こんにちわ、僕です。

今回は画像の中で専有している色を取り出す既存の rgbaster.js と、今回自分が作った traditionalColors.js を組み合わせてWebアプリを作ってみます。

成果物

イメージは以下にスクリーンショットを貼り付けましたが、画像の中の専有している色に近い「日本の伝統色」を返すという感じのWebアプリです。

スクリーンショット 2018-05-25 23.02.17.jpg

実際に動作する環境はこちらのGitHub.ioからどうぞ!!

「ファイルを選択」をクリックして適当な画像をブラウザにあげてみてください。そうするとJS/Canvasがごりごり動き出して色を判定してくれるはずです。

成果物2

イメージは以下にスクリーンショットを貼り付けましたがカラーピッカーを立ち上げて色を入力すると伝統色を返すWebアプリです。どうぞ遊んでみてください。 GitHub.io クリックできるのは上のほうのカラーピッカーだけです!

スクリーンショット 2018-05-26 0.20.00.jpg

コード的な話

コードは https://github.com/ykhirao/traditional-color/ です。

traditionalColor.js

;(function(window, undefined){
  "use strict";

  class TraditionalColors {
    constructor() {
      console.log("TraditionalColors is roaded !!!");
      this.colors = [] // 本当はここに伝統色のJSONが入っている
    }

    distance3D(a, b) {
      return Math.sqrt((Math.pow((a.r - b.r), 2) + Math.pow((a.g - b.g), 2) + Math.pow((a.b - b.b), 2)));
    }

    regExpToRgb(result, decimal=10) {
      const r = parseInt(result[1], decimal)
      const g = parseInt(result[2], decimal)
      const b = parseInt(result[3], decimal)
      return {r, g, b}
    }

    rgbStrToObj(str) {
      // from text "rgb(4,8,16)" to obj { r: 4, g: 8, a:16 }
      var result = /([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})/i.exec(str);
      return result ? this.regExpToRgb(result) : null;
    }

    hexToRgbObj(str){
      // "#1234aa" to { r: 12, g: 34, a: aa }
      var result = /([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})([a-zA-Z0-9]{2})/i.exec(str);
      return result ? this.regExpToRgb(result, 16) : null;
    }

    getNearColor(rgb) {
      let i = 0,
        approximationIndex = 0,
        minDiff = Math.abs(this.distance3D(this.colors[0].rgb, rgb)),
        diff;

      while (++i < this.colors.length) {
        diff = Math.abs(this.distance3D(this.colors[i].rgb, rgb));

        if (diff < minDiff) {
          minDiff = diff;
          approximationIndex = i;
        }
      }
      return this.colors[approximationIndex];
    }
  }

  window.TraditionalColors = window.TraditionalColors || TraditionalColors;
})(window);

以上がtraditionalColors.jsですが、見てわかるように大したことはしていません。すべての伝統色との距離測って近いのを返却しているだけです。

使い方は

index.html
<script src="./traditionalColors.js"></script> |
<script>
  const tc = new window.TraditionalColors();
  console.log(tc.getNearColor({r: 14, g: 12, b: 243}))
</script>

的な感じで、インスタンス変数を作ってメソッドを呼びせばいろいろ使えます。さくっと簡単なお遊びで作ったのですが、写真が趣味な人からすると結構楽しかったりします。

終わりに

rgbaster.js のソースコードを読むのは簡単でしたのでぜひ読んでみるといいかと思います。canvasの使い方も学べました。

参考

rgbaster.jsを使って画像の色を抽出してみよう | 株式会社LIG