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没用,可以不要。

相关推荐
青草地溪水旁20 小时前
设计模式(C++)详解——状态模式(State)(1)
c++·设计模式·状态模式
千里马-horse21 小时前
Async++ 源码分析3---cancel.h
开发语言·c++·async++·cancel
渡我白衣1 天前
C++ :std::bind 还能用吗?它和 Lambda 有什么区别?
开发语言·c++·c++20
胖咕噜的稞达鸭1 天前
算法入门:专题攻克主题一---双指针(1)移动零 复写零
c语言·开发语言·c++·算法
一只小bit1 天前
CMake 入门实战手册:从理解原理开始,打造高效 C/C++ 开发流程
c语言·开发语言·c++·cmake
青草地溪水旁1 天前
设计模式(C++)详解——策略模式(1)
c++·设计模式·策略模式
余衫马1 天前
llama.cpp:本地大模型推理的高性能 C++ 框架
c++·人工智能·llm·llama·大模型部署
胖咕噜的稞达鸭1 天前
算法入门:专题攻克主题一---双指针(2)快乐数 呈最多水的容器
开发语言·数据结构·c++·算法
孞㐑¥1 天前
Linux网络部分—网络层
linux·c++·经验分享·笔记
班公湖里洗过脚1 天前
第1章 线程安全的对象生命期管理
c++