2013/07/08

C#.Net 擷取Kinect影像


這個專案用於儲存Kinect影像,每秒都儲存一張照片在使用者的圖片資料夾裏頭
如需要儲存更多張影像的使用者可以自行修正執行續休眠時間
或用其他方式去控制,為了避免硬碟故障,所以我就一秒只儲存一張XD

<Window x:Class="Kinect_Storage_Images.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Kinect Storage Images" Height="50" Width="150" Loaded="Window_Loaded" Unloaded="Window_Unloaded">
</Window>




using System.Windows;
using Microsoft.Kinect;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System;
using System.IO;
using System.Threading;

namespace Kinect_Storage_Images
{
    /// 
    /// MainWindow.xaml 的互動邏輯
    /// 
    public partial class MainWindow : Window
    {
        private KinectSensor sensor = KinectSensor.KinectSensors[0];
        private byte[] databyte;

        public MainWindow()
        {
            InitializeComponent();
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            sensor.ColorStream.Enable();
            sensor.ColorFrameReady += VideoFrameReady;
            sensor.Start();
        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            if (sensor != null)
            {
                sensor.Stop();
            }
        }

        private void VideoFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            bool hasData = false;

            using (ColorImageFrame frame = e.OpenColorImageFrame())
            {
                if (frame == null)
                {
                }
                else
                {
                    databyte = new byte[frame.PixelDataLength];
                    frame.CopyPixelDataTo(databyte);
                    hasData = true;
                }
            }
            if (hasData)
            {
                BitmapSource source = BitmapSource.Create(640, 480, 96, 96,
                    PixelFormats.Bgr32, null, databyte, 640 * 4);
                SaveImage(ref source);
                Thread.Sleep(1000);
            }
        }

        private static String GetFileName()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "//" +
                DateTime.Now.ToFileTime().ToString() + ".png";
        }

        private void SaveImage(ref BitmapSource source)
        {
            PngBitmapEncoder pe = new PngBitmapEncoder();
            pe.Frames.Add(BitmapFrame.Create(source));
            using (Stream s = new FileStream(GetFileName(), FileMode.Create))
            {
                pe.Save(s);
            }
        }

    }
}

參考資料:
http://msdn.microsoft.com/zh-tw/library/system.windows.media.imaging.bitmapencoder.aspx