将双目相机的实时视频流传入Unity3D中并且利用SteamVR插件传入到VR头盔中。
根据ZED Unity Plugin组件中的ZED_Rig_Stereo可以同等的使用SteamVR中的组件创建出属于我的水下双目相机的Rig_Stereo。
-
首先导入SteamVR插件,打开CameraRig这个预制体。创建一个空对象名字为Stereo_Camera,然后将Camera移动到Stereo_Camera之下作为左目相机,然后复制一个Camera作为右目相机。具体如下:
(2)将Stereo_Camera加入以下的SteamVR_Camera和SteamVR_Camera_Helper两个脚本,并且将目标眼睛选为无。
(3)将左右目相机的目标眼睛分别选为左和右,并且取消勾选SteamVR_Camera_Helper脚本,如下图:
- 创建LeftCanvas和RightCanvas这两个画布,并且给它们都创建一个RawImage作为子物体接收视频信号,并且渲染在其上。创建两个纹理分别用于渲染左右眼视频信号,具体如下:
编写一个名为StereoCameraRendering的脚本获取USB接口的双目相机视频信号并且将其渲染在纹理上,且在LeftCanvas的检查器栏中选择对应的左右眼虚拟相机将其视频流传输到VR头显中。
using UnityEngine;
using UnityEngine.UI; // 引入 UI 命名空间来使用 RawImagepublic class StereoCameraRendering : MonoBehaviour
{
public string cameraName = "USB Camera"; // 双目相机设备名称
public RawImage leftEyeRawImage; // 左眼 RawImage
public RawImage rightEyeRawImage; // 右眼 RawImageprivate WebCamTexture cameraTexture;
private int width;
private int height;void Start()
{
// 获取可用的摄像头设备列表
WebCamDevice[] devices = WebCamTexture.devices;foreach (var device in devices)
{
Debug.Log("Device found: " + device.name);
}// 假设设备名称是 "USB Camera" 作为双目相机
cameraTexture = new WebCamTexture(cameraName);if (cameraTexture != null)
{
width = cameraTexture.width;
height = cameraTexture.height;// 将 WebCamTexture 分配给 RawImage 的 texture
if (leftEyeRawImage != null)
{
leftEyeRawImage.texture = cameraTexture;
}if (rightEyeRawImage != null)
{
rightEyeRawImage.texture = cameraTexture;
}// 启动摄像头
cameraTexture.Play();
}
else
{
Debug.LogError("Camera not found!");
}
}void Update()
{
// 每帧更新 WebCamTexture
if (cameraTexture.didUpdateThisFrame)
{
// 裁剪图像,将左半部分作为左眼,右半部分作为右眼
CropAndAssignTextures();
}
}void CropAndAssignTextures()
{
// 裁剪左半部分作为左眼图像
if (leftEyeRawImage != null)
{
// 设置 RawImage 显示左半部分
leftEyeRawImage.uvRect = new Rect(0f, 0f, 0.5f, 1f);
}// 裁剪右半部分作为右眼图像
if (rightEyeRawImage != null)
{
// 设置 RawImage 显示右半部分
rightEyeRawImage.uvRect = new Rect(0.5f, 0f, 0.5f, 1f);
}
}void OnDestroy()
{
// 停止摄像头
if (cameraTexture != null)
{
cameraTexture.Stop();
}
}
}
最后将此脚本挂在在LeftCanvas上。