C# EMGU 3.4.1學習筆記(二)XML和YAML檔案的寫入
阿新 • • 發佈:2019-01-09
以下是《OpenCV3程式設計入門》中5.6.3的示例程式的C# + EMGU 3.4.1版,和C++程式相比,有如下幾點不同:
1. 使用Matrix<>儲存多維陣列,多維陣列的各維需要使用{}擴起來,之間用逗號分隔;
2. C#中無法使用<<和>>實現流的輸入和輸出,對應於<<的是Insert和Write函式,Insert函式只能插入string,Write函式可以把一個value插入到string形式的node;
3. 對於vector結構的輸入和輸出,要注意在第一個元素前加上“[”,在最後一個元素前加上“]”;而對於map結構的操作,使用的符號是“{”和“}”。需要注意的是,如果在“[”或“{”的後面緊跟“:”,則表示不進行換行輸出,反之則進行換行輸出;
4. 程式碼中使用了DateTime類獲得系統當前時間,並以GetDateTimeFormats('r')[0]的格式進行顯示;
5. 程式碼中使用了System.Security.Cryptography.RNGCryptoServiceProvider類,生成random seed,實現“真”隨機數功能。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Security.Cryptography; //RNGCryptoServiceProvider(用於生成真隨機數)所在名稱空間 using Emgu.CV; namespace XML_YAML_Write { class Program { static void Main(string[] args) { //初始化 FileStorage fs = new FileStorage("test.yaml", FileStorage.Mode.Write); //開始檔案寫入 fs.Write(5, "frameCount"); DateTime rawtime = DateTime.Now; fs.Insert("calibrationDate"); fs.Insert(rawtime.GetDateTimeFormats('r')[0].ToString()); double[,] values1 = new double[3, 3] { { 1000, 0, 30 }, { 0, 1000, 240 }, { 0, 0, 1 } }; Matrix<double> cameraMatrix = new Matrix<double>(values1); double[,] values2 = new double[5, 1] { { 0.1 }, { 0.01 }, { -0.001 }, { 0 }, {0} }; Matrix<double> distCoeffs = new Matrix<double>(values2); fs.Write(cameraMatrix.Mat, "cameraMatrix"); fs.Write(distCoeffs.Mat, "distCoeffs"); fs.Insert("features"); fs.Insert("["); //開始寫入array for(int i = 0; i < 3; i++) { int x = new Random(GetRandomSeed()).Next() % 640; int y = new Random(GetRandomSeed()).Next() % 480; byte lbp = (byte) (new Random(GetRandomSeed()).Next() % 256); //開始寫入Mapping文字 fs.Insert("{:"); //“:”是格式符,帶之則不換行寫入,反之換行寫入 fs.Write(x, "x"); fs.Write(y, "y"); fs.Insert("lbp"); fs.Insert("[:"); //“:”是格式符,帶之則不換行寫入,反之換行寫入 for (int j = 0; j < 8; j++) fs.Insert(((lbp >> j) & 1).ToString()); // “>>”為移位運算子 fs.Insert("]"); fs.Insert("}"); //關閉Mapping } fs.Insert("]"); //關閉array fs.ReleaseAndGetString(); Console.WriteLine("檔案寫入完畢,請在工程目錄下檢視生成的檔案~"); Console.ReadKey(); } //該函式作用為產生隨機數種子,以便生成“真”隨機數 static int GetRandomSeed() { byte[] bytes = new byte[4]; //4個位元組可合成為int32 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); //把4個位元組合成為int32 } } }