Theodoros80
Theodoros80

Reputation: 796

Looping through pixels excluding an area

I have the following code for looping pixels in an image:

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();
     }
}

The above works. What if i want to exclude an area of the image. The area is an area selected by the user,for example:

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

How i loop all pixels except the one i wrote above? Thank you!

Upvotes: 0

Views: 125

Answers (2)

yazan
yazan

Reputation: 610

I think you can do something like the following

        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();
            }
        }

Upvotes: 2

HABJAN
HABJAN

Reputation: 9338

Maybe write a function to test x and y like this:

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;
    }
}

and then use it like this:

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);

Upvotes: 2

Related Questions