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

标签 c# multithreading image image-processing grayscale

我编写了一个将图像转换为灰度的代码。但代码只转换其中的一部分。 我正在尝试将此代码转换为并行计算。我最终遇到了一些我无法理解的错误。有什么建议吗?

    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

最佳答案

int wib = bitmapData.Width + bpp;

应该是:

int wib = bitmapData.Width * bpp;

您想要的是需要乘法而不是加法的字节数。可能还有其他问题,但这绝对是不正确的。

关于c# - 将图像转换为灰度并行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43878144/

相关文章:

c# - 通过 POST Multipart (HTTPRequest) 发送图像

c# - .NET 进程的内存转储中存在大量无法解释的内存

c++ - 调用 std::condition_variable 后因无效参数导致应用程序崩溃

c++ - 一张一张打开图片

python - 如何在python中使用Matlab的imresize

c# - "For"循环增量无法正常工作。为什么?

c# - LoadControlState 没有被解雇

java - java 8流和并行流之间的区别

c++ - 如何在 C++ 中正确创建线程类的子类(std::thread 的子类)

javascript - 通过手机加载时, Canvas 图像将图像旋转 90 度