kinect2.0 基础篇第一篇 用C#在Visual Studio上编写关闭彩色图像的三色通道的某个通

时间:2021-10-16 03:13:59

网上基于kinect2.0 用C#语言编写的小程序太少了 

下面的链接上C#语言的一些基础开发,对于什么都不会的最好手把手敲一遍 

使用kinect2.0  要求环境如下:

系统win8以上

Usb接口3.0

Direct11 以上

1.新建一个WPF应用程序,首先肯定要添加应用  Microsoft.Kinect

2.在WPF 在Grid中 添加一个控件

<Image x:Name="image"/>

3.后端代码如下

   public partial class MainWindow : Window
    {
        private KinectSensor kinect = null;
        private ColorFrameReader colorFrame = null;
        private WriteableBitmap colorBitmap = null;
        private FrameDescription colorFrameDescription = null;
        private Int32Rect colorBitmapRect;
        private int colorBitmapStride;
        byte[] pixelData = null;

public MainWindow()
        {
            InitializeComponent();
            this.kinect = KinectSensor.GetDefault();
            this.colorFrame = kinect.ColorFrameSource.OpenReader();
            this.colorFrame.FrameArrived += colorFrame_FrameArrived;
            this.colorFrameDescription = this.kinect.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
            pixelData = new byte[colorFrameDescription.LengthInPixels*4];
            //按照Bgra格式设定数据帧的描述信息(B:Blue,G:Green,R:Red,A:Alpha)
            // 1920*1080  彩色图像
            this.colorBitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height, 96.0, 96.0, PixelFormats.Bgr32, null);
            //根据数据帧的宽高创建colorBitmap的实例
            this.colorBitmapRect = new Int32Rect(0, 0, this.colorBitmap.PixelWidth, colorBitmap.PixelHeight);
            this.colorBitmapStride = this.colorFrameDescription.Width * 4;
            image.Source = this.colorBitmap;
            this.kinect.Open(); //启动kinect摄像头
        }

void colorFrame_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
        {
            using (ColorFrame frame = e.FrameReference.AcquireFrame())
            //建立一个ColorFrame的实例frame保存送过来的帧,,通过using保证走完函数后及时释放相应资源
            {
                if (frame != null)
                {
                    frame.CopyConvertedFrameDataToArray(this.pixelData, ColorImageFormat.Bgra);
                    for (int i = 0; i < pixelData.Length; i +=4) //看来bgra是占4位的
                    {
                        pixelData[i] = 0x00;//关闭蓝色通道
                       // pixelData[i + 1] = 0x00;//关闭绿色通道
                        pixelData[i + 2] = 0x00;//关闭红色通道
                    }
                    this.colorBitmap.WritePixels(this.colorBitmapRect, this.pixelData, this.colorBitmapStride, 0);
                }
            }
        }

开启之后效果如下(只留下绿色通道)