2015-07-13 51 views
0

我正在使用OpenCV保存.yml。這裏是我的代碼,我用在OpenCV中讀取YAML文件

FileStorage fs; 
fs.open("test", FileStorage::WRITE); 
for (unsigned int i = 0; i < (block_hist_size * blocks_per_img.area()) ; i++) 
{ 
fs << "features" << dest_ptr[i]; 
} 
fs.release(); 

這裏是YAML文件

%YAML:1.0 
features: 1.5302167832851410e-01 
features: 1.0552208870649338e-01 
features: 1.6659785807132721e-01 
features: 2.3539969325065613e-01 
features: 2.0810306072235107e-01 
features: 1.2627227604389191e-01 
features: 8.0759152770042419e-02 
features: 6.4930714666843414e-02 
features: 6.1364557594060898e-02 
features: 2.1614919602870941e-01 
features: 1.4714729785919189e-01 
features: 1.5476198494434357e-01 

的輸出誰能幫我讀YML文件回到dest_ptr。我只需要浮點值

+0

我想,以上將無法正常工作。 FileStorage基本上是一個關鍵值存儲,您的密鑰不是唯一的。什麼是dest_ptr?你不能把它放入一個cv :: Mat或類似的東西嗎? (也更容易回讀) – berak

+0

這些是僅限塊的HOG功能。隨着下面我得到全零。我想弄明白@berak – shah

回答

1

您不能對同一個鍵使用多個值。在你的情況下,你應該把它作爲一個特徵向量來存儲。請參閱下面的代碼

FileStorage fs, fs2; 
fs.open("test.yml", FileStorage::WRITE); 
fs << "features" << "["; 
for (unsigned int i = 0; i < 20; i++) { 
    fs << 1.0/(i + 1); 
} 
fs << "]"; 
fs.release(); 

fs2.open("test.yml", FileStorage::READ); 
vector<float> a; 
fs2["features"] >> a; 
+0

我得到所有的零@Tal Darom – shah

+0

好吧,我錯過了你使用相同的關鍵所有功能的事實。更新我的回答 –

+0

是的相同的關鍵特徵是一個錯誤的條件。我正試圖解決這個問題 – shah

1

您必須誤讀YAML規範,因爲您使用代碼生成的內容不是YAML文件。
在YAML文件映射項必須爲每定義獨特的generic mapping(並且使用的是因爲你沒有指定一個標籤的通用映射):

Definition: 

    Represents an associative container, where each key is unique in the 
    association and mapped to exactly one value. YAML places no restrictions on 
    the type of keys; in particular, they are not restricted to being scalars. 
    Example bindings to native types include Perl’s hash, Python’s dictionary, 
    and Java’s Hashtable. 

真正問題你試圖讓一個簡單的YAML發射器做字符串自己寫。您應該已經在C++和emitted that結構中創建了所需的數據結構,那麼YAML將是正確的(假設發射器不是越野車)。

根據什麼樣的文件結構的選擇,你可能會得到:

%YAML:1.0 
- features: 1.5302167832851410e-01 
- features: 1.0552208870649338e-01 
- features: 1.6659785807132721e-01 
- features: 2.3539969325065613e-01 
- features: 2.0810306072235107e-01 
- features: 1.2627227604389191e-01 
- features: 8.0759152770042419e-02 
- features: 6.4930714666843414e-02 
- features: 6.1364557594060898e-02 
- features: 2.1614919602870941e-01 
- features: 1.4714729785919189e-01 
- features: 1.5476198494434357e-01 

(單個鍵/值映射關係的序列)或:

%YAML:1.0 
features: 
- 1.5302167832851410e-01 
- 1.0552208870649338e-01 
- 1.6659785807132721e-01 
- 2.3539969325065613e-01 
- 2.0810306072235107e-01 
- 1.2627227604389191e-01 
- 8.0759152770042419e-02 
- 6.4930714666843414e-02 
- 6.1364557594060898e-02 
- 2.1614919602870941e-01 
- 1.4714729785919189e-01 
- 1.5476198494434357e-01 

(一個單一的映射關鍵是一個序列的單個值)

正如你經歷過的,使用字符串寫入爲數據結構創建正確的YAML並不簡單。如果你開始用合適的數據結構和發射出的結構,你也知道,你可以使用相同的結構來讀回。


在我的經驗,同樣適用於生成XML/HTML /真CSV/INI文件,其中具有正確的數據結構並且使用發射器也避免輸出格式中的錯誤,從而補償初始代碼的任何稍高的複雜度。

+0

現在我明白了。非常感謝你的詳細描述。不久我嘗試閱讀功能我有同樣的關鍵異常。 @Anthon – shah