unity中获取外置摄像头图像后,显示的尺寸问题。

    private WebCamTexture cameraTexture;
    private bool isPlay = false;
    private string cameraName;

    public int getWidth = 1920;
    public int getHeight = 1080;

    IEnumerator CamInput()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            cameraName = devices[0].name;
            cameraTexture = new WebCamTexture(cameraName, getWidth, getHeight, 30);
            cameraTexture.Play();
            print("画面得到");
            isPlay = true;
        }
    }

上面设置的cameraTexture的长和宽其实并不是一定符合你自己规定的值的。

如果你打印一下

    private void Update()
    {
        if (isPlay)
        {
            print(cameraTexture.width + "   " + cameraTexture.height);
        }
    }

会发现,如果你输入定义1400和800,打印结果是1280和720。也就是说,unity对webcamtexture的大小是受相机干扰的。你的摄像头会自动调整你设置的图像的大小。当设置为800 * 600的时候,不同的usb摄像头也许会做出完全不一样的处理,也许按照你的设置获取图像,也许会自动给你调整为640 * 360的大小。

要在Unity使用OpenCVSharp来获取摄像头视频,你需要按照以下步骤进行操作: 1. 首先,下载并安装OpenCVSharp库。你可以从OpenCVSharp的GitHub页面(https://github.com/shimat/opencvsharp)下载最新版本的库。 2. 在Unity创建一个新的C#脚本,例如"CameraCapture.cs",并将其附加到一个GameObject上。 3. 在脚本导入OpenCVSharp库,你可以使用以下语句: ```csharp using OpenCvSharp; ``` 4. 在脚本编写代码来获取摄像头视频。下面是一个简单的示例: ```csharp using UnityEngine; using OpenCvSharp; public class CameraCapture : MonoBehaviour { private VideoCapture videoCapture; private Texture2D texture; void Start() { videoCapture = new VideoCapture(0); // 摄像头索引,0表示默认摄像头 if (!videoCapture.IsOpened()) { Debug.LogError("Failed to open camera!"); return; } texture = new Texture2D((int)videoCapture.FrameWidth, (int)videoCapture.FrameHeight, TextureFormat.RGBA32, false); } void Update() { Mat frame = new Mat(); videoCapture.Read(frame); if (!frame.Empty()) { // 将OpenCV的Mat转换为Unity的Texture2D texture.LoadRawTextureData(frame.Data, (int)(videoCapture.FrameWidth * videoCapture.FrameHeight * 4)); texture.Apply(); // 在Unity显示摄像头视频 GetComponent<Renderer>().material.mainTexture = texture; } } void OnDestroy() { videoCapture.Release(); texture.Dispose(); } } ``` 在上述示例,我们首先创建了一个VideoCapture对象来打开摄像头。然后,在Update方法,我们使用videoCapture.Read方法读取摄像头的每一帧,并将其转换为Unity的Texture2D对象。最后,我们将Texture2D对象应用到一个渲染器的材质上,从而在Unity显示摄像头视频。 请注意,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。 希望这能帮助到你!如果有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值