Search code examples
visual-studio-2010emgucv

Get values 1 or 0 of binary images


I have my code That consist: I open the images that I want to upload, then I convert it in grayscale and later in binary image. But I have a question. How do I get values (0,1) of binary image in order to create a matrix with that values with emgucv c#??

      OpenFileDialog Openfile = new OpenFileDialog();
      if (Openfile.ShowDialog() == DialogResult.OK)
      {
          Image<Gray, Byte> My_Image = new Image<Gray, byte>(Openfile.FileName);
          pictureBox1.Image = My_Image.ToBitmap();

          My_Image = My_Image.ThresholdBinary(new Gray(69), new Gray(255));
          pictureBox2.Image = My_Image.ToBitmap();


      }
  }

Solution

  • Second Post

    I think I misunderstood the question, sorry for giving wrong info. But I think you may get some understanding from this post? Work with matrix in emgu cv


    First post

    By passing your My_Image which is result after ThresholdBinary() to following function, you can have array of zero and one only about the binary image.

    public int[] ZeroOneArray(Image<Gray, byte> binaryImage)
    {
        //get the bytes value after Image.ThresholdBinary() 
        //either 0 or 255
        byte[] imageBytes = binaryImage.Bytes;
        //change 255 to 1 and remain 0
        var binary_0_Or_255 = from byteInt in imageBytes select byteInt / 255;
        //convert to array
        int[] arrayOnlyOneOrZero = binary_0_Or_255.ToArray();
        //checking the array content
        foreach (var bin in arrayOnlyOneOrZero)
        {
            Console.WriteLine(bin);
        }
        return arrayOnlyOneOrZero;
    }
    

    Is this what you want? thanks


    Third Post

    By understanding this, chris answer in error copying image to array, I write a function for you to transfer your gray binary image to gray matrix image

    public Image<Gray, double> GrayBinaryImageToMatrixImage(Image<Gray, byte> binaryImage)
    {
        byte[] imageBytes = binaryImage.Bytes;
        Image<Gray, double> gray_image_div = new Image<Gray, double>(binaryImage.Size);//empty image method one
        //or
        Image<Gray, double> gray_image_div_II = binaryImage.Convert<Gray, double>().CopyBlank();//empty image method two
    
        //transfer binaryImage array to gray image matrix
        for (int i = 0; i < binaryImage.Width; i++)
        {
                for (int j = 0; j < binaryImage.Height; j++)
                {
                    if (imageBytes[i*binaryImage.Width+j] == 0)
                    {
                        //grey image only one channel
                        gray_image_div.Data[i, j, 0] = 0;
                    }
                    else if (imageBytes[i*binaryImage.Width+j] == 255)
                    {
                        gray_image_div.Data[i, j, 0] = 255;
                    }
    
                }
            }
            return gray_image_div;
    }