Godot+C#+OpenCV实现调用本机摄像头
在此记录一下使用godot调用本地摄像头的实现方法:
1.使用Godot(Godot_v4.0.2-stable_mono_win64.exe)创建一个项目,
2.添加一个Sprite2D节点显示画面用
3.生成解决方案并用VS2022打开
4.添加OpenCvSharp4.Windows和OpenCvSharp4.Extensions(来自NuGet)
5.核心实现函数(注意要套个线程执行):
var capture = new VideoCapture(1, VideoCaptureAPIs.DSHOW);//本机摄像头
capture.XI_OffsetX = 0; // 以左上角为起点 坐标X
capture.XI_OffsetY = 0; // 以左上角为起点 坐标Y
capture.FrameWidth = 640; // 宽
capture.FrameHeight = 480; // 高
capture.AutoFocus = true;
var image = new Mat();
while (true)
{
capture.Read(image);//获取图像
if (image.Empty())//为空跳出
break;
var bytes = image.ToBytes();//图像转byte
Godot.Image img = new Godot.Image();//实例化godot Image节点
img.LoadPngFromBuffer(bytes);//装载图像
var texture = new ImageTexture();//实例化Texture
texture.SetImage(img);//装载img
Sprite2D.Texture = texture;//赋值给Sprite2D显示
}