【问题标题】:Get pixel data from image UWP从图像 UWP 中获取像素数据
【发布时间】:2018-12-10 13:03:59
【问题描述】:

我正在编写一个简单的工具,用户可以选择一张图片,它应该列出图片中找到的所有颜色。

现在,我面临两个主要问题,一个是速度很慢,因为我正在循环遍历图像中的所有像素。 其次,我得到了意想不到的结果。

第一件事,代码:

    public static async Task<List<ImageColor>> GetImageColorsAsync(StorageFile image)
    {
        List<ImageColor> colors = new List<ImageColor>();

        var imagestream = await image.OpenStreamForReadAsync(); // Convert image to stream
        var imageDecoder = await BitmapDecoder.CreateAsync(imagestream.AsRandomAccessStream()); // decode stream
        var imagePixelData = await imageDecoder.GetPixelDataAsync(); // get information about pixels
        var bytes = imagePixelData.DetachPixelData(); // get pixel data

        for (int x = 0; x < imageDecoder.PixelWidth; x++)
        {
            for (int y = 0; y < imageDecoder.PixelHeight; y++)
            {
                var location = (y * (int)imageDecoder.PixelWidth + x) * 3; // Navigate to corresponding coordinates
                var color = Color.FromArgb(0, bytes[location + 0], bytes[location + 1], bytes[location + 2]); // Filter Red Green Blue and convert this to Argb

                // find if color already exsists from its hex code
                string hex = color.ToString();
                var prevColor = colors.FirstOrDefault(a => a.ColorCodeHex == hex);

                if (colors.Count == 0 || prevColor == null)
                {
                    // new color
                    ImageColor imgColor = new ImageColor()
                    {
                        R = color.R,
                        G = color.G,
                        B = color.B,
                        ColorCodeHex = hex,
                        Occurence = 1
                    };

                    colors.Add(imgColor);
                }
                else
                {
                    // exsisting color
                    prevColor.Occurence++;
                }
            }
        }


        return colors;
    }

现在,我真的需要遍历每个像素吗?

而且,我所做的是使用黑色图像(全黑)测试此功能,我得到的是那张图片中有 4 种颜色:黑色、红色、绿色和蓝色。

另外,当使用只是一些文本的屏幕截图的图像进行测试时(因此存在黑色、白色和一些黄色),结果是巨大的(几乎 1000 多种颜色),所以我的显然有问题方法

现在我找到 locationcolor 的行不是我的,我在网上找到了它们,我无法真正验证你应该这样做。

有什么帮助吗?

【问题讨论】:

    标签: c# image performance uwp


    【解决方案1】:

    首先,我手头没有 UWP 应用,但我认为您的正确性问题是因为您忽略了步幅。这个数字是系统用来表示一行的字节数,不是 3*width*y,而是通常更多,以便将行数据对齐到固定网格。

    其次,您确定您的图像是 3 通道而不是 4 (ARGB)?第四个通道至少可以解释为什么您在黑色图片中看到非零值,特别是因为您看到(#ff0000、#00ff00 和 #0000ff),所以您在意想不到的位置得到 ff。

    第三,在性能方面,使用字典或哈希集而不是列表是一个明智的决定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-01
      • 2011-09-25
      • 2013-06-06
      • 2021-03-29
      • 1970-01-01
      • 2013-01-24
      • 2013-07-21
      • 1970-01-01
      相关资源
      最近更新 更多