C#,如何获取图像中特定区域的颜色

时间:2018-05-16 22:45:14

标签: c# image pixels

如何获得图像中具有5x5像素的区域的颜色。

int xPixel = 200; int yPixel = 100;                               
Bitmap myBitmap = new Bitmap(“C:/Users/admin/Desktop/image.png");  
Color pixelColor = myBitmap.GetPixel(xPixel, yPixel, 5, 5); 
MessageBox.Show(pixelColor.Name);

此代码不起作用! enter image description here

2 个答案:

答案 0 :(得分:0)

你可以使用这种扩展方法来获取图像区域中的主色,以防它们不完全相同

kubectl cp dataaccess:/data data/

然后您可以像

一样使用它
public static Color GetDominantColor(this Bitmap bitmap, int startX, int startY, int width, int height) {

    var maxWidth = bitmap.Width;
    var maxHeight = bitmap.Height;

    //TODO: validate the region being requested

    //Used for tally
    int r = 0;
    int g = 0;
    int b = 0;
    int totalPixels = 0;

    for (int x = startX; x < (startX + width); x++) {
        for (int y = startY; y < (startY + height); y++) {
            Color c = bitmap.GetPixel(x, y);

            r += Convert.ToInt32(c.R);
            g += Convert.ToInt32(c.G);
            b += Convert.ToInt32(c.B);

            totalPixels++;
        }
    }

    r /= totalPixels;
    g /= totalPixels;
    b /= totalPixels;

    Color color = Color.FromArgb(255, (byte)r, (byte)g, (byte)b);

    return color;
}

还有改进的余地,例如使用Color pixelColor = myBitmap.GetDominantColor(xPixel, yPixel, 5, 5); Point,甚至是Size

Rectangle

但这应该足以开始。

答案 1 :(得分:-1)

使用System.Drawing提供的实际绘图方法将给定区域的大小调整为1x1并获取其像素值的解决方案:

public static Color GetRectangleColor(Bitmap sourceBitmap, Int32 x, Int32 y, Int32 width, Int32 height)
{
    using(Bitmap onePix = new Bitmap(1,1, PixelFormat.Format24bppRgb))
    {
        using (Graphics pg = Graphics.FromImage(onePix)){
            pg.DrawImage(sourceBitmap,
                         new Rectangle(0, 0, 1, 1),
                         new Rectangle(x, y, width, height)),
                         GraphicsUnit.Pixel);
        return onePix.GetPixel(0, 0);
    }
}

但是,如果你一直在使用均匀颜色的方格,我个人不会打扰。只要避免任何可能的边缘消失,你就可以了:

public static Color GetRectangleCenterColor(Bitmap sourceBitmap, Int32 x, Int32 y, Int32 width, Int32 height)
{
    return sourceBitmap.GetPixel(x + (width / 2), y + (height / 2));
}