2014-06-30 497 views
14

我完全不熟悉Unity3D的更复杂的功能集,并且很好奇它是否具备拍照然后操作它的功能。具体而言,我的愿望是让用户拍摄自拍照,然后让他们追踪自己的脸部以创建PNG,然后将其纹理映射到模型上。我可以使用设备的相机在Unity中拍照吗?

我知道模型上的脸部映射很简单,但我想知道是否需要将照片/雕刻功能写入包含Chrome的应用程序,或者是否可以在Unity中完成。我不需要关于如何去做的教程,只是问是否有可能。

+0

对于2016年这里是如何做到这一点的全面解释... http://answers.unity3d.com/questions/909967/getting-a-web-cam-to-play-on-ui-texture-image .html#answer-910020 *** CRITICAL *** ...按照链接获取“魔术”代码,以便在iOS/Android上正确旋转,反转,旋转***图像。 – Fattie

回答

16

是的,这是可能的。您需要查看WebCamTexture功能。

您创建WebCamTexture并调用启动摄像头的Play()函数。 WebCamTexture与任何Texture一样,允许您通过GetPixels()调用获取像素。这允许您随时拍摄快照,并且可以将其保存在Texture2D中。致电EncodeToPNG()并随后写入文件应该可以让你在那里。

请注意,以下代码是基于文档的快速书写。我没有测试过它。如果有多个可用设备,则可能必须选择正确的设备。

using UnityEngine; 
using System.Collections; 
using System.IO; 

public class WebCamPhotoCamera : MonoBehaviour 
{ 
    WebCamTexture webCamTexture; 

    void Start() 
    { 
     webCamTexture = new WebCamTexture(); 
     renderer.material.mainTexture = webCamTexture; 
     webCamTexture.Play(); 
    } 

    void TakePhoto() 
    { 

    // NOTE - you almost certainly have to do this here: 

    yield return new WaitForEndOfFrame(); 

    // it's a rare case where the Unity doco is pretty clear, 
    // http://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html 
    // be sure to scroll down to the SECOND long example on that doco page 

     Texture2D photo = new Texture2D(webCamTexture.width, webCamTexture.height); 
     photo.SetPixels(webCamTexture.GetPixels()); 
     photo.Apply(); 

     //Encode to a PNG 
     byte[] bytes = photo.EncodeToPNG(); 
     //Write out the PNG. Of course you have to substitute your_path for something sensible 
     File.WriteAllBytes(your_path + "photo.png", bytes); 
    } 
} 
+0

现在如何处理相机旋转说一个Android设备时这样做? – Codejoy

+0

究竟是在这里处理@Codejoy?你想要发生什么? – Bart

+0

回复太晚了?我已经将代码分类,并将其附加到带有spriteRenderer的gameObject中。它启动相机,如果按下按钮但拍摄照片,但不显示实时视图....任何想法做错了? (在2D UI环境中工作) – Matt

6

对于那些试图让相机渲染活动饲料,这里是我如何设法把它关闭。首先,我编辑Bart的答案,让纹理将在更新分配,而不是仅仅在开始:

void Start() 
{ 
    webCamTexture = new WebCamTexture(); 
    webCamTexture.Play(); 
} 

void Update() 
{ 
    GetComponent<RawImage>().texture = webCamTexture; 
} 

然后接上脚本与RawImage分量的游戏对象。你可以在Unity Editor的Hierarchy中通过右键单击 - > UI - > RawImage轻松创建一个(这需要Unity 4.6及更高版本)。运行它应该在您的视图中显示相机的实时馈送。在撰写本文时,Unity 5支持在Unity 5的免费个人版中使用网络摄像头。

我希望这有助于任何想要在Unity中捕捉实时摄像头feed的人。

相关问题