😀

OpenCV for Unityでカメラ画像を表示する

2022/12/24に公開

画像処理を行う前段階として、カメラ画像を取得します。

前提条件

  • Unity 2018.4.21f1
  • プロジェクトタイプ 2D

手順

Hierachy内は下図のようにRawImageとButtonを追加します。

次にC# ScriptとしてRawImageController.csを作成します。
カメラ画像表示のほかにChangeCamera関数を呼ぶとカメラデバイスの切り替えを行います。
スマホで実行した際には内側/外側のカメラを切り替えることができます。

using UnityEngine;
using UnityEngine.UI;

public class RawImageController: MonoBehaviour
{
    WebCamTexture webCamTexture;
    WebCamDevice[] webCamDevice;
    int selectCamera = 0;

    void Start()
    {
        webCamTexture = new WebCamTexture();
        webCamDevice = WebCamTexture.devices;

        webCamTexture = new WebCamTexture(webCamDevice[selectCamera].name);
        GetComponent<RawImage>().texture = webCamTexture;
        webCamTexture.Play();

        ChangeCamera();
    }

    public void ChangeCamera()
    {
        int cameras = webCamDevice.Length;
        if (cameras < 1) return;

        webCamTexture.Stop();
        webCamTexture = new WebCamTexture(webCamDevice[selectCamera].name);
        GetComponent<RawImage>().texture = webCamTexture;
        webCamTexture.Play();

        selectCamera++;
        if (selectCamera >= cameras) selectCamera = 0;
    }
}

RawImageController.csをRawImageにアタッチします。

また、ButtonをクリックしたときにChangeCamera関数を呼ぶようにしたいので、
ButtonのInspector内で設定します。
On Click()にRawImageを登録し、関数にChangeCameraを指定してください。

https://scrapbox.io/ConsoleSoup/OpenCV_for_Unityでカメラ映像を描画

GitHubで編集を提案

Discussion