【问题标题】:treshould filter in Aforge doesn't seem to work properlyAforge 中的 treshould 过滤器似乎无法正常工作
【发布时间】:2014-12-06 03:18:40
【问题描述】:

希望你们一切都好。我确实使用 Aforge 库在 C# 中编写了一些代码。我想裁剪从网络摄像头捕获的主要图像,以获得良好的投资回报率。当我使用 0 的阈值时,所有内容都应该是白色像素(可以说是 26880 像素),但我的裁剪图像中似乎有一些黑色像素(578 像素)。知道是什么原因造成的吗?当我不裁剪图像时,一切都很好。

            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!

BitmapToByteArray 方法如下:

 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;

    }

【问题讨论】:

    标签: c# aforge threshold


    【解决方案1】:

    位图每行的字节数将强制为 4 的倍数。如果roi width * bytes per pixel 不是 4 的倍数,则每行末尾都有填充字节。

    它们不会被阈值化,因为它们实际上并不是位图的一部分,因此它们的值可能为 0。您的 BitmapToByteArray 方法可能无法识别填充并读取每个字节。

    【讨论】:

    • 谢谢,我认为这是问题所在,因为裁剪前图像的宽度是 4 的倍数。一个选项只让用户选择 4 的倍数,这可能不是最佳选择.有什么建议可以让我使用填充感知的方法吗?我将更新上面的代码以包含该方法。我想投票给你的答案,但我仍然需要更多的声誉:P
    • @maziar derakhshandeh:您可以遍历每一行,并仅复制 width * byte per pixel 字节而不是 stride。您可能必须使用不安全的代码。另一种方法是改变你的阅读循环。让它遍历行并在一行内只考虑最多width * byte per pixel 个字节。
    猜你喜欢
    • 2018-07-10
    • 2017-09-04
    • 2012-05-06
    • 2013-02-17
    • 2017-10-09
    • 2017-08-03
    • 2014-05-02
    • 2011-09-11
    • 2016-02-11
    相关资源
    最近更新 更多