1

我正在尝试使用此代码将相机的提要保存到 png,但它似乎无法正常工作:

void RecordAndSaveFrameTexture()
{
    if (mXr.ShouldUseRealityRGBATexture())
    {
        SaveTextureAsPNG(mXr.GetRealityRGBATexture(), mTakeDirInfo.FullName + "/texture_" + mFrameInfo.mFrameCount.ToString() + ".png");
    }
    else
    {
        SaveTextureAsPNG(mXr.GetRealityYTexture(), mTakeDirInfo.FullName + "/texture_y_" + mFrameInfo.mFrameCount.ToString() + ".png");
        SaveTextureAsPNG(mXr.GetRealityUVTexture(), mTakeDirInfo.FullName + "/texture_uv_" + mFrameInfo.mFrameCount.ToString() + ".png");
    }

}

public static void SaveTextureAsPNG(Texture2D aTexture, string aFullPath)
{
    byte[] bytes = aTexture.EncodeToPNG();
    System.IO.File.WriteAllBytes(aFullPath, bytes);
    Debug.Log("Image with Instance ID:" + aTexture.GetInstanceID() + "with dims of " + aTexture.width.ToString() + " px X " + aTexture.height + " px " + " with size of" + bytes.Length / 1024 + "Kb was saved as: " + aFullPath);
}

在非 ArCore android 上进行测试,我得到正确大小为 480 x 640 像素的黑色图像(带有随机彩色像素)。使用 ArCore,它是 0kb 黑色图像。

4

1 回答 1

1

直接从这些纹理创建图像不能正常工作,因为这些数据是在渲染有效图像之前传递XRCameraYUVShader的。XRARCoreCamera

一种选择是创建一个自定义版本,XRVideoController它提供对用于渲染相机馈送的材料的访问。从那里,您的代码可以这样修改:

void RecordAndSaveFrameTexture() {
  Texture2D src = xr.ShouldUseRealityRGBATexture()
      ? xr.GetRealityRGBATexture()
      : xr.GetRealityYTexture();

  RenderTexture renderTexture = new RenderTexture (src.width, src.height, 0, RenderTextureFormat.ARGB32);
  Graphics.Blit (null, renderTexture, xrMat);
  SaveTextureAsPNG(renderTexture, Application.persistentDataPath + "/texture.png");
}

public static void SaveTextureAsPNG(RenderTexture renderTexture, string aFullPath) {
  Texture2D aTexture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
  RenderTexture.active = renderTexture;
  aTexture.ReadPixels(new Rect(0, 0, aTexture.width, aTexture.height), 0, 0);
  RenderTexture.active = null;

  byte[] bytes = aTexture.EncodeToPNG();
  System.IO.File.WriteAllBytes(aFullPath, bytes);
}

xrMat用于渲染相机馈送的材质在哪里。

这将给出一个没有任何 Unity 游戏对象的相机图像。如果您希望游戏对象显示在保存的图像中,您可以覆盖OnRenderImage以实现:

void OnRenderImage(RenderTexture src, RenderTexture dest) {
    if (shouldSaveImageFrame) {
      SaveTextureAsPNG(src, Application.persistentDataPath + "/_rgbatexture.png");
      shouldSaveImageFrame = false;
    }
    Graphics.Blit (src, dest);
}

shouldSaveImageFrame您在其他地方设置的标志在哪里,以防止图像被保存在每一帧上。

于 2018-04-05T21:59:08.287 回答