15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

canvasとD3.jsで画像の輝度ヒストグラムをつくる

Last updated at Posted at 2014-07-10

輝度のヒストグラム

画像の明るさや品質を調べるために、画像の輝度の分布状況をヒストグラムを取ることがあります。
YUVのYを計算しその値ごとをカウントしてD3.jsでグラフを出力しようと思います。

histogram.html
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-2.1.1.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
function drawGraph(ys) {
    //d3.js でグラフを描画する。

    //グラフを描画するSVGを用意
    var w = 500;
    var h = 300;
    var barPadding = 1;
    var svg = d3.select("body")
                 .append("svg")
                 .attr("width", w)
                 .attr("height", h);

    //受け取ったデータを元にヒストグラムを作成する
    svg.selectAll("rect")
        .data(ys)
        .enter()
        .append("rect")
        .attr("x", function(d, i) {
            return i * (w/ys.length);
        })
        .attr("y", function(d) {
            return h - d/8;
        })
        .attr("width", w/ys.length - barPadding)
        .attr("height", function(d) {
            return d/8;
        });
}

function fail(e) {
    //エラーの時のメソッド
    alert(e);
}

function getYArray(data) {
    var ys = new Array(256);
    for (var i = 0; i < ys.length;i++) {
        ys[i] = 0;
    }

    for (var i = 0; i < data.length; i= i + 4) {
        // 輝度(YUVのY)の計算を行う
        var y = ~~(0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]);
        // 輝度の値ごとのカウント
        ys[y]++;
    }
    return ys;
}

function calcY() {    
    var dfd = new $.Deferred;

    var canvas = document.getElementById("c1");
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.src = "test.jpg";
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        var imagedata = ctx.getImageData(0, 0, canvas.width, canvas.height);
        var ys = getYArray(imagedata.data);
        dfd.resolve(ys);
    };
    return dfd.promise();
}

window.onload = function() {    
    calcY().then(drawGraph, fail);
};
</script>
</head>
<body>
<canvas id="c1" width="300" height="300">
</body>
</html>

いろいろな画像の結果を以下に示します。
暗い画像ほど左(0に近いほう)の値が大きくなっているのがわかります。

histogram1.png

histogram2.png

histogram3.png

15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?