首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取图像值总计

获取图像值总计
EN

Code Review用户
提问于 2021-11-02 15:38:06
回答 1查看 566关注 0票数 4

下面是我的代码:

代码语言:javascript
运行
复制
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;
}

下面的代码返回图像中每个像素的总价值。有办法加快手术速度吗?谢谢你的帮助。

EN

回答 1

Code Review用户

回答已采纳

发布于 2021-11-02 17:49:29

位图数据存储在非托管GDI对象中。每次调用GetPixel时,系统都需要访问该对象。您可以通过使用LockBits直接访问原始图像数据来加快速度。

代码语言:javascript
运行
复制
private double GetImageValue(Bitmap image)
{
    double imageValue = 0;

    // Lock the bitmap's bits.  
    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);

    // Get the address of the first line.
    var ptr = bmpData.Scan0;

    // Declare an array to hold the bytes of the bitmap.
    var bytes = Math.Abs(bmpData.Stride) * image.Height;
    var values = new byte[bytes];

    // Copy the RGB values into the array.
    System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);

    // Add the rgb values to ImageValue
    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];
        }
    }

    // Unlock the bits.
    image.UnlockBits(bmpData);

    return imageValue;
}
票数 8
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/269644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档