【问题标题】:Get total image value获取图像总价值
【发布时间】:2021-12-17 04:10:01
【问题描述】:

下面是我的代码:

private double GetImageValue(Bitmap Image)
{
    double ImageValue = 0;

    for (int X = 0; X < Image.Width; X++)
    {
        for (int Y = 0; Y < Image.Height; Y++)
        {
            Color CurrentPixel = Image.GetPixel(X, Y);

            ImageValue += CurrentPixel.A + CurrentPixel.B + CurrentPixel.G + CurrentPixel.R;
        }
    }
    return ImageValue;
}

代码返回图像中每个像素的总值。有没有办法加快这个过程?

【问题讨论】:

  • 并行化双 for 循环
  • 尝试使用LockBits 并一次性读取整个数组
  • @Charlieface 请您提供使用 lockbits 的代码,而不是代码当前正在执行的操作。
  • 多线程 (OpenMP?) 将域切成宽的水平条纹,分布在内核之间。 -- 确保编译器产生 SSE/AVX/... 向量指令
  • @ChristophRackwitz 请您提供多线程代码。谢谢。

标签: c# image-processing


【解决方案1】:

类似这样的:

private double GetImageValue(Bitmap image)
{
double imageValue = 0;

var rect = new Rectangle(0, 0, image.Width, image.Height);
var bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var ptr = bmpData.Scan0;
var bytes = Math.Abs(bmpData.Stride) * image.Height;
var values = new byte[bytes];

System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);

for (int y = 0; y < image.Height; y++)
{
    int lineStart = y * Math.Abs(bmpData.Stride);
    for (int x = 0; x < image.Width * 3; x++)
    {
        imageValue += values[lineStart + x];
    }
}
image.UnlockBits(bmpData);
return imageValue;
}

【讨论】:

  • 欢迎来到 Stack Overflow,感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地了解正在发生的事情,尤其是那些刚接触该语言并难以理解概念的社区成员。
猜你喜欢
  • 2022-01-06
  • 2020-07-20
  • 1970-01-01
  • 2021-06-28
  • 2019-07-24
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 2014-03-02
相关资源
最近更新 更多