首页 > 解决方案 > 实时捕获 Unity 像素数据的最佳选择是什么?

问题描述

重点:

我一直在尝试优化一个系统,该系统需要在返回数据之前捕获屏幕的像素信息并进行一些计算(可能在计算着色器中?)。

语境:

在我阅读的所有地方,我看到很多人在谈论 Unity 的“x.ReadPixels()”方法效率不高,因为它必须将信息从 GPU 传递到 CPU,从而成为大规模调用的瓶颈。然而,这是我发现从 Unity 相机捕获像素信息的唯一方法。也许它可以直接从计算着色器链接到?

设想:

    private Texture2D texture;

    internal List<KeyValuePair<int, double>> ProcessTextureData(RenderTexture textureData, List<int> characterID, float multiplier)
    {
        if (texture is null)
            texture = new Texture2D(textureData.width, textureData.height, TextureFormat.RGBAHalf, false);

        RenderTexture.active = textureData;
        texture.ReadPixels(new Rect(0, 0, textureData.width, textureData.height), 0, 0);
        texture.Apply();

        if (texture != null && characterID.Count > 0)
        {
            List<KeyValuePair<int, double>> result = new List<KeyValuePair<int, double>>();
            Color[] colors = texture.GetPixels();
            int blockSize = (texture.width * texture.height) / characterID.Count;

            foreach (int cID in characterID)
            {
                if (DataHelper.GetCountIO(cID, 'I') > 0)
                {
                    double value = 0;
                    Color[] colors = new Color[blockSize];

                    for (int c = 0; c < colors.Length; c++)
                    {
                        if (c < blockSize)
                            colors[c] = colors[c];
                        else
                            break;
                    }

                    for (int i = 0; i < colors.Length; i++)
                    {
                        value += -(colors[i].r * 0.21) + -(colors[i].g * 0.72) + -(colors[i].b * 0.7);
                    }

                    value /= colors.Length;

                    result.Add(new KeyValuePair<int, double>(cID, -value * multiplier));
                }
            }

            return result;
        }
        else
            return new List<KeyValuePair<int, double>>();
    }

最后注:

我现在正在学习计算着色器,感觉它有助于优化这个功能,但是我在完全转换数据并在计算着色器中使用它时遇到了麻烦。

标签: c#unity3dmemory-managementhlslcompute-shader

解决方案


推荐阅读