C# OpencvSharp获取Astra Pro奥比中光深度相机深度图

在某鱼花了90RMB,买了个Astra Pro奥比中光深度相机,性价比还是比较高的。通过封装官方的SDK,导出为dll给C#调用,效果如下

///////////AstraCamera.cs////////////

using System;

using System.Runtime.InteropServices;

using System.Threading;

using System.Drawing;

using OpenCvSharp;

using OpenCvSharp.Extensions;

public class AstraCamera : IDisposable

{

// DLL导入

DllImport("ColorReaderEventCPP.dll", CallingConvention = CallingConvention.StdCall)

private static extern void StartCamera();

DllImport("ColorReaderEventCPP.dll", CallingConvention = CallingConvention.StdCall)

private static extern void StopCamera();

DllImport("ColorReaderEventCPP.dll", CallingConvention = CallingConvention.StdCall)

private static extern bool GetLatestFrames(

IntPtr rawDepthData, int rawDepthSize,

IntPtr depthData, int depthSize,

IntPtr colorData, int colorSize);

DllImport("ColorReaderEventCPP.dll", CallingConvention = CallingConvention.StdCall)

private static extern void GetFrameInfo(

out int rawDepthWidth, out int rawDepthHeight, out int rawDepthType,

out int depthWidth, out int depthHeight, out int depthType,

out int colorWidth, out int colorHeight, out int colorType);

// 图像属性

public int RawDepthWidth;

public int RawDepthHeight;

public MatType RawDepthType { get; private set; }

public int DepthWidth;

public int DepthHeight;

public MatType DepthType { get; private set; }

public int ColorWidth;

public int ColorHeight;

public MatType ColorType { get; private set; }

// 非托管内存缓冲区

private IntPtr _rawDepthBuffer;

private IntPtr _depthBuffer;

private IntPtr _colorBuffer;

private int _rawDepthBufferSize;

private int _depthBufferSize;

private int _colorBufferSize;

// 当前帧

public Mat RawDepthFrame { get; private set; } // 原始深度图 (16位)

public Mat DepthFrame { get; private set; } // 伪彩色深度图

public Mat ColorFrame { get; private set; } // 彩色图

// 更新事件

public event Action FramesUpdated;

// 后台线程

private Thread _updateThread;

private bool _isRunning;

public AstraCamera()

{

// 获取帧信息

GetFrameInfo(out RawDepthWidth, out RawDepthHeight, out int rawDepthType,

out DepthWidth, out DepthHeight, out int depthType,

out ColorWidth, out ColorHeight, out int colorType);

// 转换为MatType

RawDepthType = (MatType)rawDepthType;

DepthType = (MatType)depthType;

ColorType = (MatType)colorType;

// 计算缓冲区大小

_rawDepthBufferSize = RawDepthWidth * RawDepthHeight * sizeof(ushort); // 16位深度图

_depthBufferSize = DepthWidth * DepthHeight * 3; // 伪彩色图 (3通道)

_colorBufferSize = ColorWidth * ColorHeight * 3; // 彩色图 (3通道)

// 分配非托管内存

_rawDepthBuffer = Marshal.AllocHGlobal(_rawDepthBufferSize);

_depthBuffer = Marshal.AllocHGlobal(_depthBufferSize);

_colorBuffer = Marshal.AllocHGlobal(_colorBufferSize);

// 创建Mat对象

RawDepthFrame = new Mat(RawDepthHeight, RawDepthWidth, RawDepthType);

DepthFrame = new Mat(DepthHeight, DepthWidth, DepthType);

ColorFrame = new Mat(ColorHeight, ColorWidth, ColorType);

// 启动相机

StartCamera();

_isRunning = true;

// 启动更新线程

_updateThread = new Thread(UpdateFrames);

_updateThread.IsBackground = true;

_updateThread.Start();

}

private void UpdateFrames()

{

while (_isRunning)

{

// 获取最新帧

if (GetLatestFrames(

_rawDepthBuffer, _rawDepthBufferSize,

_depthBuffer, _depthBufferSize,

_colorBuffer, _colorBufferSize))

{

// 将数据复制到Mat

RawDepthFrame = new Mat(RawDepthHeight, RawDepthWidth, RawDepthType, _rawDepthBuffer);

Cv2.Flip(RawDepthFrame,RawDepthFrame,FlipMode.Y);

DepthFrame = new Mat(DepthHeight, DepthWidth, DepthType, _depthBuffer);

Cv2.Flip(DepthFrame, DepthFrame, FlipMode.Y);

ColorFrame = new Mat(ColorHeight, ColorWidth, ColorType, _colorBuffer);

Cv2.Flip(ColorFrame, ColorFrame, FlipMode.Y);

// 触发更新事件

FramesUpdated?.Invoke();

}

Thread.Sleep(30); // 约30fps

}

}

// 转换为Bitmap用于PictureBox显示

public Bitmap GetRawDepthBitmap()

{

// 将16位深度图转换为8位显示

using (Mat normalized = new Mat())

{

double min, max;

RawDepthFrame.MinMaxLoc(out min, out max);

RawDepthFrame.ConvertTo(normalized, MatType.CV_8UC1, 255.0 / (max - min), -min * 255.0 / (max - min));

return normalized.ToBitmap();

}

}

public Bitmap GetDepthBitmap()

{

return DepthFrame.ToBitmap();

}

public Bitmap GetColorBitmap()

{

return ColorFrame.ToBitmap();

}

public void Dispose()

{

_isRunning = false;

_updateThread?.Join(1000);

StopCamera();

Marshal.FreeHGlobal(_rawDepthBuffer);

Marshal.FreeHGlobal(_depthBuffer);

Marshal.FreeHGlobal(_colorBuffer);

RawDepthFrame?.Dispose();

DepthFrame?.Dispose();

ColorFrame?.Dispose();

}

}

/////////////AstraProCamera.cs////////////////

using System;

using System.Drawing;

using System.Runtime.InteropServices;

using System.Runtime.Remoting.Contexts;

using System.Windows.Forms;

using OpenCvSharp;

namespace WindowsFormsApp1

{

public partial class AstraProCamera : Form

{

public AstraProCamera()

{

InitializeComponent();

}

private AstraCamera _astraCamera;

private Mat depthMat;

private void InitializeCamera()

{

try

{

_astraCamera = new AstraCamera();

_astraCamera.FramesUpdated += UpdatePictureBoxes;

}

catch (Exception ex)

{

MessageBox.Show($"Camera initialization failed: {ex.Message}");

Close();

}

}

private void UpdatePictureBoxes()

{

// 使用BeginInvoke确保UI线程更新

if (_depthPictureBox.InvokeRequired || _colorPictureBox.InvokeRequired)

{

BeginInvoke(new Action(UpdatePictureBoxes));

return;

}

try

{

// 更新原始深度图

depthMat = _astraCamera.RawDepthFrame.Clone();

using (var rawDepthBitmap = _astraCamera.GetRawDepthBitmap())

{

_rawDepthPictureBox.Image?.Dispose();

_rawDepthPictureBox.Image = new Bitmap(rawDepthBitmap);

}

// 更新深度图

using (var depthBitmap = _astraCamera.GetDepthBitmap())

{

_depthPictureBox.Image?.Dispose();

_depthPictureBox.Image = new Bitmap(depthBitmap);

}

// 更新彩色图

using (var colorBitmap = _astraCamera.GetColorBitmap())

{

_colorPictureBox.Image?.Dispose();

_colorPictureBox.Image = new Bitmap(colorBitmap);

//Bitmap flipped = FlipX(colorBitmap);

//_colorPictureBox.Image = flipped;

}

}

catch (Exception ex)

{

Console.WriteLine($"Update error: {ex.Message}");

}

}

private void button3_Click(object sender, EventArgs e)

{

InitializeCamera();

}

private void button4_Click(object sender, EventArgs e)

{

_astraCamera.Dispose();

}

// 计算图片在PictureBox中的显示区域

private RectangleF GetImageDisplayRectangle(PictureBox picBox)

{

if (picBox.Image == null) return RectangleF.Empty;

System.Drawing.Size imgSize = picBox.Image.Size;

System.Drawing.Size boxSize = picBox.ClientSize;

switch (picBox.SizeMode)

{

case PictureBoxSizeMode.Normal:

case PictureBoxSizeMode.AutoSize:

return new RectangleF(0, 0, imgSize.Width, imgSize.Height);

case PictureBoxSizeMode.StretchImage:

return new RectangleF(0, 0, boxSize.Width, boxSize.Height);

case PictureBoxSizeMode.Zoom:

float ratio = Math.Min(

(float)boxSize.Width / imgSize.Width,

(float)boxSize.Height / imgSize.Height);

float width = imgSize.Width * ratio;

float height = imgSize.Height * ratio;

float x = (boxSize.Width - width) / 2;

float y = (boxSize.Height - height) / 2;

return new RectangleF(x, y, width, height);

case PictureBoxSizeMode.CenterImage:

return new RectangleF(

(boxSize.Width - imgSize.Width) / 2,

(boxSize.Height - imgSize.Height) / 2,

imgSize.Width,

imgSize.Height);

default:

return RectangleF.Empty;

}

}

private static int Clamp(int value, int min, int max)

{

return value < min ? min : (value > max ? max : value);

}

private void _colorPictureBox_MouseMove(object sender, MouseEventArgs e)

{

if (_depthPictureBox.Image == null) return;

// 获取图片原始尺寸和PictureBox显示区域

int imgWidth = _depthPictureBox.Image.Width;

int imgHeight = _depthPictureBox.Image.Height;

RectangleF displayRect = GetImageDisplayRectangle(_depthPictureBox);

// 检查点击是否在图片区域内

if (!displayRect.Contains(e.Location)) return;

// 计算实际图片坐标

float scaleX = imgWidth / displayRect.Width;

float scaleY = imgHeight / displayRect.Height;

int actualX = (int)((e.X - displayRect.X) * scaleX);

int actualY = (int)((e.Y - displayRect.Y) * scaleY);

// 确保坐标在图片范围内

actualX = Clamp(actualX, 0, imgWidth - 1);

actualY = Clamp(actualY, 0, imgHeight - 1);

ushort depth = depthMat.At<ushort>(actualY, actualX);

listBox1.Items.Insert(0, $"{DateTime.Now.ToString()} 深度:{depth} mm");

label4.Text = $"({actualX}, {actualY}) 深度:{depth} mm";

}

}

}

相关推荐
Coding茶水间5 小时前
基于深度学习的肾结石检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉
就是有点傻6 小时前
如何创建一个WebApi服务端
服务器·c#
雍凉明月夜6 小时前
视觉opencv学习笔记Ⅴ-数据增强(1)
人工智能·python·opencv·计算机视觉
这张生成的图像能检测吗6 小时前
(论文速读)Nickel and Diming Your GAN:通过知识蒸馏提高GAN效率的双重方法
人工智能·生成对抗网络·计算机视觉·知识蒸馏·图像生成·模型压缩技术
donkey_19937 小时前
ShiftwiseConv: Small Convolutional Kernel with Large Kernel Effect
人工智能·深度学习·目标检测·计算机视觉·语义分割·实例分割
她说彩礼65万7 小时前
C# params使用
开发语言·c#·log4j
专注VB编程开发20年7 小时前
C#内存加载dll和EXE是不是差不多,主要是EXE有入口点
数据库·windows·microsoft·c#
再__努力1点8 小时前
【68】颜色直方图详解与Python实现
开发语言·图像处理·人工智能·python·算法·计算机视觉
她说彩礼65万8 小时前
C# 反射
java·算法·c#
laocooon5238578869 小时前
C#二次开发中简单块的定义与应用
android·数据库·c#