unity3d 打开相机将视频传给C++ dll

Unity C#

cameraDll.cs

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class cameraDll : MonoBehaviour
{


    [DllImport("run_on_camera_sequence")]
    //static extern void ByteToMat(System.IntPtr imageData, int imageW, int imageH, int nFlag);
    static extern void ByteToMat(byte[] imagedata, int imageW, int imageH, int nFlag);


    // Start is called before the first frame update



    int width = 640;
    int height = 480;

    private WebCamTexture webCamTexture;


    void Start()
    {

        webCamTexture = new WebCamTexture();

        如果有后置摄像头,调用后置摄像头  
        //for (int i = 0; i < WebCamTexture.devices.Length; i++)
        //{

        //    print(WebCamTexture.devices[i].name);

        //    if (WebCamTexture.devices[i].name == "Creative GestureCam")
        //    {
        //        webcamTexture.deviceName = WebCamTexture.devices[i].name;

        //        break;
        //    }
        //}
        webCamTexture.deviceName = WebCamTexture.devices[0].name;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = webCamTexture;
        webCamTexture.Play();



    }


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

        ByteToMat(ConvertWebCamTextureToByteArray(), 480, 640, 3);

    }

    //获取像素
    public byte[] ConvertWebCamTextureToByteArray()
    {

        Color[] pixels = new Color[width * height];

        pixels = webCamTexture.GetPixels();
        byte[] bytes = new byte[width * height * 4];
        for (int i = 0; i < pixels.Length; i++)
        {
            Color color = pixels[i];
            bytes[i * 4] = (byte)(color.r * 255);
            bytes[i * 4 + 1] = (byte)(color.g * 255);
            bytes[i * 4 + 2] = (byte)(color.b * 255);
            bytes[i * 4 + 3] = (byte)(color.a * 255);
        }

        return bytes;
    }


}

C++

cpp 复制代码
cv::Mat outImg;
extern "C" __declspec(dllexport)
//解析从u3d中传过来的字节格式的图像数据为Mat
void  ByteToMat(byte* pImg, int nH, int nW, int nFlag)//nH,nW为BYTE*类型图像的高和宽,nFlag为通道数
{
	if (pImg == nullptr)
	{
		return ;
	}


	 outImg = cv::Mat(nH, nW, CV_8UC4, pImg);
	cv::cvtColor(outImg, outImg, cv::COLOR_RGB2BGR);
	cv::flip(outImg, outImg, 1);
	 cv::rotate(outImg, outImg, cv::ROTATE_180);

	cv::imshow("u3dvideo", outImg);
	cv::waitKey(1);
}

初阶上nFlag没用,可以不要。

相关推荐
whoarethenext41 分钟前
初始https附带c/c++源码使用curl库调用
服务器·c++·qt·https·curl
群联云防护小杜1 小时前
云服务器主动防御策略与自动化防护(下)
运维·服务器·分布式·安全·自动化·音视频
cloues break.2 小时前
C++进阶----多态
开发语言·c++
Despacito0o2 小时前
C++核心编程:类与对象全面解析
开发语言·c++
CodeWithMe5 小时前
【C++】线程池
开发语言·c++
wuqingshun3141595 小时前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
hu_yuchen6 小时前
C++:BST、AVL、红黑树
开发语言·c++
炯哈哈6 小时前
【上位机——MFC】视图
开发语言·c++·mfc·上位机
我也不曾来过16 小时前
继承(c++版 非常详细版)
开发语言·c++
带娃的IT创业者7 小时前
《AI大模型应知应会100篇》第39篇:多模态大模型应用:文本、图像和音频的协同处理
人工智能·microsoft·音视频