【发布时间】:2020-04-12 09:21:40
【问题描述】:
我正在尝试提高用于将 png 转换为灰度的代码的性能。
我通过 Json 加载图像,转换为纹理,然后在运行时通过每个像素进行灰度化并使用 GetPixels32/SetPixels32。对于我拥有的许多图像,内存使用量太高,所以我想使用更高效的GetRawTextureData。
但是LoadImage 正在返回一个 ARGB32 texture2d,这似乎很混乱,然后在 GetRawTextureData (RGB32) 中继续使用。
这很令人困惑,因为在 Unity 2019.2 上带有 LoadImage 的 png 应该返回 RGBA32,但对我来说它返回的是 ARGB32,这是旧版 Unity 5.3 会返回的 LoadImage - 不确定是错误还是文档错误。
Texture2D thisTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
byte[] t = Convert.FromBase64String(imageString);//png image in string format
thisTexture.LoadImage(t);//Using Unity2019.2.2 result is ARGB32
当我将图像转换为灰度时,我得到一个黄色图像,我认为这是因为 GetRawTextureData 是 RGB32 但LoadImage 返回 ARGB32。
我如何复制LoadImage 过程来获得RGB32?
//convert texture
graph = thisTexture;
grayImg = new Texture2D(graph.width, graph.height, graph.format, false);
Debug.Log("grayImg format " + grayImg.format + " graph format " + graph.format);
Graphics.CopyTexture(graph, grayImg);
var data = grayImg.GetRawTextureData<Color32>();
int index = 0;
Color32 pixel;
for (int x = 0; x < grayImg.width; x++)
{
for (int y = 0; y < grayImg.height; y++)
{
pixel = data[index];
int p = ((256 * 256 + pixel.r) * 256 + pixel.b) * 256 + pixel.g;
int b = p % 256;
p = Mathf.FloorToInt(p / 256);
int g = p % 256;
p = Mathf.FloorToInt(p / 256);
int r = p % 256;
byte l = (byte) ((pixel.r ) + pixel.g + pixel.b);
Color32 c = new Color32(pixel.r, pixel.g, pixel.b, 1);
data[index++] = c;
}
}
// upload to the GPU
grayImg.Apply(false);
使用 LoadRawTextureData 修改代码:
Texture2D thisTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
byte[] t = Convert.FromBase64String(imageString);//png image in string format
thisTexture.LoadRawTextureData(t);//results in RGBA32 (Note: using either thisTexture.LoadImage(t); or thisTexture.LoadRawTextureData(t); when using LoadRawTextureData to set the pixels on the grayscale, the texture continues to be yellowish.
thisTexture.Apply();
【问题讨论】:
-
你的设备是什么?
-
在独立的 windows 和 ios 上测试构建,目标是在 iOS 上构建用于移动设备(ios13 及更高版本)和 iPad
-
您的代码缺少很多上下文。你在哪里定义changedPixels?为什么不使用 LoadRawTextureData 设置像素?
-
对不起,没有 changedPixels ,我已经编辑了代码。不使用 changedPixels,因为这是使用 GetRawTextureData 的版本。我不知道 LoadRawTextureData 我现在要测试!
-
你的图形 API 是什么?
标签: unity3d gpu textures texture2d loadimage