2015-07-13 53 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