test_io.cpp 45.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include "test_precomp.hpp"

using namespace cv;
using namespace std;

static SparseMat cvTsGetRandomSparseMat(int dims, const int* sz, int type,
                                        int nzcount, double a, double b, RNG& rng)
{
    SparseMat m(dims, sz, type);
    int i, j;
    CV_Assert(CV_MAT_CN(type) == 1);
    for( i = 0; i < nzcount; i++ )
    {
        int idx[CV_MAX_DIM];
        for( j = 0; j < dims; j++ )
            idx[j] = cvtest::randInt(rng) % sz[j];
        double val = cvtest::randReal(rng)*(b - a) + a;
        uchar* ptr = m.ptr(idx, true, 0);
        if( type == CV_8U )
            *(uchar*)ptr = saturate_cast<uchar>(val);
        else if( type == CV_8S )
            *(schar*)ptr = saturate_cast<schar>(val);
        else if( type == CV_16U )
            *(ushort*)ptr = saturate_cast<ushort>(val);
        else if( type == CV_16S )
            *(short*)ptr = saturate_cast<short>(val);
        else if( type == CV_32S )
            *(int*)ptr = saturate_cast<int>(val);
        else if( type == CV_32F )
            *(float*)ptr = saturate_cast<float>(val);
        else
            *(double*)ptr = saturate_cast<double>(val);
    }
34

35 36 37 38 39 40 41 42
    return m;
}

static bool cvTsCheckSparse(const CvSparseMat* m1, const CvSparseMat* m2, double eps)
{
    CvSparseMatIterator it1;
    CvSparseNode* node1;
    int depth = CV_MAT_DEPTH(m1->type);
43

44 45 46
    if( m1->heap->active_count != m2->heap->active_count ||
       m1->dims != m2->dims || CV_MAT_TYPE(m1->type) != CV_MAT_TYPE(m2->type) )
        return false;
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    for( node1 = cvInitSparseMatIterator( m1, &it1 );
        node1 != 0; node1 = cvGetNextSparseNode( &it1 ))
    {
        uchar* v1 = (uchar*)CV_NODE_VAL(m1,node1);
        uchar* v2 = cvPtrND( m2, CV_NODE_IDX(m1,node1), 0, 0, &node1->hashval );
        if( !v2 )
            return false;
        if( depth == CV_8U || depth == CV_8S )
        {
            if( *v1 != *v2 )
                return false;
        }
        else if( depth == CV_16U || depth == CV_16S )
        {
            if( *(ushort*)v1 != *(ushort*)v2 )
                return false;
        }
        else if( depth == CV_32S )
        {
            if( *(int*)v1 != *(int*)v2 )
                return false;
        }
        else if( depth == CV_32F )
        {
            if( fabs(*(float*)v1 - *(float*)v2) > eps*(fabs(*(float*)v2) + 1) )
                return false;
        }
        else if( fabs(*(double*)v1 - *(double*)v2) > eps*(fabs(*(double*)v2) + 1) )
            return false;
    }
78

79 80 81 82 83 84 85
    return true;
}


class Core_IOTest : public cvtest::BaseTest
{
public:
86
    Core_IOTest() { }
87 88 89 90 91 92 93 94 95
protected:
    void run(int)
    {
        double ranges[][2] = {{0, 256}, {-128, 128}, {0, 65536}, {-32768, 32768},
            {-1000000, 1000000}, {-10, 10}, {-10, 10}};
        RNG& rng = ts->get_rng();
        RNG rng0;
        int progress = 0;
        MemStorage storage(cvCreateMemStorage(0));
M
MYLS 已提交
96 97
        const char * suffixs[3] = {".yml", ".xml", ".json" };
        test_case_count = 6;
98

99 100 101 102
        for( int idx = 0; idx < test_case_count; idx++ )
        {
            ts->update_context( this, idx, false );
            progress = update_progress( progress, idx, test_case_count, 0 );
103

104
            cvClearMemStorage(storage);
105

M
MYLS 已提交
106 107
            bool mem = (idx % test_case_count) >= (test_case_count >> 1);
            string filename = tempfile(suffixs[idx % (test_case_count >> 1)]);
108

109
            FileStorage fs(filename, FileStorage::WRITE + (mem ? FileStorage::MEMORY : 0));
110

111 112 113
            int test_int = (int)cvtest::randInt(rng);
            double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9);
            string test_string = "vw wv23424rt\"&amp;&lt;&gt;&amp;&apos;@#$@$%$%&%IJUKYILFD@#$@%$&*&() ";
114

115 116 117
            int depth = cvtest::randInt(rng) % (CV_64F+1);
            int cn = cvtest::randInt(rng) % 4 + 1;
            Mat test_mat(cvtest::randInt(rng)%30+1, cvtest::randInt(rng)%30+1, CV_MAKETYPE(depth, cn));
118

119 120 121 122 123 124 125 126
            rng0.fill(test_mat, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
            if( depth >= CV_32F )
            {
                exp(test_mat, test_mat);
                Mat test_mat_scale(test_mat.size(), test_mat.type());
                rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
                multiply(test_mat, test_mat_scale, test_mat);
            }
127

128 129
            CvSeq* seq = cvCreateSeq(test_mat.type(), (int)sizeof(CvSeq),
                                     (int)test_mat.elemSize(), storage);
130
            cvSeqPushMulti(seq, test_mat.ptr(), test_mat.cols*test_mat.rows);
131

132 133 134 135 136 137 138 139 140 141 142 143 144
            CvGraph* graph = cvCreateGraph( CV_ORIENTED_GRAPH,
                                           sizeof(CvGraph), sizeof(CvGraphVtx),
                                           sizeof(CvGraphEdge), storage );
            int edges[][2] = {{0,1},{1,2},{2,0},{0,3},{3,4},{4,1}};
            int i, vcount = 5, ecount = 6;
            for( i = 0; i < vcount; i++ )
                cvGraphAddVtx(graph);
            for( i = 0; i < ecount; i++ )
            {
                CvGraphEdge* edge;
                cvGraphAddEdge(graph, edges[i][0], edges[i][1], 0, &edge);
                edge->weight = (float)(i+1);
            }
145

146 147
            depth = cvtest::randInt(rng) % (CV_64F+1);
            cn = cvtest::randInt(rng) % 4 + 1;
148 149 150 151 152
            int sz[] = {
                static_cast<int>(cvtest::randInt(rng)%10+1),
                static_cast<int>(cvtest::randInt(rng)%10+1),
                static_cast<int>(cvtest::randInt(rng)%10+1),
            };
153
            MatND test_mat_nd(3, sz, CV_MAKETYPE(depth, cn));
154

155 156 157 158 159 160 161 162
            rng0.fill(test_mat_nd, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
            if( depth >= CV_32F )
            {
                exp(test_mat_nd, test_mat_nd);
                MatND test_mat_scale(test_mat_nd.dims, test_mat_nd.size, test_mat_nd.type());
                rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
                multiply(test_mat_nd, test_mat_scale, test_mat_nd);
            }
163

164 165 166 167 168 169
            int ssz[] = {
                static_cast<int>(cvtest::randInt(rng)%10+1),
                static_cast<int>(cvtest::randInt(rng)%10+1),
                static_cast<int>(cvtest::randInt(rng)%10+1),
                static_cast<int>(cvtest::randInt(rng)%10+1),
            };
170 171
            SparseMat test_sparse_mat = cvTsGetRandomSparseMat(4, ssz, cvtest::randInt(rng)%(CV_64F+1),
                                                               cvtest::randInt(rng) % 10000, 0, 100, rng);
172

173 174 175 176
            fs << "test_int" << test_int << "test_real" << test_real << "test_string" << test_string;
            fs << "test_mat" << test_mat;
            fs << "test_mat_nd" << test_mat_nd;
            fs << "test_sparse_mat" << test_sparse_mat;
177

178 179 180
            fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
            "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
            fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
181

182 183
            const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
            fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
184

185 186
            fs << "]" << "}";
            cvWriteComment(*fs, "test comment", 0);
187

188 189 190
            fs.writeObj("test_seq", seq);
            fs.writeObj("test_graph",graph);
            CvGraph* graph2 = (CvGraph*)cvClone(graph);
191

192
            string content = fs.releaseAndGetString();
193

194
            if(!fs.open(mem ? content : filename, FileStorage::READ + (mem ? FileStorage::MEMORY : 0)))
195
            {
196
                ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", !mem ? filename.c_str() : content.c_str());
197 198 199
                ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
                return;
            }
200

201 202
            int real_int = (int)fs["test_int"];
            double real_real = (double)fs["test_real"];
203
            String real_string = (String)fs["test_string"];
204

205 206 207 208 209 210 211 212
            if( real_int != test_int ||
               fabs(real_real - test_real) > DBL_EPSILON*(fabs(test_real)+1) ||
               real_string != test_string )
            {
                ts->printf( cvtest::TS::LOG, "the read scalars are not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
213

214 215 216 217 218 219 220
            CvMat* m = (CvMat*)fs["test_mat"].readObj();
            CvMat _test_mat = test_mat;
            double max_diff = 0;
            CvMat stub1, _test_stub1;
            cvReshape(m, &stub1, 1, 0);
            cvReshape(&_test_mat, &_test_stub1, 1, 0);
            vector<int> pt;
221

222
            if( !m || !CV_IS_MAT(m) || m->rows != test_mat.rows || m->cols != test_mat.cols ||
A
Andrey Kamaev 已提交
223
               cvtest::cmpEps( cv::cvarrToMat(&stub1), cv::cvarrToMat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
224 225 226 227 228 229 230 231 232
            {
                ts->printf( cvtest::TS::LOG, "the read matrix is not correct: (%.20g vs %.20g) at (%d,%d)\n",
                            cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[0], pt[1]),
                            pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
            if( m && CV_IS_MAT(m))
                cvReleaseMat(&m);
233

234 235
            CvMatND* m_nd = (CvMatND*)fs["test_mat_nd"].readObj();
            CvMatND _test_mat_nd = test_mat_nd;
236

237 238 239 240 241 242
            if( !m_nd || !CV_IS_MATND(m_nd) )
            {
                ts->printf( cvtest::TS::LOG, "the read nd-matrix is not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
243

244 245 246 247 248
            CvMat stub, _test_stub;
            cvGetMat(m_nd, &stub, 0, 1);
            cvGetMat(&_test_mat_nd, &_test_stub, 0, 1);
            cvReshape(&stub, &stub1, 1, 0);
            cvReshape(&_test_stub, &_test_stub1, 1, 0);
249

250 251
            if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
               !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
252
               //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
A
Andrey Kamaev 已提交
253
               cvtest::cmpEps( cv::cvarrToMat(&stub1), cv::cvarrToMat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
254 255 256 257 258 259 260
            {
                ts->printf( cvtest::TS::LOG, "readObj method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
                           cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[0], pt[1]),
                           pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
261

262 263 264 265 266
            MatND mat_nd2;
            fs["test_mat_nd"] >> mat_nd2;
            CvMatND m_nd2 = mat_nd2;
            cvGetMat(&m_nd2, &stub, 0, 1);
            cvReshape(&stub, &stub1, 1, 0);
267

268 269
            if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
               !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
270
               //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
A
Andrey Kamaev 已提交
271
               cvtest::cmpEps( cv::cvarrToMat(&stub1), cv::cvarrToMat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
272 273 274 275 276 277 278
            {
                ts->printf( cvtest::TS::LOG, "C++ method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
                           cvGetReal2D(&stub1, pt[0], pt[1]), cvGetReal2D(&_test_stub1, pt[1], pt[0]),
                           pt[0], pt[1] );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
279

280
            cvRelease((void**)&m_nd);
281

R
Roman Donchenko 已提交
282 283 284
            Ptr<CvSparseMat> m_s((CvSparseMat*)fs["test_sparse_mat"].readObj());
            Ptr<CvSparseMat> _test_sparse_(cvCreateSparseMat(test_sparse_mat));
            Ptr<CvSparseMat> _test_sparse((CvSparseMat*)cvClone(_test_sparse_));
285 286
            SparseMat m_s2;
            fs["test_sparse_mat"] >> m_s2;
R
Roman Donchenko 已提交
287
            Ptr<CvSparseMat> _m_s2(cvCreateSparseMat(m_s2));
288

289
            if( !m_s || !CV_IS_SPARSE_MAT(m_s) ||
R
Roman Donchenko 已提交
290 291
               !cvTsCheckSparse(m_s, _test_sparse, 0) ||
               !cvTsCheckSparse(_m_s2, _test_sparse, 0))
292 293 294 295 296
            {
                ts->printf( cvtest::TS::LOG, "the read sparse matrix is not correct\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
297

298 299 300 301 302 303
            FileNode tl = fs["test_list"];
            if( tl.type() != FileNode::SEQ || tl.size() != 6 ||
               fabs((double)tl[0] - 0.0000000000001) >= DBL_EPSILON ||
               (int)tl[1] != 2 ||
               fabs((double)tl[2] - CV_PI) >= DBL_EPSILON ||
               (int)tl[3] != -3435345 ||
304
               (String)tl[4] != "2-502 2-029 3egegeg" ||
305 306 307 308 309 310 311 312 313
               tl[5].type() != FileNode::MAP || tl[5].size() != 3 ||
               (int)tl[5]["month"] != 12 ||
               (int)tl[5]["day"] != 31 ||
               (int)tl[5]["year"] != 1969 )
            {
                ts->printf( cvtest::TS::LOG, "the test list is incorrect\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
314

315 316
            FileNode tm = fs["test_map"];
            FileNode tm_lbp = tm["lbp"];
317

318 319 320 321
            int real_x = (int)tm["x"];
            int real_y = (int)tm["y"];
            int real_width = (int)tm["width"];
            int real_height = (int)tm["height"];
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            int real_lbp_val = 0;
            FileNodeIterator it;
            it = tm_lbp.begin();
            real_lbp_val |= (int)*it << 0;
            ++it;
            real_lbp_val |= (int)*it << 1;
            it++;
            real_lbp_val |= (int)*it << 2;
            it += 1;
            real_lbp_val |= (int)*it << 3;
            FileNodeIterator it2(it);
            it2 += 4;
            real_lbp_val |= (int)*it2 << 7;
            --it2;
            real_lbp_val |= (int)*it2 << 6;
            it2--;
            real_lbp_val |= (int)*it2 << 5;
            it2 -= 1;
            real_lbp_val |= (int)*it2 << 4;
            it2 += -1;
            CV_Assert( it == it2 );
344

345 346 347 348 349 350 351 352 353 354 355 356 357
            if( tm.type() != FileNode::MAP || tm.size() != 5 ||
               real_x != 1 ||
               real_y != 2 ||
               real_width != 100 ||
               real_height != 200 ||
               tm_lbp.type() != FileNode::SEQ ||
               tm_lbp.size() != 8 ||
               real_lbp_val != 0xb6 )
            {
                ts->printf( cvtest::TS::LOG, "the test map is incorrect\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
358

359 360 361 362 363 364 365 366
            CvGraph* graph3 = (CvGraph*)fs["test_graph"].readObj();
            if(graph2->active_count != vcount || graph3->active_count != vcount ||
               graph2->edges->active_count != ecount || graph3->edges->active_count != ecount)
            {
                ts->printf( cvtest::TS::LOG, "the cloned or read graph have wrong number of vertices or edges\n" );
                ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                return;
            }
367

368 369 370 371 372 373 374 375 376 377 378 379
            for( i = 0; i < ecount; i++ )
            {
                CvGraphEdge* edge2 = cvFindGraphEdge(graph2, edges[i][0], edges[i][1]);
                CvGraphEdge* edge3 = cvFindGraphEdge(graph3, edges[i][0], edges[i][1]);
                if( !edge2 || edge2->weight != (float)(i+1) ||
                   !edge3 || edge3->weight != (float)(i+1) )
                {
                    ts->printf( cvtest::TS::LOG, "the cloned or read graph do not have the edge (%d, %d)\n", edges[i][0], edges[i][1] );
                    ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
                    return;
                }
            }
380

381
            fs.release();
382 383
            if( !mem )
                remove(filename.c_str());
384 385 386 387 388
        }
    }
};

TEST(Core_InputOutput, write_read_consistency) { Core_IOTest test; test.safe_run(); }
389

390
extern void testFormatter();
391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

struct UserDefinedType
{
    int a;
    float b;
};

static inline bool operator==(const UserDefinedType &x,
                              const UserDefinedType &y) {
    return (x.a == y.a) && (x.b == y.b);
}

static inline void write(FileStorage &fs,
                         const String&,
                         const UserDefinedType &value)
{
    fs << "{:" << "a" << value.a << "b" << value.b << "}";
}

static inline void read(const FileNode& node,
                        UserDefinedType& value,
                        const UserDefinedType& default_value
                          = UserDefinedType()) {
    if(node.empty())
    {
        value = default_value;
    }
    else
    {
        node["a"] >> value.a;
        node["b"] >> value.b;
    }
}

426 427 428 429
class CV_MiscIOTest : public cvtest::BaseTest
{
public:
    CV_MiscIOTest() {}
430
    ~CV_MiscIOTest() {}
431 432 433
protected:
    void run(int)
    {
M
MYLS 已提交
434 435 436 437 438
        const char * suffix[3] = {
            ".yml",
            ".xml",
            ".json"
        };
439

M
MYLS 已提交
440
        for ( size_t i = 0u; i < 3u; i++ )
441
        {
M
MYLS 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
            try
            {
                string fname = cv::tempfile(suffix[i]);
                vector<int> mi, mi2, mi3, mi4;
                vector<Mat> mv, mv2, mv3, mv4;
                vector<UserDefinedType> vudt, vudt2, vudt3, vudt4;
                Mat m(10, 9, CV_32F);
                Mat empty;
                UserDefinedType udt = { 8, 3.3f };
                randu(m, 0, 1);
                mi3.push_back(5);
                mv3.push_back(m);
                vudt3.push_back(udt);
                Point_<float> p1(1.1f, 2.2f), op1;
                Point3i p2(3, 4, 5), op2;
                Size s1(6, 7), os1;
                Complex<int> c1(9, 10), oc1;
                Rect r1(11, 12, 13, 14), or1;
                Vec<int, 5> v1(15, 16, 17, 18, 19), ov1;
                Scalar sc1(20.0, 21.1, 22.2, 23.3), osc1;
                Range g1(7, 8), og1;

                FileStorage fs(fname, FileStorage::WRITE);
                fs << "mi" << mi;
                fs << "mv" << mv;
                fs << "mi3" << mi3;
                fs << "mv3" << mv3;
                fs << "vudt" << vudt;
                fs << "vudt3" << vudt3;
                fs << "empty" << empty;
                fs << "p1" << p1;
                fs << "p2" << p2;
                fs << "s1" << s1;
                fs << "c1" << c1;
                fs << "r1" << r1;
                fs << "v1" << v1;
                fs << "sc1" << sc1;
                fs << "g1" << g1;
                fs.release();

                fs.open(fname, FileStorage::READ);
                fs["mi"] >> mi2;
                fs["mv"] >> mv2;
                fs["mi3"] >> mi4;
                fs["mv3"] >> mv4;
                fs["vudt"] >> vudt2;
                fs["vudt3"] >> vudt4;
                fs["empty"] >> empty;
                fs["p1"] >> op1;
                fs["p2"] >> op2;
                fs["s1"] >> os1;
                fs["c1"] >> oc1;
                fs["r1"] >> or1;
                fs["v1"] >> ov1;
                fs["sc1"] >> osc1;
                fs["g1"] >> og1;
                CV_Assert( mi2.empty() );
                CV_Assert( mv2.empty() );
                CV_Assert( cvtest::norm(Mat(mi3), Mat(mi4), CV_C) == 0 );
                CV_Assert( mv4.size() == 1 );
                double n = cvtest::norm(mv3[0], mv4[0], CV_C);
                CV_Assert( vudt2.empty() );
                CV_Assert( vudt3 == vudt4 );
                CV_Assert( n == 0 );
                CV_Assert( op1 == p1 );
                CV_Assert( op2 == p2 );
                CV_Assert( os1 == s1 );
                CV_Assert( oc1 == c1 );
                CV_Assert( or1 == r1 );
                CV_Assert( ov1 == v1 );
                CV_Assert( osc1 == sc1 );
                CV_Assert( og1 == g1 );
            }
            catch(...)
            {
                ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
            }
519 520 521 522 523 524
        }
    }
};

TEST(Core_InputOutput, misc) { CV_MiscIOTest test; test.safe_run(); }

525 526 527 528
/*class CV_BigMatrixIOTest : public cvtest::BaseTest
{
public:
    CV_BigMatrixIOTest() {}
529
    ~CV_BigMatrixIOTest() {}
530 531 532 533 534 535 536 537 538
protected:
    void run(int)
    {
        try
        {
            RNG& rng = theRNG();
            int N = 1000, M = 1200000;
            Mat mat(M, N, CV_32F);
            rng.fill(mat, RNG::UNIFORM, 0, 1);
539
            FileStorage fs(cv::tempfile(".xml"), FileStorage::WRITE);
540 541 542 543 544 545 546 547 548 549 550 551 552
            fs << "mat" << mat;
            fs.release();
        }
        catch(...)
        {
            ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
        }
    }
};

TEST(Core_InputOutput, huge) { CV_BigMatrixIOTest test; test.safe_run(); }
*/

553
TEST(Core_globbing, accuracy)
M
marina.kolpakova 已提交
554 555 556 557
{
    std::string patternLena    = cvtest::TS::ptr()->get_data_path() + "lena*.*";
    std::string patternLenaPng = cvtest::TS::ptr()->get_data_path() + "lena.png";

558
    std::vector<String> lenas, pngLenas;
M
marina.kolpakova 已提交
559 560 561 562 563 564 565 566 567
    cv::glob(patternLena, lenas, true);
    cv::glob(patternLenaPng, pngLenas, true);

    ASSERT_GT(lenas.size(), pngLenas.size());

    for (size_t i = 0; i < pngLenas.size(); ++i)
    {
        ASSERT_NE(std::find(lenas.begin(), lenas.end(), pngLenas[i]), lenas.end());
    }
A
Andrey Kamaev 已提交
568 569
}

570 571 572 573 574 575 576 577 578
TEST(Core_InputOutput, FileStorage)
{
    std::string file = cv::tempfile(".xml");
    cv::FileStorage f(file, cv::FileStorage::WRITE);

    char arr[66];
    sprintf(arr, "sprintf is hell %d", 666);
    EXPECT_NO_THROW(f << arr);
}
579 580 581 582 583 584 585 586

TEST(Core_InputOutput, FileStorageKey)
{
    cv::FileStorage f("dummy.yml", cv::FileStorage::WRITE | cv::FileStorage::MEMORY);

    EXPECT_NO_THROW(f << "key1" << "value1");
    EXPECT_NO_THROW(f << "_key2" << "value2");
    EXPECT_NO_THROW(f << "key_3" << "value3");
587
    const std::string expected = "%YAML:1.0\n---\nkey1: value1\n_key2: value2\nkey_3: value3\n";
588 589
    ASSERT_STREQ(f.releaseAndGetString().c_str(), expected.c_str());
}
M
MYLS 已提交
590

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
TEST(Core_InputOutput, FileStorageSpaces)
{
    cv::FileStorage f("dummy.yml", cv::FileStorage::WRITE | cv::FileStorage::MEMORY);
    const int valueCount = 5;
    std::string values[5] = { "", " ", " ", "  a", " some string" };
    for (size_t i = 0; i < valueCount; i++) {
        EXPECT_NO_THROW(f << cv::format("key%d", i) << values[i]);
    }
    cv::FileStorage f2(f.releaseAndGetString(), cv::FileStorage::READ | cv::FileStorage::MEMORY);
    std::string valuesRead[valueCount];
    for (size_t i = 0; i < valueCount; i++) {
        EXPECT_NO_THROW(f2[cv::format("key%d", i)] >> valuesRead[i]);
        ASSERT_STREQ(values[i].c_str(), valuesRead[i].c_str());
    }
}

607
struct data_t
M
MYLS 已提交
608
{
609 610 611 612 613 614 615 616
    typedef uchar  u;
    typedef char   b;
    typedef ushort w;
    typedef short  s;
    typedef int    i;
    typedef float  f;
    typedef double d;

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    /*0x00*/ u u1   ;u u2   ;                i i1                           ;
    /*0x08*/ i i2                           ;i i3                           ;
    /*0x10*/ d d1                                                           ;
    /*0x18*/ d d2                                                           ;
    /*0x20*/ i i4                           ;i required_alignment_field_for_linux32;
    /*
     * OpenCV persistence.cpp stuff expects: sizeof(data_t) = alignSize(36, sizeof(largest type = double)) = 40
     * Some compilers on some archs returns sizeof(data_t) = 36 due struct packaging UB
     */

    static inline const char * signature() {
        if (sizeof(data_t) != 40)
        {
            printf("sizeof(data_t)=%d, u1=%p u2=%p i1=%p i2=%p i3=%p d1=%p d2=%p i4=%p\n", (int)sizeof(data_t),
                    &(((data_t*)0)->u1),
                    &(((data_t*)0)->u2),
                    &(((data_t*)0)->i1),
                    &(((data_t*)0)->i2),
                    &(((data_t*)0)->i3),
                    &(((data_t*)0)->d1),
                    &(((data_t*)0)->d2),
                    &(((data_t*)0)->i4)
            );
        }
        CV_Assert(sizeof(data_t) == 40);
        CV_Assert((size_t)&(((data_t*)0)->u1) == 0x0);
        CV_Assert((size_t)&(((data_t*)0)->u2) == 0x1);
        CV_Assert((size_t)&(((data_t*)0)->i1) == 0x4);
        CV_Assert((size_t)&(((data_t*)0)->i2) == 0x8);
        CV_Assert((size_t)&(((data_t*)0)->i3) == 0xc);
        CV_Assert((size_t)&(((data_t*)0)->d1) == 0x10);
        CV_Assert((size_t)&(((data_t*)0)->d2) == 0x18);
        CV_Assert((size_t)&(((data_t*)0)->i4) == 0x20);
        return "2u3i2di";
    }
652
};
M
MYLS 已提交
653

654
TEST(Core_InputOutput, filestorage_base64_basic)
M
MYLS 已提交
655
{
656 657 658
    char const * filenames[] = {
        "core_io_base64_basic_test.yml",
        "core_io_base64_basic_test.xml",
M
MYLS 已提交
659
        "core_io_base64_basic_test.json",
660
        0
M
MYLS 已提交
661 662
    };

663
    for (char const ** ptr = filenames; *ptr; ptr++)
664
    {
665
        char const * name = *ptr;
M
MYLS 已提交
666

667
        std::vector<data_t> rawdata;
M
MYLS 已提交
668

669 670 671 672
        cv::Mat _em_out, _em_in;
        cv::Mat _2d_out, _2d_in;
        cv::Mat _nd_out, _nd_in;
        cv::Mat _rd_out(64, 64, CV_64FC1), _rd_in;
M
MYLS 已提交
673

M
MYLS 已提交
674 675
        bool no_type_id = true;

676
        {   /* init */
M
MYLS 已提交
677

678 679 680 681 682
            /* a normal mat */
            _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U));
            for (int i = 0; i < _2d_out.rows; ++i)
                for (int j = 0; j < _2d_out.cols; ++j)
                    _2d_out.at<cv::Vec3b>(i, j)[1] = (i + j) % 256;
683

684 685 686 687 688 689 690 691 692 693 694 695
            /* a 4d mat */
            const int Size[] = {4, 4, 4, 4};
            cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444));
            const cv::Range ranges[] = {
                cv::Range(0, 2),
                cv::Range(0, 2),
                cv::Range(1, 2),
                cv::Range(0, 2) };
            _nd_out = _4d(ranges);

            /* a random mat */
            cv::randu(_rd_out, cv::Scalar(0.0), cv::Scalar(1.0));
696

697
            /* raw data */
698
            for (int i = 0; i < 1000; i++) {
699 700 701 702 703 704 705 706 707 708
                data_t tmp;
                tmp.u1 = 1;
                tmp.u2 = 2;
                tmp.i1 = 1;
                tmp.i2 = 2;
                tmp.i3 = 3;
                tmp.d1 = 0.1;
                tmp.d2 = 0.2;
                tmp.i4 = i;
                rawdata.push_back(tmp);
709
            }
710
        }
M
MYLS 已提交
711

712 713 714 715 716 717 718 719 720 721 722 723 724
        {   /* write */
            cv::FileStorage fs(name, cv::FileStorage::WRITE_BASE64);
            fs << "normal_2d_mat" << _2d_out;
            fs << "normal_nd_mat" << _nd_out;
            fs << "empty_2d_mat"  << _em_out;
            fs << "random_mat"    << _rd_out;

            cvStartWriteStruct( *fs, "rawdata", CV_NODE_SEQ | CV_NODE_FLOW, "binary" );
            for (int i = 0; i < 10; i++)
                cvWriteRawDataBase64(*fs, rawdata.data() + i * 100, 100, data_t::signature());
            cvEndWriteStruct( *fs );

            fs.release();
725
        }
726 727 728 729 730 731 732 733 734 735

        {   /* read */
            cv::FileStorage fs(name, cv::FileStorage::READ);

            /* mat */
            fs["empty_2d_mat"]  >> _em_in;
            fs["normal_2d_mat"] >> _2d_in;
            fs["normal_nd_mat"] >> _nd_in;
            fs["random_mat"]    >> _rd_in;

M
MYLS 已提交
736 737 738 739 740 741
            if ( !fs["empty_2d_mat"]["type_id"].empty() ||
                !fs["normal_2d_mat"]["type_id"].empty() ||
                !fs["normal_nd_mat"]["type_id"].empty() ||
                !fs[   "random_mat"]["type_id"].empty() )
                no_type_id = false;

742 743 744 745 746
            /* raw data */
            std::vector<data_t>(1000).swap(rawdata);
            cvReadRawData(*fs, fs["rawdata"].node, rawdata.data(), data_t::signature());

            fs.release();
747
        }
748

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
        int errors = 0;
        for (int i = 0; i < 1000; i++)
        {
            EXPECT_EQ((int)rawdata[i].u1, 1);
            EXPECT_EQ((int)rawdata[i].u2, 2);
            EXPECT_EQ((int)rawdata[i].i1, 1);
            EXPECT_EQ((int)rawdata[i].i2, 2);
            EXPECT_EQ((int)rawdata[i].i3, 3);
            EXPECT_EQ(rawdata[i].d1, 0.1);
            EXPECT_EQ(rawdata[i].d2, 0.2);
            EXPECT_EQ((int)rawdata[i].i4, i);
            if (::testing::Test::HasNonfatalFailure())
            {
                printf("i = %d\n", i);
                errors++;
            }
            if (errors >= 3)
                break;
767 768
        }

M
MYLS 已提交
769 770
        EXPECT_TRUE(no_type_id);

771 772 773 774 775 776 777 778 779
        EXPECT_EQ(_em_in.rows   , _em_out.rows);
        EXPECT_EQ(_em_in.cols   , _em_out.cols);
        EXPECT_EQ(_em_in.depth(), _em_out.depth());
        EXPECT_TRUE(_em_in.empty());

        EXPECT_EQ(_2d_in.rows   , _2d_out.rows);
        EXPECT_EQ(_2d_in.cols   , _2d_out.cols);
        EXPECT_EQ(_2d_in.dims   , _2d_out.dims);
        EXPECT_EQ(_2d_in.depth(), _2d_out.depth());
780 781

        errors = 0;
782
        for(int i = 0; i < _2d_out.rows; ++i)
783
        {
784
            for (int j = 0; j < _2d_out.cols; ++j)
785
            {
786
                EXPECT_EQ(_2d_in.at<cv::Vec3b>(i, j), _2d_out.at<cv::Vec3b>(i, j));
787 788 789 790 791 792 793 794 795 796 797 798
                if (::testing::Test::HasNonfatalFailure())
                {
                    printf("i = %d, j = %d\n", i, j);
                    errors++;
                }
                if (errors >= 3)
                {
                    i = _2d_out.rows;
                    break;
                }
            }
        }
799 800 801 802 803 804 805 806 807 808 809 810 811 812

        EXPECT_EQ(_nd_in.rows   , _nd_out.rows);
        EXPECT_EQ(_nd_in.cols   , _nd_out.cols);
        EXPECT_EQ(_nd_in.dims   , _nd_out.dims);
        EXPECT_EQ(_nd_in.depth(), _nd_out.depth());
        EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0);

        EXPECT_EQ(_rd_in.rows   , _rd_out.rows);
        EXPECT_EQ(_rd_in.cols   , _rd_out.cols);
        EXPECT_EQ(_rd_in.dims   , _rd_out.dims);
        EXPECT_EQ(_rd_in.depth(), _rd_out.depth());
        EXPECT_EQ(cv::countNonZero(cv::mean(_rd_in != _rd_out)), 0);

        remove(name);
M
MYLS 已提交
813
    }
814
}
815

816
TEST(Core_InputOutput, filestorage_base64_valid_call)
817
{
818 819 820
    char const * filenames[] = {
        "core_io_base64_other_test.yml",
        "core_io_base64_other_test.xml",
M
MYLS 已提交
821
        "core_io_base64_other_test.json",
822 823
        "core_io_base64_other_test.yml?base64",
        "core_io_base64_other_test.xml?base64",
M
MYLS 已提交
824
        "core_io_base64_other_test.json?base64",
825 826 827 828 829
        0
    };
    char const * real_name[] = {
        "core_io_base64_other_test.yml",
        "core_io_base64_other_test.xml",
M
MYLS 已提交
830
        "core_io_base64_other_test.json",
831 832
        "core_io_base64_other_test.yml",
        "core_io_base64_other_test.xml",
M
MYLS 已提交
833
        "core_io_base64_other_test.json",
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
        0
    };

    std::vector<int> rawdata(10, static_cast<int>(0x00010203));
    cv::String str_out = "test_string";

    for (char const ** ptr = filenames; *ptr; ptr++)
    {
        char const * name = *ptr;

        EXPECT_NO_THROW(
        {
            cv::FileStorage fs(name, cv::FileStorage::WRITE_BASE64);

            cvStartWriteStruct(*fs, "manydata", CV_NODE_SEQ);
            cvStartWriteStruct(*fs, 0, CV_NODE_SEQ | CV_NODE_FLOW);
            for (int i = 0; i < 10; i++)
                cvWriteRawData(*fs, rawdata.data(), static_cast<int>(rawdata.size()), "i");
            cvEndWriteStruct(*fs);
            cvWriteString(*fs, 0, str_out.c_str(), 1);
            cvEndWriteStruct(*fs);

            fs.release();
        });

        {
            cv::FileStorage fs(name, cv::FileStorage::READ);
            std::vector<int> data_in(rawdata.size());
            fs["manydata"][0].readRaw("i", (uchar *)data_in.data(), data_in.size());
            EXPECT_TRUE(fs["manydata"][0].isSeq());
            EXPECT_TRUE(std::equal(rawdata.begin(), rawdata.end(), data_in.begin()));
            cv::String str_in;
            fs["manydata"][1] >> str_in;
            EXPECT_TRUE(fs["manydata"][1].isString());
            EXPECT_EQ(str_in, str_out);
            fs.release();
        }

        EXPECT_NO_THROW(
        {
            cv::FileStorage fs(name, cv::FileStorage::WRITE);

            cvStartWriteStruct(*fs, "manydata", CV_NODE_SEQ);
            cvWriteString(*fs, 0, str_out.c_str(), 1);
            cvStartWriteStruct(*fs, 0, CV_NODE_SEQ | CV_NODE_FLOW, "binary");
            for (int i = 0; i < 10; i++)
                cvWriteRawData(*fs, rawdata.data(), static_cast<int>(rawdata.size()), "i");
            cvEndWriteStruct(*fs);
            cvEndWriteStruct(*fs);

            fs.release();
        });

        {
            cv::FileStorage fs(name, cv::FileStorage::READ);
            cv::String str_in;
            fs["manydata"][0] >> str_in;
            EXPECT_TRUE(fs["manydata"][0].isString());
            EXPECT_EQ(str_in, str_out);
            std::vector<int> data_in(rawdata.size());
            fs["manydata"][1].readRaw("i", (uchar *)data_in.data(), data_in.size());
            EXPECT_TRUE(fs["manydata"][1].isSeq());
            EXPECT_TRUE(std::equal(rawdata.begin(), rawdata.end(), data_in.begin()));
            fs.release();
        }

        remove(real_name[ptr - filenames]);
    }
902
}
M
MYLS 已提交
903

904
TEST(Core_InputOutput, filestorage_base64_invalid_call)
905
{
906 907 908
    char const * filenames[] = {
        "core_io_base64_other_test.yml",
        "core_io_base64_other_test.xml",
M
MYLS 已提交
909
        "core_io_base64_other_test.json",
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
        0
    };

    for (char const ** ptr = filenames; *ptr; ptr++)
    {
        char const * name = *ptr;

        EXPECT_ANY_THROW({
            cv::FileStorage fs(name, cv::FileStorage::WRITE);
            cvStartWriteStruct(*fs, "rawdata", CV_NODE_SEQ, "binary");
            cvStartWriteStruct(*fs, 0, CV_NODE_SEQ | CV_NODE_FLOW);
        });

        EXPECT_ANY_THROW({
            cv::FileStorage fs(name, cv::FileStorage::WRITE);
            cvStartWriteStruct(*fs, "rawdata", CV_NODE_SEQ);
            cvStartWriteStruct(*fs, 0, CV_NODE_SEQ | CV_NODE_FLOW);
            cvWriteRawDataBase64(*fs, name, 1, "u");
        });

        remove(name);
    }
M
MYLS 已提交
932
}
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

TEST(Core_InputOutput, filestorage_yml_vec2i)
{
    const std::string file_name = "vec2i.yml";
    cv::Vec2i vec(2, 1), ovec;

    /* write */
    {
        cv::FileStorage fs(file_name, cv::FileStorage::WRITE);
        fs << "prms0" << "{" << "vec0" << vec << "}";
        fs.release();
    }

    /* read */
    {
        cv::FileStorage fs(file_name, cv::FileStorage::READ);
        fs["prms0"]["vec0"] >> ovec;
        fs.release();
    }

    EXPECT_EQ(vec(0), ovec(0));
    EXPECT_EQ(vec(1), ovec(1));

    remove(file_name.c_str());
}
M
MYLS 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

TEST(Core_InputOutput, filestorage_json_comment)
{
    String mem_str =
        "{ /* comment */\n"
        "  \"key\": \"value\"\n"
        "  /************\n"
        "   * multiline comment\n"
        "   ************/\n"
        "  // 233\n"
        "  // \n"
        "}\n"
        ;

    String str;

    EXPECT_NO_THROW(
    {
        cv::FileStorage fs(mem_str, cv::FileStorage::READ | cv::FileStorage::MEMORY);
        fs["key"] >> str;
        fs.release();
    });

    EXPECT_EQ(str, String("value"));
}
V
Vladislav Sovrasov 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

TEST(Core_InputOutput, filestorage_utf8_bom)
{
    EXPECT_NO_THROW(
    {
        String content ="\xEF\xBB\xBF<?xml version=\"1.0\"?>\n<opencv_storage>\n</opencv_storage>\n";
        cv::FileStorage fs(content, cv::FileStorage::READ | cv::FileStorage::MEMORY);
        fs.release();
    });
    EXPECT_NO_THROW(
    {
        String content ="\xEF\xBB\xBF%YAML:1.0\n";
        cv::FileStorage fs(content, cv::FileStorage::READ | cv::FileStorage::MEMORY);
        fs.release();
    });
    EXPECT_NO_THROW(
    {
        String content ="\xEF\xBB\xBF{\n}\n";
        cv::FileStorage fs(content, cv::FileStorage::READ | cv::FileStorage::MEMORY);
        fs.release();
    });
}
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

TEST(Core_InputOutput, filestorage_vec_vec_io)
{
    std::vector<std::vector<Mat> > outputMats(3);
    for(size_t i = 0; i < outputMats.size(); i++)
    {
        outputMats[i].resize(i+1);
        for(size_t j = 0; j < outputMats[i].size(); j++)
        {
            outputMats[i][j] = Mat::eye((int)i + 1, (int)i + 1, CV_8U);
        }
    }

    String fileName = "vec_test.";

    std::vector<String> formats;
    formats.push_back("xml");
    formats.push_back("yml");
    formats.push_back("json");

    for(size_t i = 0; i < formats.size(); i++)
    {
        FileStorage writer(fileName + formats[i], FileStorage::WRITE);
        writer << "vecVecMat" << outputMats;
        writer.release();

        FileStorage reader(fileName + formats[i], FileStorage::READ);
        std::vector<std::vector<Mat> > testMats;
        reader["vecVecMat"] >> testMats;

        ASSERT_EQ(testMats.size(), testMats.size());

        for(size_t j = 0; j < testMats.size(); j++)
        {
            ASSERT_EQ(testMats[j].size(), outputMats[j].size());

            for(size_t k = 0; k < testMats[j].size(); k++)
            {
                ASSERT_TRUE(norm(outputMats[j][k] - testMats[j][k], NORM_INF) == 0);
            }
        }

        reader.release();
        remove((fileName + formats[i]).c_str());
    }
}
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

TEST(Core_InputOutput, filestorage_yaml_advanvced_type_heading)
{
    String content = "%YAML:1.0\n cameraMatrix: !<tag:yaml.org,2002:opencv-matrix>\n"
            "   rows: 1\n"
            "   cols: 1\n"
            "   dt: d\n"
            "   data: [ 1. ]";

    cv::FileStorage fs(content, cv::FileStorage::READ | cv::FileStorage::MEMORY);

    cv::Mat inputMatrix;
    cv::Mat actualMatrix = cv::Mat::eye(1, 1, CV_64F);
    fs["cameraMatrix"] >> inputMatrix;

    ASSERT_EQ(cv::norm(inputMatrix, actualMatrix, NORM_INF), 0.);
}
1068

1069
TEST(Core_InputOutput, filestorage_keypoints_vec_vec_io)
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
{
    vector<vector<KeyPoint> > kptsVec;
    vector<KeyPoint> kpts;
    kpts.push_back(KeyPoint(0, 0, 1.1f));
    kpts.push_back(KeyPoint(1, 1, 1.1f));
    kptsVec.push_back(kpts);
    kpts.clear();
    kpts.push_back(KeyPoint(0, 0, 1.1f, 10.1f, 34.5f, 10, 11));
    kptsVec.push_back(kpts);

    FileStorage writer("", FileStorage::WRITE + FileStorage::MEMORY + FileStorage::FORMAT_XML);
    writer << "keypoints" << kptsVec;
    String content = writer.releaseAndGetString();

    FileStorage reader(content, FileStorage::READ + FileStorage::MEMORY);
    vector<vector<KeyPoint> > readKptsVec;
    reader["keypoints"] >> readKptsVec;

    ASSERT_EQ(kptsVec.size(), readKptsVec.size());

    for(size_t i = 0; i < kptsVec.size(); i++)
    {
        ASSERT_EQ(kptsVec[i].size(), readKptsVec[i].size());
        for(size_t j = 0; j < kptsVec[i].size(); j++)
        {
            ASSERT_FLOAT_EQ(kptsVec[i][j].pt.x, readKptsVec[i][j].pt.x);
            ASSERT_FLOAT_EQ(kptsVec[i][j].pt.y, readKptsVec[i][j].pt.y);
            ASSERT_FLOAT_EQ(kptsVec[i][j].angle, readKptsVec[i][j].angle);
            ASSERT_FLOAT_EQ(kptsVec[i][j].size, readKptsVec[i][j].size);
            ASSERT_FLOAT_EQ(kptsVec[i][j].response, readKptsVec[i][j].response);
            ASSERT_EQ(kptsVec[i][j].octave, readKptsVec[i][j].octave);
            ASSERT_EQ(kptsVec[i][j].class_id, readKptsVec[i][j].class_id);
        }
    }
}

A
Alexander Alekhin 已提交
1106 1107 1108 1109 1110 1111 1112 1113
TEST(Core_InputOutput, FileStorage_DMatch)
{
    cv::FileStorage fs("dmatch.yml", cv::FileStorage::WRITE | cv::FileStorage::MEMORY);

    cv::DMatch d(1, 2, 3, -1.5f);

    EXPECT_NO_THROW(fs << "d" << d);
    cv::String fs_result = fs.releaseAndGetString();
T
Tomoaki Teshima 已提交
1114 1115 1116
#if defined _MSC_VER && _MSC_VER <= 1700 /* MSVC 2012 and older */
    EXPECT_STREQ(fs_result.c_str(), "%YAML:1.0\n---\nd: [ 1, 2, 3, -1.5000000000000000e+000 ]\n");
#else
A
Alexander Alekhin 已提交
1117
    EXPECT_STREQ(fs_result.c_str(), "%YAML:1.0\n---\nd: [ 1, 2, 3, -1.5000000000000000e+00 ]\n");
T
Tomoaki Teshima 已提交
1118
#endif
A
Alexander Alekhin 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

    cv::FileStorage fs_read(fs_result, cv::FileStorage::READ | cv::FileStorage::MEMORY);

    cv::DMatch d_read;
    ASSERT_NO_THROW(fs_read["d"] >> d_read);

    EXPECT_EQ(d.queryIdx, d_read.queryIdx);
    EXPECT_EQ(d.trainIdx, d_read.trainIdx);
    EXPECT_EQ(d.imgIdx, d_read.imgIdx);
    EXPECT_EQ(d.distance, d_read.distance);
}

TEST(Core_InputOutput, FileStorage_DMatch_vector)
{
    cv::FileStorage fs("dmatch.yml", cv::FileStorage::WRITE | cv::FileStorage::MEMORY);

    cv::DMatch d1(1, 2, 3, -1.5f);
    cv::DMatch d2(2, 3, 4, 1.5f);
    cv::DMatch d3(3, 2, 1, 0.5f);
    std::vector<cv::DMatch> dv;
    dv.push_back(d1);
    dv.push_back(d2);
    dv.push_back(d3);

    EXPECT_NO_THROW(fs << "dv" << dv);
    cv::String fs_result = fs.releaseAndGetString();
T
Tomoaki Teshima 已提交
1145 1146 1147 1148 1149 1150 1151 1152
#if defined _MSC_VER && _MSC_VER <= 1700 /* MSVC 2012 and older */
    EXPECT_STREQ(fs_result.c_str(),
"%YAML:1.0\n"
"---\n"
"dv: [ 1, 2, 3, -1.5000000000000000e+000, 2, 3, 4,\n"
"    1.5000000000000000e+000, 3, 2, 1, 5.0000000000000000e-001 ]\n"
);
#else
A
Alexander Alekhin 已提交
1153 1154 1155 1156 1157 1158
    EXPECT_STREQ(fs_result.c_str(),
"%YAML:1.0\n"
"---\n"
"dv: [ 1, 2, 3, -1.5000000000000000e+00, 2, 3, 4, 1.5000000000000000e+00,\n"
"    3, 2, 1, 5.0000000000000000e-01 ]\n"
);
T
Tomoaki Teshima 已提交
1159
#endif
A
Alexander Alekhin 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

    cv::FileStorage fs_read(fs_result, cv::FileStorage::READ | cv::FileStorage::MEMORY);

    std::vector<cv::DMatch> dv_read;
    ASSERT_NO_THROW(fs_read["dv"] >> dv_read);

    ASSERT_EQ(dv.size(), dv_read.size());
    for (size_t i = 0; i < dv.size(); i++)
    {
        EXPECT_EQ(dv[i].queryIdx, dv_read[i].queryIdx);
        EXPECT_EQ(dv[i].trainIdx, dv_read[i].trainIdx);
        EXPECT_EQ(dv[i].imgIdx, dv_read[i].imgIdx);
        EXPECT_EQ(dv[i].distance, dv_read[i].distance);
    }
}

TEST(Core_InputOutput, FileStorage_DMatch_vector_vector)
{
    cv::FileStorage fs("dmatch.yml", cv::FileStorage::WRITE | cv::FileStorage::MEMORY);

    cv::DMatch d1(1, 2, 3, -1.5f);
    cv::DMatch d2(2, 3, 4, 1.5f);
    cv::DMatch d3(3, 2, 1, 0.5f);
    std::vector<cv::DMatch> dv1;
    dv1.push_back(d1);
    dv1.push_back(d2);
    dv1.push_back(d3);

    std::vector<cv::DMatch> dv2;
    dv2.push_back(d3);
    dv2.push_back(d1);

    std::vector< std::vector<cv::DMatch> > dvv;
    dvv.push_back(dv1);
    dvv.push_back(dv2);

    EXPECT_NO_THROW(fs << "dvv" << dvv);
    cv::String fs_result = fs.releaseAndGetString();
T
Tomoaki Teshima 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
#if defined _MSC_VER && _MSC_VER <= 1700 /* MSVC 2012 and older */
    EXPECT_STREQ(fs_result.c_str(),
"%YAML:1.0\n"
"---\n"
"dvv:\n"
"   - [ 1, 2, 3, -1.5000000000000000e+000, 2, 3, 4,\n"
"       1.5000000000000000e+000, 3, 2, 1, 5.0000000000000000e-001 ]\n"
"   - [ 3, 2, 1, 5.0000000000000000e-001, 1, 2, 3,\n"
"       -1.5000000000000000e+000 ]\n"
);
#else
A
Alexander Alekhin 已提交
1209 1210 1211 1212 1213 1214 1215 1216
    EXPECT_STREQ(fs_result.c_str(),
"%YAML:1.0\n"
"---\n"
"dvv:\n"
"   - [ 1, 2, 3, -1.5000000000000000e+00, 2, 3, 4, 1.5000000000000000e+00,\n"
"       3, 2, 1, 5.0000000000000000e-01 ]\n"
"   - [ 3, 2, 1, 5.0000000000000000e-01, 1, 2, 3, -1.5000000000000000e+00 ]\n"
);
T
Tomoaki Teshima 已提交
1217
#endif
A
Alexander Alekhin 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

    cv::FileStorage fs_read(fs_result, cv::FileStorage::READ | cv::FileStorage::MEMORY);

    std::vector< std::vector<cv::DMatch> > dvv_read;
    ASSERT_NO_THROW(fs_read["dvv"] >> dvv_read);

    ASSERT_EQ(dvv.size(), dvv_read.size());
    for (size_t j = 0; j < dvv.size(); j++)
    {
        const std::vector<cv::DMatch>& dv = dvv[j];
        const std::vector<cv::DMatch>& dv_read = dvv_read[j];
        ASSERT_EQ(dvv.size(), dvv_read.size());
        for (size_t i = 0; i < dv.size(); i++)
        {
            EXPECT_EQ(dv[i].queryIdx, dv_read[i].queryIdx);
            EXPECT_EQ(dv[i].trainIdx, dv_read[i].trainIdx);
            EXPECT_EQ(dv[i].imgIdx, dv_read[i].imgIdx);
            EXPECT_EQ(dv[i].distance, dv_read[i].distance);
        }
    }
}
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

TEST(Core_InputOutput, FileStorage_format_xml)
{
    FileStorage fs;
    fs.open("opencv_storage.xml", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_XML, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_xml_gz)
{
    FileStorage fs;
    fs.open("opencv_storage.xml.gz", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_XML, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_json)
{
    FileStorage fs;
    fs.open("opencv_storage.json", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_JSON, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_json_gz)
{
    FileStorage fs;
    fs.open("opencv_storage.json.gz", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_JSON, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_yaml)
{
    FileStorage fs;
    fs.open("opencv_storage.yaml", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_YAML, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_yaml_gz)
{
    FileStorage fs;
    fs.open("opencv_storage.yaml.gz", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_YAML, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_yml)
{
    FileStorage fs;
    fs.open("opencv_storage.yml", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_YAML, fs.getFormat());
}

TEST(Core_InputOutput, FileStorage_format_yml_gz)
{
    FileStorage fs;
    fs.open("opencv_storage.yml.gz", FileStorage::WRITE | FileStorage::MEMORY);
    EXPECT_EQ(FileStorage::FORMAT_YAML, fs.getFormat());
}
D
dkurt 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

TEST(Core_InputOutput, FileStorage_json_named_nodes)
{
    std::string test =
        "{ "
            "\"int_value\": -324,"
            "\"map_value\": {"
                "\"str_value\": \"mystring\""
            "},"
            "\"array\": [0.2, 0.1]"
        "}";
    FileStorage fs(test, FileStorage::READ | FileStorage::MEMORY);

    ASSERT_TRUE(fs["int_value"].isNamed());
    ASSERT_TRUE(fs["map_value"].isNamed());
    ASSERT_TRUE(fs["map_value"]["str_value"].isNamed());
    ASSERT_TRUE(fs["array"].isNamed());
    ASSERT_FALSE(fs["array"][0].isNamed());
    ASSERT_FALSE(fs["array"][1].isNamed());

    ASSERT_EQ(fs["int_value"].name(), "int_value");
    ASSERT_EQ(fs["map_value"].name(), "map_value");
    ASSERT_EQ(fs["map_value"]["str_value"].name(), "str_value");
    ASSERT_EQ(fs["array"].name(), "array");
    fs.release();
}
D
dkurt 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

TEST(Core_InputOutput, FileStorage_json_bool)
{
    std::string test =
        "{ "
            "\"str_true\": \"true\","
            "\"map_value\": {"
                "\"int_value\": -33333,\n"
                "\"bool_true\": true,"
                "\"str_false\": \"false\","
            "},"
            "\"bool_false\": false, \n"
            "\"array\": [0.1, 0.2]"
        "}";
    FileStorage fs(test, FileStorage::READ | FileStorage::MEMORY);

    ASSERT_TRUE(fs["str_true"].isString());
    ASSERT_TRUE(fs["map_value"]["bool_true"].isInt());
    ASSERT_TRUE(fs["map_value"]["str_false"].isString());
    ASSERT_TRUE(fs["bool_false"].isInt());

    ASSERT_EQ((std::string)fs["str_true"], "true");
    ASSERT_EQ((int)fs["map_value"]["bool_true"], 1);
    ASSERT_EQ((std::string)fs["map_value"]["str_false"], "false");
    ASSERT_EQ((int)fs["bool_false"], 0);
    fs.release();
}
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368

TEST(Core_InputOutput, FileStorage_free_file_after_exception)
{
    const std::string fileName = "test.yml";
    const std::string content = "%YAML:1.0\n cameraMatrix;:: !<tag:yaml.org,2002:opencv-matrix>\n";

    fstream testFile;
    testFile.open(fileName, std::fstream::out);
    if(!testFile.is_open()) FAIL();
    testFile << content;
    testFile.close();

    try
    {
        FileStorage fs(fileName, FileStorage::READ + FileStorage::FORMAT_YAML);
    }
    catch (const std::exception&)
    {
        ASSERT_EQ(std::remove(fileName.c_str()), 0);
    }
}