首页 > 解决方案 > 如何修改此脚本以连续拍摄照片?

问题描述

我可以使用此脚本捕获单张照片。我应该如何修改此脚本以连续捕获照片以在 3D 平面上渲染?我想将该“targetTexture”连续传递给某个函数。

public class PhotoCaptureExample : MonoBehaviour
{
    PhotoCapture photoCaptureObject = null;

    // Use this for initialization
    void Start ()
    {
        PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
    }

    void OnPhotoCaptureCreated(PhotoCapture captureObject)
    {
        photoCaptureObject = captureObject;

        Resolution cameraResolution = PhotoCapture.SupportedResolutions
            .OrderByDescending((res) => res.width * res.height).First();

        CameraParameters c = new CameraParameters();
        c.hologramOpacity = 0.0f;
        c.cameraResolutionWidth = cameraResolution.width;
        c.cameraResolutionHeight = cameraResolution.height;
        c.pixelFormat = CapturePixelFormat.BGRA32;

        captureObject.StartPhotoModeAsync(c, OnPhotoModeStarted);
    }

    void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
    {
        photoCaptureObject.Dispose();
        photoCaptureObject = null;
    }

    private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
    {
        if (result.success)
        {
            photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
        }
        else
        {
            Debug.LogError("Unable to start photo mode!");
        }
    }

    void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, 
        PhotoCaptureFrame photoCaptureFrame)
    {
        if (result.success)
        {
            // Create our Texture2D for use and set the correct resolution
            Resolution cameraResolution = PhotoCapture.SupportedResolutions
                .OrderByDescending((res) => res.width * res.height).First();
            Texture2D targetTexture = new Texture2D(cameraResolution.width, 
                cameraResolution.height);

            // Copy the raw image data into our target texture
            photoCaptureFrame.UploadImageDataToTexture(targetTexture);
            // Do as we wish with the texture such as apply it to a material, etc.
        }
        // Clean up
        photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
    }

    // Update is called once per frame
    void Update () 
    {           
    }
}

标签: c#unity3d

解决方案


Afaik 您不能TakePhotoAsync每帧都进行新调用,而必须等到当前进程完成。这是为了表现激烈,afaik 还获得了访问相机设备的独占权限,因此任何其他调用同时失败。


为了等到下一张照片完成之前,OnCapturedPhotoToMemory您可以简单地代替

photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);

呼叫下一张照片

photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);

也许你应该在它之前添加一个退出条件,private bool shouldStop就像

if(shouldStop)
{
    photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
else
{
    photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
}

但是,请注意,这会大大降低您的应用程序的速度!由于大多数Texture2D事情都发生在主线程上并且性能非常密集!


推荐阅读