Save Camera image from unity ARCore

2019-06-11 02:34发布

问题:

This is in relation to this post Save AcquireCameraImageBytes() from Unity ARCore to storage as an image

I tried the steps mentioned by @JordanRobinson I am having a similar issue of seeing just a gray square. I keep re-reading his update, and I am not clear how step 2 (creating a texture reader) ties to step 3. I added the update function to call Frame.CameraImage.AcquireCameraImageBytes. I think missing something.

I feel I am close as it is saving an image (just a gray nothing image :-) Any help you can offer will be greatly appreciated

Here is my code

private Texture2D m_TextureRender; 
private TextureReader m_CachedTextureReader;  



void Start ()
    {
        m_CachedTextureReader = GetComponent<TextureReader>();
        m_CachedTextureReader.OnImageAvailableCallback += OnImageAvailable;
        QuitOnConnectionErrors ();
    }

void Update () {

    Screen.sleepTimeout = SleepTimeout.NeverSleep;

    using (var image = Frame.CameraImage.AcquireCameraImageBytes())
    {
        if (!image.IsAvailable)
        {
            return;
        }

        OnImageAvailable(TextureReaderApi.ImageFormatType.ImageFormatColor,
            image.Width, image.Height, image.Y, 0);
    }

}



private void OnImageAvailable(TextureReaderApi.ImageFormatType format, int width, int height, System.IntPtr pixelBuffer, int bufferSize)
{

    if (format != TextureReaderApi.ImageFormatType.ImageFormatColor)
    {
        Debug.Log("No edge detected due to incorrect image format.");
        return;
    }

    if (m_TextureRender == null || m_EdgeDetectionResultImage == null || m_TextureRender.width != width || m_TextureRender.height != height)
    {
        m_TextureRender = new Texture2D(width, height, TextureFormat.RGBA32, false, false);
        m_EdgeDetectionResultImage = new byte[width * height * 4];
        m_TextureRender.width = width;
        m_TextureRender.height = height;
    }

    System.Runtime.InteropServices.Marshal.Copy(pixelBuffer, m_EdgeDetectionResultImage, 0, bufferSize);

    // Update the rendering texture with the sampled image.
    m_TextureRender.LoadRawTextureData(m_EdgeDetectionResultImage);
    m_TextureRender.Apply();

    var encodedJpg = m_TextureRender.EncodeToJPG();
    var path = Application.persistentDataPath;

    File.WriteAllBytes(path + "/test2.jpg", encodedJpg);
}