循环除了区域之外的像素

时间:2014-04-09 08:16:52

标签: c#

我有以下代码用于循环图像中的像素:

Bitmap myBitmap = new Bitmap(pictureBox1.Image);  
for (x = 0; x < pictureBox1.Image.Width; x += 1) 
{
     for (y = 0; y < pictureBox1.Image.Height; y += 1)
     {
          Color pixelColor = myBitmap.GetPixel(x, y);
          aws = pixelColor.GetBrightness();
     }
}

以上作品。如果我想要排除图像区域该怎么办?该区域是用户选择的区域,例如:

from x=200&y=30 to x=250&y=30
from x=200&y=35 to x=250&y=35
from x=200&y=40 to x=250&y=40
from x=200&y=45 to x=250&y=45

除了我上面写的那个外,我如何循环所有像素? 谢谢!

2 个答案:

答案 0 :(得分:2)

也许写一个函数来测试x和y,如下所示:

public static bool IsInArea(int testx, int testy, int x1, int y1, int x2, int y2)
{
    if (testx > x1 && testx < x2 && testy > y1 && testy < y2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

然后像这样使用它:

BitmapData bmd = myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height),
                                    System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                    myBitmap.PixelFormat);

int PixelSize = 4;

unsafe
{
    for (int y = 0; y < bmd.Height; y++)
    {
        byte* row = (byte*)bmd.Scan0 + (y * bmd.Stride);

        for (int x = 0; x < bmd.Width; x++)
        {
            if (!IsInArea(x, y, 200, 30, 250, 30))
            {
                int b = row[x * PixelSize];         //Blue
                int g = row[x * PixelSize + 1];     //Green
                int r = row[x * PixelSize + 2];     //Red
                int a = row[x * PixelSize + 3];     //Alpha

                Color c = Color.FromArgb(a, r, g, b);

                float brightness = c.GetBrightness();
            }

        }
    }
}

myBitmap.UnlockBits(bmd);

答案 1 :(得分:2)

我认为您可以执行以下操作

        Rectangle rectToExclude = new Rectangle(200, 30, 250, 30);//rectangle to be excluded
        Bitmap myBitmap = new Bitmap(pictureBox1.Image);
        for (x = 0; x < pictureBox1.Image.Width; x += 1)
        {
            for (y = 0; y < pictureBox1.Image.Height; y += 1)
            {
                if (rectToExclude.Contains(x, y)) continue; // if in the exclude rect then continue without doing any effects
                Color pixelColor = myBitmap.GetPixel(x, y);
                aws = pixelColor.GetBrightness();
            }
        }