简体   繁体   中英

treshould filter in Aforge doesn't seem to work properly

hope you all doing well. I did write a bit of codes in C# using Aforge library. I wanted to crop my main image captured from webcam so as to have a nice ROI. When I use threshold value of 0 everything should be in white pixels (total of lets say 26880 pixels) but it seems that I have some black pixels (578 pixels) within my cropped image. any idea of what may caused it? when I don't crop my image everything is fine.

            Bitmap img = (Bitmap)eventArgs.Frame.Clone(); 
            Bitmap bmp = new Bitmap(x2box, y2box); 
            bmp = img.Clone(new Rectangle(x1box, y1box, x2box, y2box), eventArgs.Frame.PixelFormat); 
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721); 
            Bitmap img1 = filter.Apply(bmp);
            Threshold tresh = new Threshold((int)tresh1);      // tresh1 is 0-255 but is set to zero here
            tresh.ApplyInPlace(img1);   
            int iterator = 1; int xrow = 0;      // here i use these constant to calculate location of the pixels
            byte[] arraybyte = BitmapToByteArray(img1);      
            for (int i = 0; i < arraybyte.Length; i++)
            {
                if (i - iterator * img1.Width == 0)
                {
                    xrow++;
                    iterator++;
                }
                if (arraybyte[i] == 0) // if pixel is black
                {
                    X_val.Add(i - xrow * img1.Width);
                    Y_val.Add(iterator);
                }
            }

            for (int i = 0; i < X_val.Count; i++)
            {
                YAve += Y_val[i];
                XAve += X_val[i];
            }
            MessageBox.Show(X_val.Count.ToString()); // shows non-zero value!

the BitmapToByteArray method is as follow:

 public static byte[] BitmapToByteArray(Bitmap bitmap)
    {

        BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
        int numbytes = bmpdata.Stride * bitmap.Height;
        byte[] bytedata = new byte[numbytes];
        IntPtr ptr = bmpdata.Scan0;
        Marshal.Copy(ptr, bytedata, 0, numbytes);
        bitmap.UnlockBits(bmpdata);
        return bytedata;

    }

The number of bytes for each row of the Bitmap will be enforced to be a multiple of 4. If roi width * bytes per pixel is not a multiple of 4, you will have padding bytes at the end of each row.

They will not be thresholded as they aren't really part of the Bitmap, so their value may be 0. Your BitmapToByteArray method might not be padding-aware and read every byte.

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