彩色圖像很有用,很有用!!說到圖像識別,未來肯定是個大方向!在機器人視覺和一些智能識別在應用很廣,而獲取下來的數據再加上Opencv就能做出很多很好玩很有趣的功能。這個以后等我進一步成長后再回來慢慢記錄。
這里首先要遵循下我在博客里第一篇文章kinect基本認識(http://www.cnblogs.com/carsonche/p/5891517.html)上講的流程進行源碼分析
流程:開始程序-獲取kinect攝像機-打開讀取器-打開Kinect-獲取讀取器的相關幀數據-使用幀數據-關閉幀-關閉讀取器-關閉Kinect-關閉程序
官方的SDK把獲取彩色幀的數據放在了Color source manager,而顯示幀的數據放在了Color Source View里。
Color source manager的操作流程:(在源碼上做了注釋和解析)
u
sing UnityEngine; using System.Collections; using Windows.Kinect; public class ColorSourceManager : MonoBehaviour { public int ColorWidth { get; private set; } public int ColorHeight { get; private set; } public uint BytesPerPixel; public uint LengthInPixels; private KinectSensor _Sensor; private ColorFrameReader _Reader; private Texture2D _Texture; private byte[] _Data; //獲取圖像 public Texture2D GetColorTexture() { return _Texture; } void Start() { //獲取傳感器 _Sensor = KinectSensor.GetDefault(); if (_Sensor != null) { //獲取顏色幀讀取器 _Reader = _Sensor.ColorFrameSource.OpenReader(); //獲取RGBA的彩色幀的分辨率為1920*1080,30幀,每像素 var frameDesc = _Sensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba); ColorWidth = frameDesc.Width; ColorHeight = frameDesc.Height; _Texture = new Texture2D(frameDesc.Width, frameDesc.Height, TextureFormat.RGBA32, false); //定義字節數據大小,大小為沒像素字節*像素長度(1920*1080) _Data = new byte[frameDesc.BytesPerPixel * frameDesc.LengthInPixels]; if (!_Sensor.IsOpen) { //若Kinect沒有開啟,則開啟kinect _Sensor.Open(); } } } void Update () { if (_Reader != null) { //獲取最新的幀 var frame = _Reader.AcquireLatestFrame(); //或存在幀 if (frame != null) { //把幀按照RGBA的個數保存在DATA里 frame.CopyConvertedFrameDataToArray(_Data, ColorImageFormat.Rgba); //把圖像按行寫入數據 _Texture.LoadRawTextureData(_Data); //更新圖像 _Texture.Apply(); //釋放並關閉幀 frame.Dispose(); //幀為空 frame = null; } } } void OnApplicationQuit() { //程序關閉時關閉並釋放讀取器 if (_Reader != null) { _Reader.Dispose(); _Reader = null; } //程序關閉時關閉kinect if (_Sensor != null) { if (_Sensor.IsOpen) { _Sensor.Close(); } _Sensor = null; } } }
從上面可以看到,主要整個類為了一個函數,GetColorTexture()而存在的,主要的操作是先定義各種要的參數(字節數組,圖片大小,幀讀取器等),然后下面這三行就是核心程序了
從最新的幀里保存在data數組里,並轉化賦值給texture。后續可以把圖像的所有會用到的函數集合在這個類里,並且進行調用。
圖像的顯示在unity里很簡單,只需要一行代碼就行了,
gameObject.GetComponent<Renderer>().material.mainTexture = _ColorManager.GetColorTexture();
將之前獲得的圖像轉給material,這樣我們就能獲得一個很基本的實時的color圖像了。