色をテストする単純なアルゴリズム: ネストされた for ループ (幅と高さ) で画像をピクセルごとに移動し、ピクセルの RGB 値が等しいかどうかをテストします。そうでない場合、画像には色情報があります。この状態に遭遇せずにすべてのピクセルを通過すると、グレースケールの画像になります。
より複雑なアルゴリズムによるリビジョン:
この投稿の最初のリビジョンでは、各ピクセルの RGB 値が等しい場合にピクセルがグレースケールであると仮定する単純なアルゴリズムを提案しました。したがって、0,0,0 または 128,128,128 または 230,230,230 の RGB はすべてグレーとしてテストされますが、123,90,78 はテストされません。単純。
グレーからの差異をテストするコードのスニペットを次に示します。2 つの方法は、より複雑なプロセスの小さなサブセクションですが、元の質問を解決するのに十分な未加工のコードを提供する必要があります。
/// <summary>
/// This function accepts a bitmap and then performs a delta
/// comparison on all the pixels to find the highest delta
/// color in the image. This calculation only works for images
/// which have a field of similar color and some grayscale or
/// near-grayscale outlines. The result ought to be that the
/// calculated color is a sample of the "field". From this we
/// can infer which color in the image actualy represents a
/// contiguous field in which we're interested.
/// See the documentation of GetRgbDelta for more information.
/// </summary>
/// <param name="bmp">A bitmap for sampling</param>
/// <returns>The highest delta color</returns>
public static Color CalculateColorKey(Bitmap bmp)
{
Color keyColor = Color.Empty;
int highestRgbDelta = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
if (GetRgbDelta(bmp.GetPixel(x, y)) <= highestRgbDelta) continue;
highestRgbDelta = GetRgbDelta(bmp.GetPixel(x, y));
keyColor = bmp.GetPixel(x, y);
}
}
return keyColor;
}
/// <summary>
/// Utility method that encapsulates the RGB Delta calculation:
/// delta = abs(R-G) + abs(G-B) + abs(B-R)
/// So, between the color RGB(50,100,50) and RGB(128,128,128)
/// The first would be the higher delta with a value of 100 as compared
/// to the secong color which, being grayscale, would have a delta of 0
/// </summary>
/// <param name="color">The color for which to calculate the delta</param>
/// <returns>An integer in the range 0 to 510 indicating the difference
/// in the RGB values that comprise the color</returns>
private static int GetRgbDelta(Color color)
{
return
Math.Abs(color.R - color.G) +
Math.Abs(color.G - color.B) +
Math.Abs(color.B - color.R);
}