使用Unity和ARCore的新版本1.1,API提供了一些获取相机信息的新方法。然而,我找不到任何好的例子将其保存为本地存储的文件,例如jpg格式。
ARCore示例提供了一个很好的示例,在此处检索相机数据,然后进行一些操作:https://github.com/google-ar/arcore-unity-sdk/blob/master/Assets/GoogleARCore/Examples/ComputerVision/Scripts/ComputerVisionController.cs#L212 该类中有一些检索相机数据的示例,但没有关于保存数据的内容。
我看到了这个:如何使用Unity ARCore SDK拍摄和保存图片/屏幕截图? 它使用了旧的API方式获取数据,并且对保存也没有详细说明。
我理想中希望的是一种方法,能够通过Unity将API中
ARCore示例提供了一个很好的示例,在此处检索相机数据,然后进行一些操作:https://github.com/google-ar/arcore-unity-sdk/blob/master/Assets/GoogleARCore/Examples/ComputerVision/Scripts/ComputerVisionController.cs#L212 该类中有一些检索相机数据的示例,但没有关于保存数据的内容。
我看到了这个:如何使用Unity ARCore SDK拍摄和保存图片/屏幕截图? 它使用了旧的API方式获取数据,并且对保存也没有详细说明。
我理想中希望的是一种方法,能够通过Unity将API中
Frame.CameraImage.AcquireCameraImageBytes()
的数据转换为存储在磁盘上的jpg格式。
更新
我后来主要是通过查看ARCore github页面上的这个问题https://github.com/google-ar/arcore-unity-sdk/issues/72#issuecomment-355134812并修改下面Sonny的答案才解决了这个问题,所以公平起见,我接受了他的回答。
如果有其他人也在尝试这个,我必须执行以下步骤:
Add a callback to the Start method to run your
OnImageAvailable
method when the image is available:public void Start() { TextureReaderComponent.OnImageAvailableCallback += OnImageAvailable; }
Add a TextureReader (from the computer vision example provided with the SDK) to your camera and your script
Your
OnImageAvailable
should look a bit like this:/// <summary> /// Handles a new CPU image. /// </summary> /// <param name="format">The format of the image.</param> /// <param name="width">Width of the image, in pixels.</param> /// <param name="height">Height of the image, in pixels.</param> /// <param name="pixelBuffer">Pointer to raw image buffer.</param> /// <param name="bufferSize">The size of the image buffer, in bytes.</param> private void OnImageAvailable(TextureReaderApi.ImageFormatType format, int width, int height, IntPtr pixelBuffer, int bufferSize) { if (m_TextureToRender == null || m_EdgeImage == null || m_ImageWidth != width || m_ImageHeight != height) { m_TextureToRender = new Texture2D(width, height, TextureFormat.RGBA32, false, false); m_EdgeImage = new byte[width * height * 4]; m_ImageWidth = width; m_ImageHeight = height; } System.Runtime.InteropServices.Marshal.Copy(pixelBuffer, m_EdgeImage, 0, bufferSize); // Update the rendering texture with the sampled image. m_TextureToRender.LoadRawTextureData(m_EdgeImage); m_TextureToRender.Apply(); var encodedJpg = m_TextureToRender.EncodeToJPG(); var path = Application.persistentDataPath; File.WriteAllBytes(path + "/test.jpg", encodedJpg); }
Texture2D
的彩色图像吗?我想缩小问题范围,确定是AcquireCameraImageBytes()
步骤、LoadRawTextureData()
和Apply()
步骤,还是最终的EncodeToJpg()
和WriteAllBytes()
步骤出了问题。 - sonnyb