将图像转换为灰度并行循环

3

我写了一段将图像转换为灰度的代码,但是该代码只能部分转换。我正在尝试将此代码转换为并行计算。但是我遇到了无法理解的错误。有什么建议吗?

    private void button2_Click(object sender, EventArgs e)
    {

        Bitmap bmp = (Bitmap)pictureBox1.Image;
        unsafe {
            //get image dimension
            //int width = bmp.Width;
            //int height = bmp.Height;


            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);

            //define variable
            int bpp = System.Drawing.Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
            int hip = bitmapData.Height;
            int wib = bitmapData.Width + bpp;

            //point to first pixel
            byte* PtrFirstPixel = (byte*)bitmapData.Scan0;
            //color of pixel
           // Color p;

            //grayscale

            Parallel.For(0, hip, y =>
            {
                byte* currentLine = PtrFirstPixel + (y * bitmapData.Stride);
                for (int x = 0; x < wib; x = x + bpp)
                {
                    //get pixel value
                    //p = bmp.GetPixel(x, y);

                    //extract pixel component ARGB
                    //int a = p.A;
                    //int r = p.R;
                    //int g = p.G;
                    // int b = p.B;
                    int b = currentLine[x];
                    int g = currentLine[x + 1];
                    int r = currentLine[x + 2];



                    //find average
                    int avg = (r + g + b) / 3;

                    //set new pixel value
                    // bmp.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg));
                    currentLine[x] = (byte)avg;
                    currentLine[x + 1] = (byte)avg;
                    currentLine[x + 2] = (byte)avg;


                }


            });

            bmp.UnlockBits(bitmapData);



            //load grayscale image in picturebox2
            //pictureBox2.Image = bmp;




        }
        pictureBox2.Image = bmp;

    }

my out put image


如果去掉并行循环部分,它是否仍然处理整个图像?如果不是,我会先让它正常工作,而不必担心线程问题。 - Michael Dorgan
让 x 去 bmp.Width,不是 wib! - TaW
一个断言,即bpp == 3会很好,因为你在很大程度上依赖这个断言是真的。 - Michael Dorgan
1个回答

2
int wib = bitmapData.Width + bpp;

should be:

int wib = bitmapData.Width * bpp;

您需要进行乘法运算而不是加法运算才能得到所需的字节数。可能还有其他问题,但这绝对是不正确的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接