gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:44:10 26 4
gpt4 key购买 nike

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

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com