简体   繁体   中英

Converting a bitmap to an matrix

I've been trying to convert a bitmap object to a matrix of int. I drew the letter 'C' in paint on a blank white sheet and the program was supposed to initialize the arr in place (x,y) with '0' if the pixel in the Bitmap object in the same position (x,y) is white and correspondingly '1' if it were a black pixel.

I wrote the following code:

 static void Main(string[] args)
    {

          Bitmap arie = new Bitmap(@"C:\Users\User\Desktop\letter.bmp");
          object [,] arr = new object[arie.Width, arie.Height];
        int min=1000,counter=1;
        for (int i = 0; i < arr.GetLength(0) - 1; i++)
        {
            for (int j = 0; j < arr.GetLength(1) - 1; j++)
            {
                if (arie.GetPixel(i, j).ToArgb() == Color.White.ToArgb())
                {
                    arr[i, j] = 0;
                }
                else
                    arr[i, j] = 1;
            }
        }

          for (int i = 1; i < arr.GetLength(0) - 2; i++)
          {
              for (int j = 1; j < arr.GetLength(1) - 2; j++)
              {
                  Console.Write(arr[i, j]);
              }
              Console.WriteLine();
          }

    }

at the end the letter 'C' that I drew came out like this: http://teachers.web.cern.ch/teachers/archiv/hst2000/teaching/expt/wavesand/image39.gif

Can anyone seem to recognize the issue?

The main issue is that when you are outputting the array to the console, you are traversing it by columns, rather than rows. That is why your array appears to be rotated by 90 degrees.

If in the second looping portion (where you are outputting to the console), you swap the inner and outer loops, you should see better results.

I also agree with the other comments that: 1) If you want better performance, use the LockBits/UnlockBits method of accessing the Bitmap 2) Your loop indexing is out of whack

If you use x and y instead of i and j, it will help you recognize when you're making these kind of mistakes.

Try this:

static void Main(string[] args)
{
    Bitmap arie = new Bitmap(@"C:\Users\User\Desktop\letter.bmp");
    object [,] arr = new object[arie.Width, arie.Height];
    int min=1000,counter=1;
    for (int i = 0; i < arie.Width; i++)
    {
        for (int j = 0; j < arie.Height; j++)
        {
            if (arie.GetPixel(i, j).ToArgb() == Color.White.ToArgb())
            {
                arr[i, j] = 0;
            }
            else
                arr[i, j] = 1;
        }
    }

    for (int y = 0; y < arie.Height; y++)
    {
       for (int x = 0; x < arie.Width; x++)
       {
           Console.Write(arr[x, y]);
       }
       Console.WriteLine();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM