酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

グレースケール変換

分割した記事で書かれていたのを「Windowsストアアプリで画像処理をおこなう - 酢ろぐ!」とひとつのエントリにまとめました。以下のエントリをご覧ください。

本記事では「ネガティブ(ネガポジ反転)変換 - 酢ろぐ!」で紹介したIEffectインターフェースをベースにして、グレースケール処理を実装します。

グレースケール画像は白から黒への256階調で表現されています。カラー画像からグレースケール画像を得るのに一番簡単なのは単純平均法ですね。Windows Mobile時代の説明ですが「第8回 Windows phoneで画像エフェクトアプリを作ろう!(1):Windows Phoneアプリケーション開発入門|gihyo.jp … 技術評論社」に以前書いたことがあるのでご覧ください。


|cs| // GrayscaleEffect.cs

using System;

namespace Softbuild.Media.Effects { public class GrayscaleEffect : IEffect { public byte Effect(int width, int height, byte source) { int pixelCount = width * height; var dest = new byte[source.Length];

        for (int i = 0; i < pixelCount; i++)
        {
            var index = i * 4;

            // 単純平均法で輝度を求める
            var sum = source[index + 0] + source[index + 1] + source[index + 2];
            var y = (double)sum / 3;

            dest[index + 0] = (byte)Math.Min(255, Math.Max(0, y));
            dest[index + 1] = (byte)Math.Min(255, Math.Max(0, y));
            dest[index + 2] = (byte)Math.Min(255, Math.Max(0, y));
            dest[index + 3] = source[index + 3];
        }

        return dest;
    }
}

} ||<