OpenCV讀取XML YML檔案的方法

2021-07-03 20:33:51 字數 2400 閱讀 7828

在平時寫一些程式的時候,需要一些配置引數的檔案,最簡單的方法是使用txt檔案儲存引數,但當引數較多時,為了讓儲存的引數更美觀有序且方便讀取,一些其他庫提供的一些資料儲存方法就顯得很方便了,例如libconfig。當然這裡並不打算著重講解這個庫,而是主要說一說opencv中關於資料儲存的方法——讀取xml/yml檔案。xml是一種可擴充套件標記語言,yml和它類似,但是更適合人閱讀。關於xml格式的檔案除了opencv可以讀寫外,還有其他一些專門的庫提供了讀寫的api,例如比較輕量級的tinyxml

xml/yml的寫

檔案的寫的過程相對簡單,類似c++中資料流的寫的過程,使用<<。檔案的建立是用類filestorage,釋放時呼叫filestorage::release()並且關閉檔案。列舉乙個opencv手冊中例子如下:

#include "opencv2/opencv.hpp"

#include

using

namespace cv;

int main(int, char** argv)

"; }

fs << "]";

fs.release();

return

0;}

這樣得到的test.yml檔案中的內容儲存情況如下:

%yaml

:1.0

framecount: 5

calibrationdate: "fri apr 25 16:55:42 2014\n"

cameramatrix: !!opencv-matrix

rows: 3

cols: 3

dt: d

data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]

distcoeffs: !!opencv-matrix

rows: 5

cols: 1

dt: d

data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,

-1.0000000000000000e-03, 0., 0. ]

features:--

-

xml/yml的讀

檔案的讀的過程有三種方法,一種是和檔案的寫對應的,即使用》讀取,如下面的示例**第8行;另一種是使用型別強制轉換成相應資料,如下面例項**第4行;最後一種是針對多個資料的讀取,使用filenode對應的迭代器filenodeiterator進行逐個讀取資料,如下面例項**第28行。

filestorage fs2("test.yml", filestorage::read);

// first method: use (type) operator on filenode.

int framecount = (int)fs2["framecount"];

std::string date;

// second method: use filenode::operator >>

fs2["calibrationdate"] >> date;

mat cameramatrix2, distcoeffs2;

fs2["cameramatrix"] >> cameramatrix2;

fs2["distcoeffs"] >> distcoeffs2;

cout

<< "framecount: "

<< framecount << endl

<< "calibration date: "

<< date << endl

<< "camera matrix: "

<< cameramatrix2 << endl

<< "distortion coeffs: "

<< distcoeffs2 << endl;

filenode features = fs2["features"];

filenodeiterator it = features.begin(), it_end = features.end();

int idx = 0;

std::vector

lbpval;

// iterate through a sequence using filenodeiterator

for( ; it != it_end; ++it, idx++ )

fs.release();

之前一直使用libconfig作為引數配置的庫,但是既然opencv也有這方面的功能,考慮到不需要安裝額外的庫,還是打算轉向使用這個東西,這裡做個簡單介紹算是以後查詢使用

讀取Structs properties檔案

在這裡我直接返回的是properties物件 這樣更靈活 可以在外部呼叫的時候想哪到properties檔案裡的哪個屬性都行,當然必須要是properties裡存在的。讀取properties檔案 param propertiesname return public static propertie...

opencv 讀取畫素值

話不多說,新手在不斷學習,剛剛看見讀取每個畫素點值很是好奇。include include using namespace std int main 不過通過上訴方法在速度方面會比較慢。可以通過如下方法加快訪問,更改速度。iplimage成員有 int nsize int id 比較重要的兩個元素是...

OpenCV 讀取csv檔案

逗號分隔值 comma separated values,csv,有時也稱為字元分隔值,因為分隔字元也可以不是逗號 其檔案以純文字形式儲存 資料 數字和文字 純文字意味著該檔案是乙個字串行,不含必須像二進位制數字那樣被解讀的資料。csv檔案由任意數目的記錄組成,記錄間以某種換行符分隔 每條記錄由欄位...