From 1c347f4801c77c3f811068404f0d7328b510c551 Mon Sep 17 00:00:00 2001 From: Vadim Pisarevsky Date: Fri, 15 Apr 2011 11:13:04 +0000 Subject: [PATCH] removed obsolete tests --- tests/cv/CMakeLists.txt | 62 - tests/cv/src/aaccum.cpp | 307 -- tests/cv/src/aadaptthresh.cpp | 211 -- tests/cv/src/aapproxpoly.cpp | 358 --- tests/cv/src/abundleadjustment.cpp | 1535 ---------- tests/cv/src/acameracalibration.cpp | 1726 ----------- tests/cv/src/acameracalibration_artificial.cpp | 428 --- tests/cv/src/acamshift.cpp | 533 ---- tests/cv/src/acanny.cpp | 322 -- tests/cv/src/acascadeandhog.cpp | 469 --- tests/cv/src/achesscorners.cpp | 455 --- tests/cv/src/acolor.cpp | 1803 ------------ tests/cv/src/acomposeRT.cpp | 220 -- tests/cv/src/acondens.cpp | 147 - tests/cv/src/acontourmoments.cpp | 46 - tests/cv/src/acontours.cpp | 405 --- tests/cv/src/acontoursmatch.cpp | 170 -- tests/cv/src/aconvhull.cpp | 1622 ----------- tests/cv/src/acornerssubpix.cpp | 245 -- tests/cv/src/acreatecontourtree.cpp | 192 -- tests/cv/src/adetectordescriptor_evaluation.cpp | 1186 -------- tests/cv/src/adistancetransform.cpp | 358 --- tests/cv/src/adrawing.cpp | 411 --- tests/cv/src/adrawing_regress.cpp | 375 --- tests/cv/src/aeigenobjects.cpp | 771 ----- tests/cv/src/aeigenobjects.inc | 457 --- tests/cv/src/aemd.cpp | 122 - tests/cv/src/aestimaterigid.cpp | 176 -- tests/cv/src/afeatures2d.cpp | 1014 ------- tests/cv/src/affine3d_estimator.cpp | 196 -- tests/cv/src/afilter.cpp | 2758 ------------------ tests/cv/src/afloodfill.cpp | 596 ---- tests/cv/src/afundam.cpp | 1409 --------- tests/cv/src/ahistograms.cpp | 1883 ------------ tests/cv/src/ahmmobs.cpp | 253 -- tests/cv/src/ahoughtransform.cpp | 128 - tests/cv/src/aimage.cpp | 335 --- tests/cv/src/aimgwarp.cpp | 2052 ------------- tests/cv/src/akalman.cpp | 123 - tests/cv/src/akmeans.cpp | 291 -- tests/cv/src/amatchcontourtrees.cpp | 192 -- tests/cv/src/amoments.cpp | 425 --- tests/cv/src/amotiontemplates.cpp | 642 ---- tests/cv/src/amotseg.cpp | 314 -- tests/cv/src/amser.cpp | 201 -- tests/cv/src/anearestneighbors.cpp | 526 ---- tests/cv/src/aoptflowhs.cpp | 431 --- tests/cv/src/aoptflowlk.cpp | 304 -- tests/cv/src/aoptflowpyrlk.cpp | 217 -- tests/cv/src/aposit.cpp | 221 -- tests/cv/src/apyrsegmentation.cpp | 199 -- tests/cv/src/areprojectImageTo3D.cpp | 178 -- tests/cv/src/asnakes.cpp | 233 -- tests/cv/src/astereocorrespondencegc.cpp | 297 -- tests/cv/src/astereomatching.cpp | 823 ------ tests/cv/src/asubdivisions.cpp | 299 -- tests/cv/src/atemplmatch.cpp | 431 --- tests/cv/src/athresh.cpp | 283 -- tests/cv/src/aundistort.cpp | 907 ------ tests/cv/src/bcameracalibration.cpp | 745 ----- tests/cv/src/bchesscorners.cpp | 149 - tests/cv/src/bundistort.cpp | 522 ---- tests/cv/src/cvchessboardgenerator.cpp | 332 --- tests/cv/src/cvchessboardgenerator.h | 40 - tests/cv/src/cvtest.cpp | 44 - tests/cv/src/cvtest.h | 72 - tests/cv/src/detectors_test.cpp | 318 -- tests/cv/src/fast.cpp | 130 - tests/cv/src/grabcut.cpp | 142 - tests/cv/src/highguitest.cpp | 315 -- tests/cv/src/highguitest_guionly.cpp | 107 - tests/cv/src/inpaint.cpp | 122 - tests/cv/src/latentsvmdetector.cpp | 136 - tests/cv/src/operations.cpp | 829 ------ tests/cv/src/optflow.cpp | 356 --- tests/cv/src/tabruteforcematcher.cpp | 120 - tests/cv/src/tchesscorners.cpp | 191 -- tests/cv/src/tsysa.cpp | 60 - tests/cv/src/watershed.cpp | 134 - tests/cxcore/CMakeLists.txt | 53 - tests/cxcore/src/aarithm.cpp | 3560 ----------------------- tests/cxcore/src/aarray.cpp | 402 --- tests/cxcore/src/adatastruct.cpp | 2342 --------------- tests/cxcore/src/adxt.cpp | 1011 ------- tests/cxcore/src/aio.cpp | 432 --- tests/cxcore/src/amath.cpp | 3352 --------------------- tests/cxcore/src/apca.cpp | 308 -- tests/cxcore/src/arand.cpp | 344 --- tests/cxcore/src/areduce.cpp | 308 -- tests/cxcore/src/asolvepoly.cpp | 168 -- tests/cxcore/src/cxcoretest.h | 68 - tests/cxcore/src/cxcoretest_main.cpp | 61 - tests/cxcore/src/matrix_operations.cpp | 164 -- tests/cxcore/src/precomp.cpp | 42 - tests/cxts/CMakeLists.txt | 69 - tests/cxts/_cxts.h | 60 - tests/cxts/cxts.cpp | 2182 -------------- tests/cxts/cxts.h | 837 ------ tests/cxts/cxts_arrtest.cpp | 691 ----- tests/cxts/cxts_math.cpp | 3429 ---------------------- tests/cxts/precomp.cpp | 44 - tests/ml/CMakeLists.txt | 62 - tests/ml/src/aemknearestkmeans.cpp | 327 --- tests/ml/src/amltests.cpp | 128 - tests/ml/src/gbttest.cpp | 276 -- tests/ml/src/mltest.h | 133 - tests/ml/src/mltest_main.cpp | 57 - tests/ml/src/mltests.cpp | 800 ----- tests/ml/src/precomp.cpp | 43 - tests/ml/src/slmltests.cpp | 135 - tests/octave/frame.jpg | Bin 19985 -> 0 bytes tests/octave/test_adaptors.m | 33 - 112 files changed, 60058 deletions(-) delete mode 100644 tests/cv/CMakeLists.txt delete mode 100644 tests/cv/src/aaccum.cpp delete mode 100644 tests/cv/src/aadaptthresh.cpp delete mode 100644 tests/cv/src/aapproxpoly.cpp delete mode 100755 tests/cv/src/abundleadjustment.cpp delete mode 100644 tests/cv/src/acameracalibration.cpp delete mode 100644 tests/cv/src/acameracalibration_artificial.cpp delete mode 100644 tests/cv/src/acamshift.cpp delete mode 100644 tests/cv/src/acanny.cpp delete mode 100644 tests/cv/src/acascadeandhog.cpp delete mode 100644 tests/cv/src/achesscorners.cpp delete mode 100644 tests/cv/src/acolor.cpp delete mode 100644 tests/cv/src/acomposeRT.cpp delete mode 100644 tests/cv/src/acondens.cpp delete mode 100644 tests/cv/src/acontourmoments.cpp delete mode 100644 tests/cv/src/acontours.cpp delete mode 100644 tests/cv/src/acontoursmatch.cpp delete mode 100644 tests/cv/src/aconvhull.cpp delete mode 100644 tests/cv/src/acornerssubpix.cpp delete mode 100644 tests/cv/src/acreatecontourtree.cpp delete mode 100644 tests/cv/src/adetectordescriptor_evaluation.cpp delete mode 100644 tests/cv/src/adistancetransform.cpp delete mode 100644 tests/cv/src/adrawing.cpp delete mode 100644 tests/cv/src/adrawing_regress.cpp delete mode 100644 tests/cv/src/aeigenobjects.cpp delete mode 100644 tests/cv/src/aeigenobjects.inc delete mode 100644 tests/cv/src/aemd.cpp delete mode 100644 tests/cv/src/aestimaterigid.cpp delete mode 100644 tests/cv/src/afeatures2d.cpp delete mode 100644 tests/cv/src/affine3d_estimator.cpp delete mode 100644 tests/cv/src/afilter.cpp delete mode 100644 tests/cv/src/afloodfill.cpp delete mode 100644 tests/cv/src/afundam.cpp delete mode 100644 tests/cv/src/ahistograms.cpp delete mode 100644 tests/cv/src/ahmmobs.cpp delete mode 100644 tests/cv/src/ahoughtransform.cpp delete mode 100644 tests/cv/src/aimage.cpp delete mode 100644 tests/cv/src/aimgwarp.cpp delete mode 100644 tests/cv/src/akalman.cpp delete mode 100644 tests/cv/src/akmeans.cpp delete mode 100644 tests/cv/src/amatchcontourtrees.cpp delete mode 100644 tests/cv/src/amoments.cpp delete mode 100644 tests/cv/src/amotiontemplates.cpp delete mode 100644 tests/cv/src/amotseg.cpp delete mode 100644 tests/cv/src/amser.cpp delete mode 100644 tests/cv/src/anearestneighbors.cpp delete mode 100644 tests/cv/src/aoptflowhs.cpp delete mode 100644 tests/cv/src/aoptflowlk.cpp delete mode 100644 tests/cv/src/aoptflowpyrlk.cpp delete mode 100644 tests/cv/src/aposit.cpp delete mode 100644 tests/cv/src/apyrsegmentation.cpp delete mode 100644 tests/cv/src/areprojectImageTo3D.cpp delete mode 100644 tests/cv/src/asnakes.cpp delete mode 100644 tests/cv/src/astereocorrespondencegc.cpp delete mode 100755 tests/cv/src/astereomatching.cpp delete mode 100644 tests/cv/src/asubdivisions.cpp delete mode 100644 tests/cv/src/atemplmatch.cpp delete mode 100644 tests/cv/src/athresh.cpp delete mode 100644 tests/cv/src/aundistort.cpp delete mode 100644 tests/cv/src/bcameracalibration.cpp delete mode 100644 tests/cv/src/bchesscorners.cpp delete mode 100644 tests/cv/src/bundistort.cpp delete mode 100644 tests/cv/src/cvchessboardgenerator.cpp delete mode 100644 tests/cv/src/cvchessboardgenerator.h delete mode 100644 tests/cv/src/cvtest.cpp delete mode 100644 tests/cv/src/cvtest.h delete mode 100644 tests/cv/src/detectors_test.cpp delete mode 100644 tests/cv/src/fast.cpp delete mode 100644 tests/cv/src/grabcut.cpp delete mode 100644 tests/cv/src/highguitest.cpp delete mode 100644 tests/cv/src/highguitest_guionly.cpp delete mode 100644 tests/cv/src/inpaint.cpp delete mode 100644 tests/cv/src/latentsvmdetector.cpp delete mode 100644 tests/cv/src/operations.cpp delete mode 100644 tests/cv/src/optflow.cpp delete mode 100644 tests/cv/src/tabruteforcematcher.cpp delete mode 100644 tests/cv/src/tchesscorners.cpp delete mode 100644 tests/cv/src/tsysa.cpp delete mode 100644 tests/cv/src/watershed.cpp delete mode 100644 tests/cxcore/CMakeLists.txt delete mode 100644 tests/cxcore/src/aarithm.cpp delete mode 100644 tests/cxcore/src/aarray.cpp delete mode 100644 tests/cxcore/src/adatastruct.cpp delete mode 100644 tests/cxcore/src/adxt.cpp delete mode 100644 tests/cxcore/src/aio.cpp delete mode 100644 tests/cxcore/src/amath.cpp delete mode 100644 tests/cxcore/src/apca.cpp delete mode 100644 tests/cxcore/src/arand.cpp delete mode 100644 tests/cxcore/src/areduce.cpp delete mode 100644 tests/cxcore/src/asolvepoly.cpp delete mode 100644 tests/cxcore/src/cxcoretest.h delete mode 100644 tests/cxcore/src/cxcoretest_main.cpp delete mode 100644 tests/cxcore/src/matrix_operations.cpp delete mode 100644 tests/cxcore/src/precomp.cpp delete mode 100644 tests/cxts/CMakeLists.txt delete mode 100644 tests/cxts/_cxts.h delete mode 100644 tests/cxts/cxts.cpp delete mode 100644 tests/cxts/cxts.h delete mode 100644 tests/cxts/cxts_arrtest.cpp delete mode 100644 tests/cxts/cxts_math.cpp delete mode 100644 tests/cxts/precomp.cpp delete mode 100644 tests/ml/CMakeLists.txt delete mode 100644 tests/ml/src/aemknearestkmeans.cpp delete mode 100644 tests/ml/src/amltests.cpp delete mode 100644 tests/ml/src/gbttest.cpp delete mode 100644 tests/ml/src/mltest.h delete mode 100644 tests/ml/src/mltest_main.cpp delete mode 100644 tests/ml/src/mltests.cpp delete mode 100644 tests/ml/src/precomp.cpp delete mode 100644 tests/ml/src/slmltests.cpp delete mode 100644 tests/octave/frame.jpg delete mode 100755 tests/octave/test_adaptors.m diff --git a/tests/cv/CMakeLists.txt b/tests/cv/CMakeLists.txt deleted file mode 100644 index 01aa794..0000000 --- a/tests/cv/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -# ---------------------------------------------------------------------------- -# CMake file for cvtest. See root CMakeLists.txt -# -# ---------------------------------------------------------------------------- -project(opencv_test) - -file(GLOB test_srcs "src/*.cpp") -source_group("Src" FILES ${test_srcs}) -file(GLOB test_hdrs "src/*.h*") -source_group("Include" FILES ${test_hdrs}) - -include_directories("${CMAKE_SOURCE_DIR}/include/opencv" - "${CMAKE_SOURCE_DIR}/modules/core/include" - "${CMAKE_SOURCE_DIR}/modules/imgproc/include" - "${CMAKE_SOURCE_DIR}/modules/features2d/include" - "${CMAKE_SOURCE_DIR}/modules/flann/include" - "${CMAKE_SOURCE_DIR}/modules/calib3d/include" - "${CMAKE_SOURCE_DIR}/modules/highgui/include" - "${CMAKE_SOURCE_DIR}/modules/objdetect/include" - "${CMAKE_SOURCE_DIR}/modules/video/include" - "${CMAKE_SOURCE_DIR}/modules/legacy/include" - "${CMAKE_SOURCE_DIR}/modules/contrib/include" - "${CMAKE_CURRENT_SOURCE_DIR}/src" - "${CMAKE_CURRENT_BINARY_DIR}") - -include_directories(../cxts) - -set(the_target "opencv_test") - -add_executable(${the_target} ${test_srcs} ${test_hdrs}) - -if(PCHSupport_FOUND) - set(pch_header ${CMAKE_SOURCE_DIR}/tests/cv/src/cvtest.h) - if(${CMAKE_GENERATOR} MATCHES "Visual*" OR ${CMAKE_GENERATOR} MATCHES "Xcode*") - if(${CMAKE_GENERATOR} MATCHES "Visual*") - set(${the_target}_pch "src/cvtest.cpp") - endif() - add_native_precompiled_header(${the_target} ${pch_header}) - elseif(CMAKE_COMPILER_IS_GNUCXX AND ${CMAKE_GENERATOR} MATCHES ".*Makefiles") - add_precompiled_header(${the_target} ${pch_header}) - endif() -endif() - -# Additional target properties -set_target_properties(${the_target} PROPERTIES - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/" - ) - - -add_dependencies(${the_target} opencv_ts opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_objdetect opencv_video opencv_highgui opencv_legacy opencv_contrib) - -# Add the required libraries for linking: -target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} opencv_ts opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_objdetect opencv_video opencv_highgui opencv_legacy opencv_contrib) - -enable_testing() -get_target_property(LOC ${the_target} LOCATION) -add_test(cvtest "${LOC}") - -if(WIN32) -install(TARGETS ${the_target} RUNTIME DESTINATION bin COMPONENT main) -endif() diff --git a/tests/cv/src/aaccum.cpp b/tests/cv/src/aaccum.cpp deleted file mode 100644 index 49faa14..0000000 --- a/tests/cv/src/aaccum.cpp +++ /dev/null @@ -1,307 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const char* accum_param_names[] = { "size", "channels", "depth", "use_mask", 0 }; -static const CvSize accum_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize accum_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; -static const int accum_depths[] = { CV_8U, CV_32F, CV_64F, -1 }; -static const int accum_channels[] = { 1, 3, -1 }; - -class CV_AccumBaseTestImpl : public CvArrTest -{ -public: - CV_AccumBaseTestImpl( const char* test_name, const char* test_funcs ); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - double alpha; -}; - - -CV_AccumBaseTestImpl::CV_AccumBaseTestImpl( const char* test_name, const char* test_funcs ) - : CvArrTest( test_name, test_funcs, "" ) -{ - test_array[INPUT].push(NULL); - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[MASK].push(NULL); - optional_mask = true; - element_wise_relative_error = false; - - default_timing_param_names = 0; - depth_list = accum_depths; - size_list = accum_sizes; - whole_size_list = accum_whole_sizes; - cn_list = accum_channels; - - return; -} // ctor - - -void CV_AccumBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 3, cn = cvTsRandInt(rng) & 1 ? 3 : 1; - int accdepth = std::max((int)(cvTsRandInt(rng) % 2 + 1), depth); - int i, input_count = test_array[INPUT].size(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_32F : CV_64F; - accdepth = accdepth == 1 ? CV_32F : CV_64F; - accdepth = MAX(accdepth, depth); - - for( i = 0; i < input_count; i++ ) - types[INPUT][i] = CV_MAKETYPE(depth,cn); - - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = types[TEMP][0] = CV_MAKETYPE(accdepth,cn); - - alpha = cvTsRandReal(rng); - - return; -} - - -double CV_AccumBaseTestImpl::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type) < CV_64F || - CV_MAT_DEPTH(test_mat[INPUT][0].type) == CV_32F ? FLT_EPSILON*100 : DBL_EPSILON*1000; -} - - -void CV_AccumBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT_OUTPUT][0] = CV_MAKETYPE(MAX(CV_32F, CV_MAT_DEPTH(types[INPUT][0])), - CV_MAT_CN(types[INPUT][0])); - - alpha = 0.333333333333333; -} - - -CV_AccumBaseTestImpl accum_base( "accum", "" ); - - -class CV_AccumBaseTest : public CV_AccumBaseTestImpl -{ -public: - CV_AccumBaseTest( const char* test_name, const char* test_funcs ); -}; - - -CV_AccumBaseTest::CV_AccumBaseTest( const char* test_name, const char* test_funcs ) - : CV_AccumBaseTestImpl( test_name, test_funcs ) -{ - depth_list = 0; - size_list = 0; - whole_size_list = 0; - cn_list = 0; - - default_timing_param_names = accum_param_names; -} - - -/// acc -class CV_AccTest : public CV_AccumBaseTest -{ -public: - CV_AccTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_AccTest::CV_AccTest(void) - : CV_AccumBaseTest( "accum-acc", "cvAcc" ) -{ -} - - -void CV_AccTest::run_func(void) -{ - cvAcc( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_AccTest::prepare_to_validation( int ) -{ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* temp = &test_mat[TEMP][0]; - const CvMat* mask = test_array[MASK][0] ? &test_mat[MASK][0] : 0; - - cvTsAdd( src, cvScalarAll(1.), dst, cvScalarAll(1.), cvScalarAll(0.), temp, 0 ); - cvTsCopy( temp, dst, mask ); - return; -} - -CV_AccTest acc_test; - - -/// square acc -class CV_SquareAccTest : public CV_AccumBaseTest -{ -public: - CV_SquareAccTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_SquareAccTest::CV_SquareAccTest() - : CV_AccumBaseTest( "accum-squareacc", "cvSquareAcc" ) -{ -} - - -void CV_SquareAccTest::run_func() -{ - cvSquareAcc( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_SquareAccTest::prepare_to_validation( int ) -{ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* temp = &test_mat[TEMP][0]; - const CvMat* mask = test_array[MASK][0] ? &test_mat[MASK][0] : 0; - - cvTsMul( src, src, cvScalarAll(1.), temp ); - cvTsAdd( temp, cvScalarAll(1.), dst, cvScalarAll(1.), cvScalarAll(0.), temp, 0 ); - cvTsCopy( temp, dst, mask ); -} - -CV_SquareAccTest squareacc_test; - - -/// multiply acc -class CV_MultiplyAccTest : public CV_AccumBaseTest -{ -public: - CV_MultiplyAccTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_MultiplyAccTest::CV_MultiplyAccTest() - : CV_AccumBaseTest( "accum-mulacc", "cvMultiplyAcc" ) -{ - test_array[INPUT].push(NULL); -} - - -void CV_MultiplyAccTest::run_func() -{ - cvMultiplyAcc( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_MultiplyAccTest::prepare_to_validation( int ) -{ - const CvMat* src1 = &test_mat[INPUT][0]; - const CvMat* src2 = &test_mat[INPUT][1]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* temp = &test_mat[TEMP][0]; - const CvMat* mask = test_array[MASK][0] ? &test_mat[MASK][0] : 0; - - cvTsMul( src1, src2, cvScalarAll(1.), temp ); - cvTsAdd( temp, cvScalarAll(1.), dst, cvScalarAll(1.), cvScalarAll(0.), temp, 0 ); - cvTsCopy( temp, dst, mask ); -} - -CV_MultiplyAccTest mulacc_test; - - -/// running average -class CV_RunningAvgTest : public CV_AccumBaseTest -{ -public: - CV_RunningAvgTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_RunningAvgTest::CV_RunningAvgTest() - : CV_AccumBaseTest( "accum-runavg", "cvRunningAvg" ) -{ -} - - -void CV_RunningAvgTest::run_func() -{ - cvRunningAvg( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - alpha, test_array[MASK][0] ); -} - - -void CV_RunningAvgTest::prepare_to_validation( int ) -{ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* temp = &test_mat[TEMP][0]; - const CvMat* mask = test_array[MASK][0] ? &test_mat[MASK][0] : 0; - double a[1], b[1]; - int accdepth = CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type); - CvMat A = cvMat(1,1,accdepth,a), B = cvMat(1,1,accdepth,b); - cvSetReal1D( &A, 0, alpha); - cvSetReal1D( &B, 0, 1 - cvGetReal1D(&A, 0)); - - cvTsAdd( src, cvScalarAll(cvGetReal1D(&A, 0)), dst, cvScalarAll(cvGetReal1D(&B, 0)), cvScalarAll(0.), temp, 0 ); - cvTsCopy( temp, dst, mask ); -} - -CV_RunningAvgTest runavg_test; - diff --git a/tests/cv/src/aadaptthresh.cpp b/tests/cv/src/aadaptthresh.cpp deleted file mode 100644 index 5904af9..0000000 --- a/tests/cv/src/aadaptthresh.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -//extern "C"{ -// #include "HighGUI.h" -//} - - -static char cTestName[] = "Image Adaptive Thresholding"; -static char cTestClass[] = "Algorithm"; -static char cFuncName[] = "cvAdaptThreshold"; -static int aAdaptThreshold() -{ - - CvPoint *cp; - int parameter1 = 3; - double parameter2 = 10; - int width = 128; - int height = 128; - int kp = 5; - int nPoints2 = 20; - - int fi = 0; - int a2 = 20; - int b2 = 25,xc,yc; - - double pi = 3.1415926; - - double lower, upper; - unsigned seed; - char rand; - AtsRandState state; - - long diff_binary, diff_binary_inv; - - int l,i,j; - - IplImage *imBinary, *imBinary_inv, *imTo_zero, *imTo_zero_inv, *imInput, *imOutput; - CvSize size; - - int code = TRS_OK; - -// read tests params - if(!trsiRead( &width, "128", "image width" )) - return TRS_UNDEF; - if(!trsiRead( &height, "128", "image height" )) - return TRS_UNDEF; - -// initialized image - l = width*height*sizeof(uchar); - - cp = (CvPoint*) trsmAlloc(nPoints2*sizeof(CvPoint)); - - xc = (int)( width/2.); - yc = (int)( height/2.); - - kp = nPoints2; - - size.width = width; - size.height = height; - - int xmin = width; - int ymin = height; - int xmax = 0; - int ymax = 0; - - - for(i=0;i cp[i].x) xmin = cp[i].x; - if(xmax< cp[i].x) xmax = cp[i].x; - cp[i].y = (int)(a2*cos(2*pi*i/nPoints2)*sin(2*pi*fi/360.))+ - (int)(b2*sin(2*pi*i/nPoints2)*cos(2*pi*fi/360.))+yc; - if(ymin> cp[i].y) ymin = cp[i].y; - if(ymax< cp[i].y) ymax = cp[i].y; - } - - if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; - -// IPL image moment calculation -// create image - imBinary = cvCreateImage( size, 8, 1 ); - imBinary_inv = cvCreateImage( size, 8, 1 ); - imTo_zero = cvCreateImage( size, 8, 1 ); - imTo_zero_inv = cvCreateImage( size, 8, 1 ); - imOutput = cvCreateImage( size, 8, 1 ); - imInput = cvCreateImage( size, 8, 1 ); - - int bgrn = 50; - int signal = 150; - - memset(imInput->imageData,bgrn,l); - - cvFillPoly(imInput, &cp, &kp, 1, cvScalarAll(signal)); - -// do noise - upper = 22; - lower = -upper; - seed = 345753; - atsRandInit( &state, lower, upper, seed ); - - uchar *input = (uchar*)imInput->imageData; - uchar *binary = (uchar*)imBinary->imageData; - uchar *binary_inv = (uchar*)imBinary_inv->imageData; - uchar *to_zero = (uchar*)imTo_zero->imageData; - uchar *to_zero_inv = (uchar*)imTo_zero_inv->imageData; - double *parameter = (double*)trsmAlloc(2*sizeof(double)); - - int step = imInput->widthStep; - - for(i = 0; iimageData, (uchar*)imBinary->imageData, l, 5); - - cvAdaptiveThreshold( imInput, imOutput, (double)255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY_INV, parameter1, parameter2 ); - diff_binary_inv = atsCompare1Db( (uchar*)imOutput->imageData, (uchar*)imBinary_inv->imageData, l, 5); - - if( diff_binary > 5 || diff_binary_inv > 5 ) - code = TRS_FAIL; - - cvReleaseImage(&imInput); - cvReleaseImage(&imOutput); - cvReleaseImage(&imBinary); - cvReleaseImage(&imBinary_inv); - cvReleaseImage(&imTo_zero); - cvReleaseImage(&imTo_zero_inv); - - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "diff_binary =%ld \n", diff_binary); - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "diff_binary_inv =%ld \n", diff_binary_inv); - - trsFree(parameter); - trsFree(cp); - return code; -} - - -void InitAAdaptThreshold( void ) -{ -/* Test Registartion */ - trsReg(cFuncName,cTestName,cTestClass,aAdaptThreshold); -} /* InitAAdaptThreshold */ - -#endif - -/* End of file. */ diff --git a/tests/cv/src/aapproxpoly.cpp b/tests/cv/src/aapproxpoly.cpp deleted file mode 100644 index 09c849e..0000000 --- a/tests/cv/src/aapproxpoly.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include - -// -// TODO!!!: -// check_slice (and/or check) seem(s) to be broken, or this is a bug in function -// (or its inability to handle possible self-intersections in the generated contours). -// -// At least, if // return TotalErrors; -// is uncommented in check_slice, the test fails easily. -// So, now (and it looks like since 0.9.6) -// we only check that the set of vertices of the approximated polygon is -// a subset of vertices of the original contour. -// - -class CV_ApproxPolyTest : public CvTest -{ -public: - CV_ApproxPolyTest(); - ~CV_ApproxPolyTest(); - void clear(); - //int write_default_params(CvFileStorage* fs); - -protected: - //int read_params( CvFileStorage* fs ); - - int check_slice( CvPoint StartPt, CvPoint EndPt, - CvSeqReader* SrcReader, float Eps, - int* j, int Count ); - int check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps ); - - bool get_contour( int /*type*/, CvSeq** Seq, int* d, - CvMemStorage* storage ); - - void run(int); -}; - - -CV_ApproxPolyTest::CV_ApproxPolyTest(): - CvTest( "contour-approx", "cvApproxPoly" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -CV_ApproxPolyTest::~CV_ApproxPolyTest() -{ - clear(); -} - - -void CV_ApproxPolyTest::clear() -{ - CvTest::clear(); -} - - -/*int CV_ApproxPolyTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - } - return 0; -} - - -int CV_ApproxPolyTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count ); - min_log_size = cvTsClipInt( min_log_size, 1, 10 ); - return 0; -}*/ - - -bool CV_ApproxPolyTest::get_contour( int /*type*/, CvSeq** Seq, int* d, - CvMemStorage* storage ) -{ - CvRNG* rng = ts->get_rng(); - int max_x = INT_MIN, max_y = INT_MIN, min_x = INT_MAX, min_y = INT_MAX; - int i; - CvSeq* seq; - int total = cvTsRandInt(rng) % 1000 + 1; - CvPoint center; - int radius, angle; - double deg_to_rad = CV_PI/180.; - CvPoint pt; - - center.x = cvTsRandInt( rng ) % 1000; - center.y = cvTsRandInt( rng ) % 1000; - radius = cvTsRandInt( rng ) % 1000; - angle = cvTsRandInt( rng ) % 360; - - seq = cvCreateSeq( CV_SEQ_POLYGON, sizeof(CvContour), sizeof(CvPoint), storage ); - - for( i = 0; i < total; i++ ) - { - int d_radius = cvTsRandInt( rng ) % 10 - 5; - int d_angle = 360/total;//cvTsRandInt( rng ) % 10 - 5; - pt.x = cvRound( center.x + radius*cos(angle*deg_to_rad)); - pt.y = cvRound( center.x - radius*sin(angle*deg_to_rad)); - radius += d_radius; - angle += d_angle; - cvSeqPush( seq, &pt ); - - max_x = MAX( max_x, pt.x ); - max_y = MAX( max_y, pt.y ); - - min_x = MIN( min_x, pt.x ); - min_y = MIN( min_y, pt.y ); - } - - *d = (max_x - min_x)*(max_x - min_x) + (max_y - min_y)*(max_y - min_y); - *Seq = seq; - return true; -} - - -int CV_ApproxPolyTest::check_slice( CvPoint StartPt, CvPoint EndPt, - CvSeqReader* SrcReader, float Eps, - int* _j, int Count ) -{ - /////////// - CvPoint Pt; - /////////// - bool flag; - double dy,dx; - double A,B,C; - double Sq; - double sin_a = 0; - double cos_a = 0; - double d = 0; - double dist; - /////////// - int j, TotalErrors = 0; - - //////////////////////////////// - if( SrcReader == NULL ) - { - assert( false ); - return 0; - } - - ///////// init line //////////// - flag = true; - - dx = (double)StartPt.x - (double)EndPt.x; - dy = (double)StartPt.y - (double)EndPt.y; - - if( ( dx == 0 ) && ( dy == 0 ) ) flag = false; - else - { - A = -dy; - B = dx; - C = dy * (double)StartPt.x - dx * (double)StartPt.y; - Sq = sqrt( A*A + B*B ); - - sin_a = B/Sq; - cos_a = A/Sq; - d = C/Sq; - } - - /////// find start point and check distance //////// - for( j = *_j; j < Count; j++ ) - { - CV_READ_SEQ_ELEM( Pt, *SrcReader ); - if( StartPt.x == Pt.x && StartPt.y == Pt.y ) break; - else - { - if( flag ) dist = sin_a * Pt.y + cos_a * Pt.x - d; - else dist = sqrt( (double)(EndPt.y - Pt.y)*(EndPt.y - Pt.y) + (EndPt.x - Pt.x)*(EndPt.x - Pt.x) ); - if( dist > Eps ) TotalErrors++; - } - } - - *_j = j; - - //return TotalErrors; - return 0; -} - - -int CV_ApproxPolyTest::check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps ) -{ - ////////// - CvSeqReader DstReader; - CvSeqReader SrcReader; - CvPoint StartPt, EndPt; - /////////// - int TotalErrors = 0; - /////////// - int Count; - int i,j; - - assert( SrcSeq && DstSeq ); - - ////////// init //////////////////// - Count = SrcSeq->total; - - cvStartReadSeq( DstSeq, &DstReader, 0 ); - cvStartReadSeq( SrcSeq, &SrcReader, 0 ); - - CV_READ_SEQ_ELEM( StartPt, DstReader ); - for( i = 0 ; i < Count ; ) - { - CV_READ_SEQ_ELEM( EndPt, SrcReader ); - i++; - if( StartPt.x == EndPt.x && StartPt.y == EndPt.y ) break; - } - - ///////// start //////////////// - for( i = 1, j = 0 ; i <= DstSeq->total ; ) - { - ///////// read slice //////////// - EndPt.x = StartPt.x; - EndPt.y = StartPt.y; - CV_READ_SEQ_ELEM( StartPt, DstReader ); - i++; - - TotalErrors += check_slice( StartPt, EndPt, &SrcReader, Eps, &j, Count ); - - if( j > Count ) - { - TotalErrors++; - return TotalErrors; - } //if( !flag ) - - } // for( int i = 0 ; i < DstSeq->total ; i++ ) - - return TotalErrors; -} - - -//extern CvTestContourGenerator cvTsTestContours[]; - -void CV_ApproxPolyTest::run( int /*start_from*/ ) -{ - int code = CvTS::OK; - CvMemStorage* storage = 0; - ////////////// Variables //////////////// - int IntervalsCount = 10; - /////////// - //CvTestContourGenerator Cont; - CvSeq* SrcSeq = NULL; - CvSeq* DstSeq; - int iDiam; - float dDiam, Eps, EpsStep; - - for( int i = 0; i < 30; i++ ) - { - CvMemStoragePos pos; - - ts->update_context( this, i, false ); - - ///////////////////// init contour ///////// - dDiam = 0; - while( sqrt(dDiam) / IntervalsCount == 0 ) - { - if( storage != 0 ) - cvReleaseMemStorage(&storage); - - storage = cvCreateMemStorage( 0 ); - if( get_contour( 0, &SrcSeq, &iDiam, storage ) ) - dDiam = (float)iDiam; - } - dDiam = (float)sqrt( dDiam ); - - storage = SrcSeq->storage; - - ////////////////// test ///////////// - EpsStep = dDiam / IntervalsCount ; - for( Eps = EpsStep ; Eps < dDiam ; Eps += EpsStep ) - { - cvSaveMemStoragePos( storage, &pos ); - - ////////// call function //////////// - DstSeq = cvApproxPoly( SrcSeq, SrcSeq->header_size, storage, - CV_POLY_APPROX_DP, Eps ); - - if( DstSeq == NULL ) - { - ts->printf( CvTS::LOG, - "cvApproxPoly returned NULL for contour #%d, espilon = %g\n", i, Eps ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } // if( DstSeq == NULL ) - - code = check( SrcSeq, DstSeq, Eps ); - if( code != 0 ) - { - ts->printf( CvTS::LOG, - "Incorrect result for the contour #%d approximated with epsilon=%g\n", i, Eps ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - cvRestoreMemStoragePos( storage, &pos ); - } // for( Eps = EpsStep ; Eps <= Diam ; Eps += EpsStep ) - - ///////////// free memory /////////////////// - cvReleaseMemStorage(&storage); - } // for( int i = 0; NULL != ( Cont = Contours[i] ) ; i++ ) - -_exit_: - cvReleaseMemStorage(&storage); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - - -CV_ApproxPolyTest contour_approx; diff --git a/tests/cv/src/abundleadjustment.cpp b/tests/cv/src/abundleadjustment.cpp deleted file mode 100755 index 85e2edb..0000000 --- a/tests/cv/src/abundleadjustment.cpp +++ /dev/null @@ -1,1535 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2009, PhaseSpace Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The names of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#if defined WIN32 || defined _WIN32 -#include "direct.h" -#else -#include -#endif - -using namespace cv; - -//global variable -#ifndef MAX_PATH -#define MAX_PATH 1024 -#endif - -char g_filepath[MAX_PATH]; - -//objects for virtual environmnt - -/*****************************Camera class ************************************************/ -class Camera -{ -public: - Camera(void); - virtual ~Camera(void); - - inline void SetPosition(double x, double y, double z) - { - position[0] = x; - position[1] = y; - position[2] = z; - } - - inline double* GetPosition() { return position; } - - inline void SetDistortion(double r1, double r2, double t1, double t2) - { - distortion[0] = r1; - distortion[1] = r2; - distortion[2] = t1; - distortion[3] = t2; - } - inline void SetIntrinsics( double fx, double fy, double cx, double cy ) //fx,fy,cx,cy - { - intrinsic[0] = fx; - intrinsic[1] = 0; - intrinsic[2] = cx; - intrinsic[3] = 0; - intrinsic[4] = fy; - intrinsic[5] = cy; - intrinsic[6] = 0; - intrinsic[7] = 0; - intrinsic[8] = 1.0; - } - - CvPoint3D64f ConvertPoint2WCS( CvPoint3D64f pt ) - { - double tmp[3]; - CvMat tmp_point = cvMat( 3, 1, CV_64FC1, tmp ); - - CvMat rot = cvMat( 3, 3, CV_64FC1, rotation ); - CvMat trans = cvMat( 3, 1, CV_64FC1, translation ); - CvMat in_point = cvMat( 3, 1, CV_64FC1, &pt ); - - // out = inv(R) * (in - t) - - cvSub(&in_point, &trans, &tmp_point); - cvGEMM( &rot, &tmp_point, 1, NULL, 0, &tmp_point, CV_GEMM_A_T /* use transposed rotmat*/ ); - - CvPoint3D64f out; - out.x = tmp[0]; - out.y = tmp[1]; - out.z = tmp[2]; - - return out; - } - - inline void SetRotation( double* rotmat ) //fx,fy,cx,cy - { - memcpy( rotation, rotmat, 9 * sizeof(double) ); - } - - double* GetRotation() - { - return rotation; - } - - void ComputeTranslation() - { - //convert camera position in WCS into translation vector of the camera - //t = -R*pos - translation[0] = -(rotation[0]*position[0]+rotation[1]*position[1]+rotation[2]*position[2]); - translation[1] = -(rotation[3]*position[0]+rotation[4]*position[1]+rotation[5]*position[2]); - translation[2] = -(rotation[6]*position[0]+rotation[7]*position[1]+rotation[8]*position[2]); - } - - double* GetTranslation() - { - return translation; - } - double* GetIntrinsics() - { - return intrinsic; - } - - double* GetDistortion() - { - return distortion; - } - - void SetResolution(CvSize res) - { - resolution = res; - } - CvSize GetResolution() - { - return resolution; - } - void saveCamParams(FILE* stream); - void readCamParams(FILE* stream); - - -protected: - double distortion[4]; //distortion coeffs according to OpenCV (2 radial and 2 tangential) - double intrinsic[9]; //matrix of intrinsic parameters - double translation[3]; //camera's translation vector - double rotation[9]; //camera rotation matrix (probably need to convert to camera axis vector - double position[3]; //camera's position in WCS - - CvSize resolution; -}; - -Camera::Camera(void) -{ - //default parameters - translation[0] = translation[1] = translation[2] = 0.0; - rotation[0] = rotation[1] = rotation[2] = - rotation[3] = rotation[4] = rotation[5] = - rotation[6] = rotation[7] = rotation[8] = 0.0; - rotation[0] = rotation[4] = rotation[8] = 1.0; - - distortion[0] = distortion[1] = distortion[2] = distortion[3] = 0.0; -} - -Camera::~Camera(void) -{ -} - -void Camera::saveCamParams(FILE * stream) -{ - float tmp0 = 0.0f, tmp1 = 1.0f; - - // printing camera distortion. 4 parameters - fprintf(stream, "%.12f %.12f %.12f %.12f\n", distortion[0], distortion[1], - distortion[2], distortion[3]); - - //printing camera intrinsics matrix - fprintf(stream, "%.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f\n", - intrinsic[0], intrinsic[1], intrinsic[2], - intrinsic[3], intrinsic[4], intrinsic[5], - intrinsic[6], intrinsic[7], intrinsic[8]); - - //printing camera extrinsic transform - fprintf(stream, "%.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f %.12f\n", - rotation[0], rotation[1], rotation[2], translation[0], - rotation[3], rotation[4], rotation[5], translation[1], - rotation[6], rotation[7], rotation[8], translation[2], - tmp0, tmp0, tmp0, tmp1); -} - -void Camera::readCamParams(FILE* stream) -{ - double dummy; - - // read camera distortion. 4 parameters - fscanf(stream, "%lf %lf %lf %lf\n", &(distortion[0]), &(distortion[1]), &(distortion[2]), &(distortion[3]) ); - - //read camera intrinsics matrix - fscanf(stream, "%lf %lf %lf %lf %lf %lf %lf %lf %lf\n", - &(intrinsic[0]), &(intrinsic[1]), &(intrinsic[2]), - &(intrinsic[3]), &(intrinsic[4]), &(intrinsic[5]), - &(intrinsic[6]), &(intrinsic[7]), &(intrinsic[8])); - - //read camera extrinsic transform - fscanf(stream, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n", - &(rotation[0]), &(rotation[1]), &(rotation[2]), &(translation[0]), - &(rotation[3]), &(rotation[4]), &(rotation[5]), &(translation[1]), - &(rotation[6]), &(rotation[7]), &(rotation[8]), &(translation[2]), - &dummy, &dummy, &dummy, &dummy); -} - -/******************************** body**************************************************/ - -class RigidBody -{ - //global position of body's center - double pos[3]; - double rotation[9]; //body's rotation matrix - - int* m_ids; //points ids, these are integer numbers not necessarily zero-based indices - CvPoint3D64f* m_points3D; //these are points in object coordinate system - CvPoint3D64f* m_points3D_WCS; //these are points in WCS - int m_numPoints; - -public: - - RigidBody() - { - m_ids = 0; - m_points3D = 0; - m_points3D_WCS = 0; - m_numPoints = 0; - - SetPosition(0,0,0); - double t[9] = {1,0,0,0,1,0,0,0,1}; - SetRotation( t ); - } - virtual ~RigidBody() {} - - virtual void SetPosition(double x, double y, double z ) - { - pos[0] = x; - pos[1] = y; - pos[2] = z; - } - - virtual void SetRotation( double* rotmat ) - { - memcpy( rotation, rotmat, 9 * sizeof(double) ); - } - - void Save(char* fname, bool wcs /* 1 - save coordinates in wcs, 0 - save coordinates in object coordinate system*/ ) - { - FILE* fp = fopen(fname, "w"); - fprintf(fp, "%d\n", m_numPoints ); - if( wcs ) - { - for( int i = 0; i < m_numPoints; i++ ) - { - fprintf(fp, "%d %.12f %.12f %.12f\n", m_ids[i], m_points3D_WCS[i].x, m_points3D_WCS[i].y, m_points3D_WCS[i].z ); - } - } - else - { - for( int i = 0; i < m_numPoints; i++ ) - { - fprintf(fp, "%d, %.12f, %.12f, %.12f\n", m_ids[i], m_points3D[i].x, m_points3D[i].y, m_points3D[i].z ); - } - } - fclose(fp); - } - - void Load(char* fname) - { - clear_points(); - FILE* fp = fopen(fname, "r"); - fscanf(fp, "%d\n", &m_numPoints ); - //allocate arrays - m_points3D = new CvPoint3D64f[m_numPoints]; - m_points3D_WCS = new CvPoint3D64f[m_numPoints]; - m_ids = new int[m_numPoints]; - - for(int i = 0; i < m_numPoints; i++ ) - { - fscanf(fp, "%d %lf %lf %lf\n", &(m_ids[i]), &(m_points3D[i].x), &(m_points3D[i].y), &(m_points3D[i].z)); - } - } - - void clear_points() - { - if(m_points3D) - delete m_points3D; - m_points3D = NULL; - if(m_points3D_WCS) - delete m_points3D_WCS; - m_points3D_WCS = NULL; - if( m_ids ) - delete m_ids; - m_ids = NULL; - m_numPoints = 0; - } - - void generate_random( int n, double x_min, double x_max, - double y_min, double y_max, - double z_min, double z_max ) - { - clear_points(); - m_numPoints = n; - m_points3D = new CvPoint3D64f[m_numPoints]; - m_points3D_WCS = new CvPoint3D64f[m_numPoints]; - m_ids = new int[m_numPoints]; - - //fill ids - for( int i = 0 ; i < n; i++ ) - { - m_ids[i] = i; - } - - CvRNG rng; - - CvMat values = cvMat( m_numPoints, 1, CV_64FC3, m_points3D ); - - cvRandArr( &rng, &values, CV_RAND_UNI, - cvScalar(x_min, y_min, z_min), // min - cvScalar(x_max, y_max, z_max) // deviation - ); - } - CvPoint3D64f* GetPoints3D(bool wcs) - { - if( wcs ) - { - //fill points in WCS accordingly to rotation matrix and board position - for(int i = 0; i < NumPoints(); i++ ) - { - m_points3D_WCS[i].x = rotation[0]*m_points3D[i].x + - rotation[1]*m_points3D[i].y + - rotation[2]*m_points3D[i].z + pos[0]; - - m_points3D_WCS[i].y = rotation[3]*m_points3D[i].x + - rotation[4]*m_points3D[i].y + - rotation[5]*m_points3D[i].z + pos[1]; - - m_points3D_WCS[i].z = rotation[6]*m_points3D[i].x + - rotation[7]*m_points3D[i].y + - rotation[8]*m_points3D[i].z + pos[2]; - } - //return points in global cooordinates - return m_points3D_WCS; - - } - else - return m_points3D; - } - - double* GetRotation() { return rotation; } - - int NumPoints() - { - return m_numPoints; - } - - int* GetPointsIds() - { - return this->m_ids; - } - -}; - - -/********************************* environment *****************************************/ -#define PT_INVISIBLE 0 -#define PT_VISIBLE 1 -#define PT_OUTBORDER 2 - -class Environment -{ -public: - Environment(void); - virtual ~Environment(void); - - inline int NumCameras() - { - return (int)m_cameras.size(); - } - - inline int AddCamera(Camera* cam) - { - m_cameras.push_back(cam); - return (int)m_cameras.size(); - } - - RigidBody* GetBody() - { - return m_body; - } - - void SetNoise(float n) - { - noise = n; - } - - int Capture(); - int Save(char* filename); - -protected: - - std::vector m_cameras; - RigidBody* m_body; - std::vector m_image_points; - std::vector m_point_visibility; - float noise; - -}; - -Environment::Environment(void) -{ - m_body = new RigidBody(); -} - -Environment::~Environment(void) -{ - delete m_body; -} - -int Environment::Capture() -{ - //clear points - for( size_t i = 0; i < m_image_points.size(); i++ ) - { - if( m_image_points[i] ) - delete m_image_points[i]; - } - m_image_points.clear(); - - for( size_t i = 0; i < m_point_visibility.size(); i++ ) - { - if( m_point_visibility[i] ) - delete m_point_visibility[i]; - } - m_point_visibility.clear(); - - CvPoint3D64f* board_pts = m_body->GetPoints3D(true); - int num_points = m_body->NumPoints(); - - //loop over cameras - for( size_t i = 0; i < m_cameras.size(); i++ ) - { - //get camera parameters - //project points onto camera image - - double* rot = m_cameras[i]->GetRotation(); - double* trans = m_cameras[i]->GetTranslation(); - double* intr = m_cameras[i]->GetIntrinsics(); - double* dist = m_cameras[i]->GetDistortion(); - - CvPoint2D64f* image_points = new CvPoint2D64f[num_points]; - m_image_points.push_back(image_points); - - int* points_visibility = new int[num_points]; - m_point_visibility.push_back(points_visibility); - - cvProjectPointsSimple(num_points, board_pts, rot, trans, intr, dist, image_points); - - CvRNG rng; - - if( noise > 0) - { - CvMat* values = cvCreateMat( num_points, 1, CV_32FC2 ); - - float stdev = noise; - - cvRandArr( &rng, values, CV_RAND_NORMAL, - cvScalar(0.0, 0.0), // mean - cvScalar(stdev, stdev) // deviation - ); - - //add gaussian noise to image points - - for( int j = 0; j < num_points; j++ ) - { - CvPoint2D32f pt = *(CvPoint2D32f*)cvPtr1D( values, j, 0 ); - - pt.x = min( pt.x, stdev); - pt.x = max( pt.x, -stdev); - - pt.y = min( pt.y, stdev); - pt.y = max( pt.y, -stdev); - - image_points[j].x += pt.x; - image_points[j].y += pt.y; - } - cvReleaseMat( &values ); - } - - //decide if point visible to camera - //loop over points and assign visibility flag to them - for( int j = 0; j < num_points; j++ ) - { - //generate random visibility of the point - int visible = cvRandInt(&rng) % 2; //visibility 50% - - //check the point is in camera FOV (1-pixel border assumed invisible) - if( image_points[j].x > 0 && image_points[j].x < m_cameras[i]->GetResolution().width-1 - && image_points[j].y > 0 && image_points[j].y < m_cameras[i]->GetResolution().height-1 ) - { - if(!visible) - points_visibility[j] = PT_INVISIBLE; - else - points_visibility[j] = PT_VISIBLE; - } - else - points_visibility[j] = PT_OUTBORDER; - } - } - - //some points may become completely invisible for all cameras or visible only at one camera - //we will forcely make them visible for at least 2 cameras - for( int i = 0 ; i < num_points; i++ ) - { - int numvis = 0; - for( size_t j = 0; j < m_cameras.size(); j++ ) - { - if( m_point_visibility[j][i] == PT_VISIBLE ) - numvis++; - } - - if(numvis < 2) - { - for( size_t j = 0; j < m_cameras.size(); j++ ) - { - if( m_point_visibility[j][i] == PT_INVISIBLE ) - { - m_point_visibility[j][i] = PT_VISIBLE; - numvis++; - } - if(numvis > 1) - break; - } - assert(numvis > 1 ); - } - } - - return 0; -} - -/*void Environment::TestCamera(int camind) -{ - CvPoint3D64f* board_pts = m_body->GetPoints3D(false); - - int count = 0; - for( int j = 0; j < m_body->NumPoints(); j++ ) - { - if( m_point_visibility[camind][j] == PT_VISIBLE ) - count++; - } - - CvMat* object_points = cvCreateMat( 1, count, CV_64FC3 ); - CvMat* image_points = cvCreateMat( 1, count, CV_64FC2 ); - CvMat* intrinsic_matrix = cvCreateMatHeader( 3, 3, CV_64FC1 ); - cvSetData(intrinsic_matrix, m_cameras[camind]->GetIntrinsics(), 3*sizeof(double) ); - - CvMat* distortion_coeffs = cvCreateMat( 4, 1, CV_64FC1 ); cvSetZero(distortion_coeffs); - CvMat* rotation_vector = cvCreateMat( 3, 1, CV_64FC1 ); - CvMat* translation_vector = cvCreateMat( 3, 1, CV_64FC1 ); - - CvMat* rotation_matrix = cvCreateMat( 3, 3, CV_64FC1 ); - - //loop over points and assign visibility flag to them - int ind = 0; - for( int j = 0; j < m_body->NumPoints(); j++ ) - { - if( m_point_visibility[camind][j] == PT_VISIBLE) - { - //add to matrix - *((CvPoint3D64f*)(object_points->data.db + ind*3)) = board_pts[j]; - *((CvPoint2D64f*)(image_points->data.db + ind*2)) = m_image_points[camind][j]; - ind++; - } - } - - - //find extrinsic parameters of the board - cvFindExtrinsicCameraParams2( object_points, - image_points, - intrinsic_matrix, - distortion_coeffs, - rotation_vector, - translation_vector ); - - //cvRodrigues2( rotation_vector, rotation_matrix ); - - - //reproject points and see error of reprojection - - CvMat* image_points_repro = cvCloneMat( image_points ); - - cvProjectPoints2( object_points, rotation_vector, translation_vector, intrinsic_matrix, distortion_coeffs, - image_points_repro ); - - for( int j = 0; j < image_points_repro->cols; j++ ) - { - CvPoint2D64f pt_orig = *((CvPoint2D64f*)(image_points->data.db + j*2)); - CvPoint2D64f pt_repro = *((CvPoint2D64f*)(image_points_repro->data.db + j*2)); - - CvPoint2D64f diff; - diff.x = pt_repro.x - pt_orig.x; - diff.y = pt_repro.y - pt_orig.y; - - } -} */ - -int Environment::Save(char* filename) -{ - int* ind = m_body->GetPointsIds(); - FILE* saveFile = fopen( filename, "w" ); - if(saveFile) - { - for( size_t cam_index = 0; cam_index < m_cameras.size(); cam_index++ ) - { - CvPoint2D64f* image_points = m_image_points[cam_index]; - - int numPnt = 0; //no visible points by default - - //check points visibility - //camera is visible, check individual points - for(int i = 0; i < m_body->NumPoints(); i++ ) - { - if( m_point_visibility[cam_index][i] == PT_VISIBLE) - { - //point is visible - numPnt++; - } - } - - if(numPnt) //some points are visible - { - for( int i = 0; i < m_body->NumPoints(); i++) - { - if( m_point_visibility[cam_index][i] == PT_VISIBLE ) - { - //point is visible - fprintf(saveFile, "%d %d %d %.12f %.12f\n", 0 /*snapshot_id*/, (int)cam_index, ind[i], image_points[i].x, image_points[i].y ); - } - } - } - - } - } - - //close file - fclose(saveFile); - return 0; -} - - - - -//input parameters for envirinment generation -struct Params -{ - int width; //width of images - int height; //height of images - float FOVx; //camera field of view in horizontal direction. vertical FOV is detected from aspect ratio - float noise; //corners projection noise - float k1, k2, k3; //radial distortion coeffs - float p1,p2; //tangential distortion coeffs -}; - -int GenerateTestData2(Params& params) -{ - //create environment - Environment* env = new Environment(); - env->SetNoise(params.noise); - - CvSize im_res = cvSize(params.width,params.height); - - double FOVx = params.FOVx; // field of view relatively to width (in degrees) - double fov_rad = FOVx * CV_PI / 180; - double fx = im_res.width/2.0 / tan( fov_rad/2); - double fy = fx; - double cx = im_res.width/2.0-0.5; - double cy = im_res.height/2.0-0.5; - - //model cube room of size 2x2x2 meters - //8 cameras on the perimeter at the height 1 meter in corners and in the middle of walls - // all they look to the center of the room - //coordinate center in the center of the cube - //Z coordinate is oriented up - - Camera* cam[8]; - for( int i = 0; i < 8; i++ ) - { - cam[i] = new Camera(); - cam[i]->SetDistortion(params.k1, params.k2,0,0); //only radial distortion - cam[i]->SetIntrinsics(fx,fy, cx, cy ); //fx,fy,cx,cy - cam[i]->SetResolution(im_res); - env->AddCamera(cam[i]); - } - - //set positions - cam[0]->SetPosition( 1.,1.,0); - cam[1]->SetPosition( 0.,1.,0); - cam[2]->SetPosition( -1.,1.,0); - cam[3]->SetPosition( -1.,0.,0); - cam[4]->SetPosition( -1.,-1.,0); - cam[5]->SetPosition( 0.,-1.,0); - cam[6]->SetPosition( 1.,-1.,0); - cam[7]->SetPosition( 1.,0.,0); - - //set rotation matrices - //they will be oriented strongly vertically and rotated only around vertical axis (Z coorinate in WCS) - - CvMat* camrot = cvCreateMat( 3, 3, CV_64FC1); - - for( int i = 0; i < 8; i++ ) - { - //y of the camera is oriented along negative Z of WCS - double yDirCamera[3] = {0,0,-1}; - double zDirCamera[3]; //oriented from camera center to WCS center - double* pos = cam[i]->GetPosition(); - zDirCamera[0] = -pos[0]; - zDirCamera[1] = -pos[1]; - zDirCamera[2] = -pos[2]; - - double xDirCamera[3]; //cross product Y*Z - xDirCamera[0] = yDirCamera[1]*zDirCamera[2] - yDirCamera[2]*zDirCamera[1]; - xDirCamera[1] = yDirCamera[2]*zDirCamera[0] - yDirCamera[0]*zDirCamera[2]; - xDirCamera[2] = yDirCamera[0]*zDirCamera[1] - yDirCamera[1]*zDirCamera[0]; - - //normalize z and x - double inv_norm = 1.0/sqrt(xDirCamera[0]*xDirCamera[0] + xDirCamera[1]*xDirCamera[1] + xDirCamera[2]*xDirCamera[2]); - xDirCamera[0]*=inv_norm; - xDirCamera[1]*=inv_norm; - xDirCamera[2]*=inv_norm; - - inv_norm = 1.0 / sqrt(zDirCamera[0]*zDirCamera[0] + zDirCamera[1]*zDirCamera[1] + zDirCamera[2]*zDirCamera[2]); - zDirCamera[0] *= inv_norm; - zDirCamera[1] *= inv_norm; - zDirCamera[2] *= inv_norm; - - camrot->data.db[0] = xDirCamera[0]; - camrot->data.db[3] = xDirCamera[1]; - camrot->data.db[6] = xDirCamera[2]; - - camrot->data.db[1] = yDirCamera[0]; - camrot->data.db[4] = yDirCamera[1]; - camrot->data.db[7] = yDirCamera[2]; - - camrot->data.db[2] = zDirCamera[0]; - camrot->data.db[5] = zDirCamera[1]; - camrot->data.db[8] = zDirCamera[2]; - - //get inverse matrix (equal to transposed) - cvTranspose(camrot, camrot); - - cam[i]->SetRotation(camrot->data.db); - cam[i]->ComputeTranslation();// compute translation after we set position and rotation matrix - } - -#if defined WIN32 || defined _WIN32 - _mkdir(g_filepath); -#else - mkdir(g_filepath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); -#endif - char fname[2048]; - sprintf(fname, "%scameras.txt", g_filepath ); - FILE* clist = fopen(fname, "w"); - for(unsigned int i = 0; i < 8; i++) - { - sprintf(fname, "%scamera%d.calib", g_filepath, i ); - FILE *calibFile = fopen(fname,"w"); - cam[i]->saveCamParams(calibFile); - fclose( calibFile ); - fprintf(clist, "%s\n", fname); - } - fclose(clist); - - std::vector board_pos; - board_pos.clear(); - - //generate body position, set zero for now - CvPoint3D64f pos; - pos.x = 0; pos.y = 0; pos.z = 0; - board_pos.push_back(pos); - - RigidBody* body = env->GetBody(); - body->generate_random(50, -0.25, 0.25, -0.25, 0.25, -0.25, 0.25 ); - - CvRNG rng = cvRNG(); - int index = 0; //index of board's position to save, is used to enumerate snapshots - - for(size_t i = 0; i < board_pos.size(); i++ ) - { - CvPoint3D64f point = board_pos[i]; - body->SetPosition(point.x,point.y,point.z); - - //generate random orientation of the board - unsigned int rn = cvRandInt(&rng); - //scale to 90 degrees - rn = rn%90; - double slant = (double)rn-45-90; //angle of slant of the bord relatively to its horizontal direction - - rn = cvRandInt(&rng); - //scale to 360 degrees - rn = rn%360; - double azimuth = rn; //azimuth - - - //set slant and azimuth to 0 - slant = azimuth = 0; - - double sn = sin(azimuth*CV_PI/180); - double cs = cos(azimuth*CV_PI/180); - - //generate rotation matrix - CvMat* mat_azimuth = cvCreateMat( 3, 3, CV_64FC1); - mat_azimuth->data.db[0] = cs; - mat_azimuth->data.db[1] = -sn; - mat_azimuth->data.db[2] = 0; - - mat_azimuth->data.db[3] = sn; - mat_azimuth->data.db[4] = cs; - mat_azimuth->data.db[5] = 0; - - mat_azimuth->data.db[6] = 0; - mat_azimuth->data.db[7] = 0; - mat_azimuth->data.db[8] = 1; - - sn = sin(slant*CV_PI/180); - cs = cos(slant*CV_PI/180); - CvMat* mat_slant = cvCreateMat( 3, 3, CV_64FC1); //rotation around X axis - mat_slant->data.db[0] = 1; - mat_slant->data.db[1] = 0; - mat_slant->data.db[2] = 0; - - mat_slant->data.db[3] = 0; - mat_slant->data.db[4] = cs; - mat_slant->data.db[5] = -sn; - - mat_slant->data.db[6] = 0; - mat_slant->data.db[7] = sn; - mat_slant->data.db[8] = cs; - - CvMat* rot = cvCreateMat( 3, 3, CV_64FC1); //rotation around X axis - //create complete rotation matrix - cvMatMul(mat_azimuth, mat_slant, rot); - - //these are coordinates of board's axis in WCS - body->SetRotation(rot->data.db); - - //project images onto all cameras - env->Capture(); - - //save 3d points of corners into the file - char fname[2048]; - sprintf(fname, "%sPoints%d.3d", g_filepath, index ); - body->Save(fname, true); - //save shots from camera - - sprintf(fname, "%salldata.txt", g_filepath ); - env->Save(fname); - } - //destroy everything - delete env; - return 0; -} - -int TestLevmar2() -{ - //load data from file - - // 1. load ground truth 3D points - RigidBody body; - - char fname[2048]; - sprintf(fname, "%sPoints0.3d", g_filepath ); - body.Load(fname); - int num_points = body.NumPoints(); - - // 2. load cameras - int num_cams = 0; - //int num_cam_param = 10; - std::vector cams; - - sprintf(fname, "%scameras.txt", g_filepath ); - FILE* fp = fopen(fname, "r" ); - while( !feof(fp) ) - { - char fname[MAX_PATH]; - fscanf(fp, "%s\n", fname ); - Camera* newcam = new Camera(); - FILE* fp2 = fopen( fname, "r" ); - newcam->readCamParams(fp2); - cams.push_back(newcam); - fclose(fp2); - num_cams++; - } - fclose(fp); - - // 2. Load projection data - CvMat* m = cvCreateMat( body.NumPoints(), num_cams, CV_64FC2 ); - //all invisible point will have (-1,-1) projection - cvSet( m, cvScalar(-1,-1) ); - - sprintf(fname, "%salldata.txt", g_filepath ); - fp = fopen( fname, "r"); - - int counter = 0; - while( !feof(fp) ) - { - //read line - int snapid, cameraid, pointid; - double x,y; - fscanf(fp, "%d %d %d %lf %lf\n", &snapid, &cameraid, &pointid, &x, &y); - cvSet2D(m, pointid, cameraid, cvScalar(x,y) ); - counter++; - } - - vector > visibility; - - //transform this matrix to measurement vector - vector > imagePoints; - - for(int j = 0; j < num_cams; j++ ) - { - vector vec; - vector visvec; - for(int i = 0; i < num_points; i++ ) - { - CvScalar s = cvGet2D( m, i, j ); - if( s.val[0] != -1 ) //point is visible - { - vec.push_back(Point2d(s.val[0],s.val[1])); - visvec.push_back(1); - } - else - { - vec.push_back(Point2d(DBL_MAX,DBL_MAX)); - visvec.push_back(0); - } - } - imagePoints.push_back(vec); - visibility.push_back(visvec); - } - - //form initial params - vector cameraMatrix; //intrinsic matrices of all cameras (input and output) - vector R; //rotation matrices of all cameras (input and output) - vector T; //translation vector of all cameras (input and output) - vector distCoeffs; //distortion coefficients of all cameras (input and output) - - //store original camera positions - vector T_backup; - //store original camera rotations - vector R_backup; - //store original intrinsic matrix - vector cameraMatrix_backup; - //store original distortion - vector distCoeffs_backup; - - for( int i = 0; i < (int)cams.size(); i++ ) - { - //fill params - Camera* c = cams[i]; - //rotation - double* rotmat = c->GetRotation(); - Mat rm(3,3,CV_64F,rotmat); - R_backup.push_back(rm); - //generate small random rotation - Mat rodr; Rodrigues(rm, rodr); - double n = norm(rodr); - //add small angle - //add about 5 degrees to rotation - rodr *= ((n+0.1)/n); - Rodrigues(rodr, rm); - R.push_back(rm); - - //translation - double* tr = c->GetTranslation(); - Mat tv(Size(1,3), CV_64F, tr); - T_backup.push_back(tv); - //add random translation within 1 cm - Mat t_(3,1,CV_64F); - randu(t_, -0.01, 0.01); - tv+=t_; - - T.push_back(tv); - //intrinsic matrix - double* intr = c->GetIntrinsics(); - cameraMatrix_backup.push_back(Mat(Size(3,3), CV_64F, intr)); - cameraMatrix.push_back(Mat(Size(3,3), CV_64F, intr)); - - //distortion - Mat d(4, 1, CV_64F, c->GetDistortion() ); - distCoeffs_backup.push_back(d); - - //variate distortion by 5% - d*=1.05; - distCoeffs.push_back(d); - - } - - //form input points - const Point3d* ptptr = (const Point3d*)body.GetPoints3D(true); - vector points(ptptr, ptptr + num_points); - //store points - vector points_backup(num_points); - std::copy(points.begin(), points.end(), points_backup.begin()); - - //variate initial points - CvRNG rng; - CvMat* values = cvCreateMat( num_points*3, 1, CV_64F ); - cvRandArr( &rng, values, CV_RAND_NORMAL, - cvScalar(0.0), // mean - cvScalar(0.02) // deviation (in meters) - ); - CvMat tmp = cvMat(values->rows, values->cols, values->type, &points[0] ); - cvAdd( &tmp, values, &tmp ); - cvReleaseMat( &values ); - - LevMarqSparse::bundleAdjust( points, //positions of points in global coordinate system (input and output) - imagePoints, //projections of 3d points for every camera - visibility, //visibility of 3d points for every camera - cameraMatrix, //intrinsic matrices of all cameras (input and output) - R, //rotation matrices of all cameras (input and output) - T, //translation vector of all cameras (input and output) - distCoeffs, //distortion coefficients of all cameras (input and output) - TermCriteria(TermCriteria::COUNT|TermCriteria::EPS, 3000, DBL_EPSILON )); - //,enum{MOTION_AND_STRUCTURE,MOTION,STRUCTURE}) - - //compare input points and found points - double maxdist = 0; - for( size_t i = 0; i < points.size(); i++ ) - { - Point3d in = points_backup[i]; - Point3d out = points[i]; - double dist = sqrt(in.dot(out)); - if(dist > maxdist) - maxdist = dist; - } - printf("Maximal distance between points: %.12lf\n", maxdist ); - - //compare camera positions - maxdist = 0; - for( size_t i = 0; i < T.size(); i++ ) - { - double dist = norm(T[i], T_backup[i]); - - if(dist > maxdist) - maxdist = dist; - } - printf("Maximal distance between cameras centers: %.12lf\n", maxdist ); - - //compare rotation matrices - maxdist = 0; - for( size_t i = 0; i < R.size(); i++ ) - { - double dist = norm(R[i], R_backup[i], NORM_INF); - - if(dist > maxdist) - maxdist = dist; - } - printf("Maximal difference in rotation matrices elements: %.12lf\n", maxdist ); - - //compare intrinsic matrices - maxdist = 0; - double total_diff = 0; - for( size_t i = 0; i < cameraMatrix.size(); i++ ) - { - double fx_ratio = cameraMatrix[i].at(0,0)/ - cameraMatrix_backup[i].at(0,0); - double fy_ratio = cameraMatrix[i].at(1,1)/ - cameraMatrix_backup[i].at(1,1); - double cx_diff = cameraMatrix[i].at(0,2) - - cameraMatrix_backup[i].at(0,2); - double cy_diff = cameraMatrix[i].at(1,2) - - cameraMatrix_backup[i].at(1,2); - total_diff += fabs(fx_ratio - 1) + fabs(fy_ratio - 1) + fabs(cx_diff) + fabs(cy_diff); - } - //ts->printf(CvTS::LOG, "total diff = %g\n", total_diff); - - return 1; -} - - -class CV_BundleAdjustmentTest : public CvTest -{ - -public: - CV_BundleAdjustmentTest(); - ~CV_BundleAdjustmentTest(); - void clear(); - //int write_default_params(CvFileStorage* fs); - -protected: - //int read_params( CvFileStorage* fs ); - int compare(double* val, double* ref_val, int len, - double eps, const char* param_name); - - void run(int); -}; - - -CV_BundleAdjustmentTest::CV_BundleAdjustmentTest(): - CvTest( "bundleadjust", "bundleAdjust" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -CV_BundleAdjustmentTest::~CV_BundleAdjustmentTest() -{ - clear(); -} - - -void CV_BundleAdjustmentTest::clear() -{ - CvTest::clear(); -} - - -int CV_BundleAdjustmentTest::compare(double* val, double* ref_val, int len, - double eps, const char* param_name ) -{ - return cvTsCmpEps2_64f( ts, val, ref_val, len, eps, param_name ); -} - -void CV_BundleAdjustmentTest::run( int start_from ) -{ - int code = CvTS::OK; - char filepath[100]; - char filename[100]; - - CvSize imageSize; - int numImages; - CvSize etalonSize; - - CvPoint2D64f* imagePoints; - CvPoint3D64f* objectPoints; - CvPoint2D64f* reprojectPoints; - - double* transVects; - double* rotMatrs; - - double* goodTransVects; - double* goodRotMatrs; - - double cameraMatrix[3*3]; - double distortion[4]; - - double goodDistortion[4]; - - int* numbers; - FILE* file = 0; - FILE* datafile = 0; - int i,j; - int currImage; - int currPoint; - - int calibFlags; - char i_dat_file[100]; - int numPoints; - int numTests; - int currTest; - - imagePoints = 0; - objectPoints = 0; - reprojectPoints = 0; - numbers = 0; - - transVects = 0; - rotMatrs = 0; - goodTransVects = 0; - goodRotMatrs = 0; - int progress = 0; - - //generate test data - Params params; - //set default params - - params.FOVx = 30; - params.height = 480; - params.width = 640; - //params.noise = 0.25f; - params.k1 = -0.5f; - params.k2 = -0.5f; - params.k3 = 0.0f; - params.noise = 0.0f; - params.p1 = 0; - params.p2 = 0; - - sprintf( g_filepath, "%sSBA/", ts->get_data_path() ); - - GenerateTestData2(params); - TestLevmar2(); - - sprintf( filepath, "%scameracalibration/", ts->get_data_path() ); - sprintf( filename, "%sdatafiles.txt", filepath ); - datafile = fopen( filename, "r" ); - if( datafile == 0 ) - { - ts->printf( CvTS::LOG, "Could not open file with list of test files: %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - fscanf(datafile,"%d",&numTests); - - for( currTest = start_from; currTest < numTests; currTest++ ) - { - progress = update_progress( progress, currTest, numTests, 0 ); - fscanf(datafile,"%s",i_dat_file); - sprintf(filename, "%s%s", filepath, i_dat_file); - file = fopen(filename,"r"); - - ts->update_context( this, currTest, true ); - - if( file == 0 ) - { - ts->printf( CvTS::LOG, - "Can't open current test file: %s\n",filename); - if( numTests == 1 ) - { - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - continue; // if there is more than one test, just skip the test - } - - fscanf(file,"%d %d\n",&(imageSize.width),&(imageSize.height)); - if( imageSize.width <= 0 || imageSize.height <= 0 ) - { - ts->printf( CvTS::LOG, "Image size in test file is incorrect\n" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - /* Read etalon size */ - fscanf(file,"%d %d\n",&(etalonSize.width),&(etalonSize.height)); - if( etalonSize.width <= 0 || etalonSize.height <= 0 ) - { - ts->printf( CvTS::LOG, "Pattern size in test file is incorrect\n" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - numPoints = etalonSize.width * etalonSize.height; - - /* Read number of images */ - fscanf(file,"%d\n",&numImages); - if( numImages <=0 ) - { - ts->printf( CvTS::LOG, "Number of images in test file is incorrect\n"); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - /* Need to allocate memory */ - imagePoints = (CvPoint2D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint2D64f)); - - objectPoints = (CvPoint3D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint3D64f)); - - reprojectPoints = (CvPoint2D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint2D64f)); - - /* Alloc memory for numbers */ - numbers = (int*)cvAlloc( numImages * sizeof(int)); - - /* Fill it by numbers of points of each image*/ - for( currImage = 0; currImage < numImages; currImage++ ) - { - numbers[currImage] = etalonSize.width * etalonSize.height; - } - - /* Allocate memory for translate vectors and rotmatrixs*/ - transVects = (double*)cvAlloc(3 * 1 * numImages * sizeof(double)); - rotMatrs = (double*)cvAlloc(3 * 3 * numImages * sizeof(double)); - - goodTransVects = (double*)cvAlloc(3 * 1 * numImages * sizeof(double)); - goodRotMatrs = (double*)cvAlloc(3 * 3 * numImages * sizeof(double)); - - /* Read object points */ - i = 0;/* shift for current point */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < numPoints; currPoint++ ) - { - double x,y,z; - fscanf(file,"%lf %lf %lf\n",&x,&y,&z); - - (objectPoints+i)->x = x; - (objectPoints+i)->y = y; - (objectPoints+i)->z = z; - i++; - } - } - - /* Read image points */ - i = 0;/* shift for current point */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < numPoints; currPoint++ ) - { - double x,y; - fscanf(file,"%lf %lf\n",&x,&y); - - (imagePoints+i)->x = x; - (imagePoints+i)->y = y; - i++; - } - } - - /* Read good data computed before */ - - /* Focal lengths */ - double goodFcx,goodFcy; - fscanf(file,"%lf %lf",&goodFcx,&goodFcy); - - /* Principal points */ - double goodCx,goodCy; - fscanf(file,"%lf %lf",&goodCx,&goodCy); - - /* Read distortion */ - - fscanf(file,"%lf",goodDistortion+0); - fscanf(file,"%lf",goodDistortion+1); - fscanf(file,"%lf",goodDistortion+2); - fscanf(file,"%lf",goodDistortion+3); - - /* Read good Rot matrixes */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( i = 0; i < 3; i++ ) - for( j = 0; j < 3; j++ ) - fscanf(file, "%lf", goodRotMatrs + currImage * 9 + j * 3 + i); - } - - /* Read good Trans vectors */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( i = 0; i < 3; i++ ) - fscanf(file, "%lf", goodTransVects + currImage * 3 + i); - } - - calibFlags = - //CV_CALIB_FIX_PRINCIPAL_POINT + - //CV_CALIB_ZERO_TANGENT_DIST + - //CV_CALIB_FIX_ASPECT_RATIO + - //CV_CALIB_USE_INTRINSIC_GUESS + - 0; - memset( cameraMatrix, 0, 9*sizeof(cameraMatrix[0]) ); - cameraMatrix[0] = cameraMatrix[4] = 807.; - cameraMatrix[2] = (imageSize.width - 1)*0.5; - cameraMatrix[5] = (imageSize.height - 1)*0.5; - cameraMatrix[8] = 1.; - - /* Now we can calibrate camera */ - cvCalibrateCamera_64f( numImages, - numbers, - imageSize, - imagePoints, - objectPoints, - distortion, - cameraMatrix, - transVects, - rotMatrs, - calibFlags ); - - /* ---- Reproject points to the image ---- */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - int numPoints = etalonSize.width * etalonSize.height; - cvProjectPointsSimple( numPoints, - objectPoints + currImage * numPoints, - rotMatrs + currImage * 9, - transVects + currImage * 3, - cameraMatrix, - distortion, - reprojectPoints + currImage * numPoints); - } - - - /* ----- Compute reprojection error ----- */ - i = 0; - double dx,dy; - double rx,ry; - double meanDx,meanDy; - double maxDx = 0.0; - double maxDy = 0.0; - - meanDx = 0; - meanDy = 0; - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < etalonSize.width * etalonSize.height; currPoint++ ) - { - rx = reprojectPoints[i].x; - ry = reprojectPoints[i].y; - dx = rx - imagePoints[i].x; - dy = ry - imagePoints[i].y; - - meanDx += dx; - meanDy += dy; - - dx = fabs(dx); - dy = fabs(dy); - - if( dx > maxDx ) - maxDx = dx; - - if( dy > maxDy ) - maxDy = dy; - i++; - } - } - - meanDx /= numImages * etalonSize.width * etalonSize.height; - meanDy /= numImages * etalonSize.width * etalonSize.height; - - /* ========= Compare parameters ========= */ - - /* ----- Compare focal lengths ----- */ - code = compare(cameraMatrix+0,&goodFcx,1,0.01,"fx"); - if( code < 0 ) - goto _exit_; - - code = compare(cameraMatrix+4,&goodFcy,1,0.01,"fy"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare principal points ----- */ - code = compare(cameraMatrix+2,&goodCx,1,0.01,"cx"); - if( code < 0 ) - goto _exit_; - - code = compare(cameraMatrix+5,&goodCy,1,0.01,"cy"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare distortion ----- */ - code = compare(distortion,goodDistortion,4,0.01,"[k1,k2,p1,p2]"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare rot matrixs ----- */ - code = compare(rotMatrs,goodRotMatrs, 9*numImages,0.05,"rotation matrices"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare rot matrixs ----- */ - code = compare(transVects,goodTransVects, 3*numImages,0.05,"translation vectors"); - if( code < 0 ) - goto _exit_; - - if( maxDx > 1.0 ) - { - ts->printf( CvTS::LOG, - "Error in reprojection maxDx=%f > 1.0\n",maxDx); - code = CvTS::FAIL_BAD_ACCURACY; goto _exit_; - } - - if( maxDy > 1.0 ) - { - ts->printf( CvTS::LOG, - "Error in reprojection maxDy=%f > 1.0\n",maxDy); - code = CvTS::FAIL_BAD_ACCURACY; goto _exit_; - } - - cvFree(&imagePoints); - cvFree(&objectPoints); - cvFree(&reprojectPoints); - cvFree(&numbers); - - cvFree(&transVects); - cvFree(&rotMatrs); - cvFree(&goodTransVects); - cvFree(&goodRotMatrs); - - fclose(file); - file = 0; - } - -_exit_: - - if( file ) - fclose(file); - - if( datafile ) - fclose(datafile); - - /* Free all allocated memory */ - cvFree(&imagePoints); - cvFree(&objectPoints); - cvFree(&reprojectPoints); - cvFree(&numbers); - - cvFree(&transVects); - cvFree(&rotMatrs); - cvFree(&goodTransVects); - cvFree(&goodRotMatrs); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -//CV_BundleAdjustmentTest bundleadjustment_test; - -#endif - diff --git a/tests/cv/src/acameracalibration.cpp b/tests/cv/src/acameracalibration.cpp deleted file mode 100644 index b0eb160..0000000 --- a/tests/cv/src/acameracalibration.cpp +++ /dev/null @@ -1,1726 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include - -#if 0 -class CV_ProjectPointsTest : public CvArrTest -{ -public: - CV_ProjectPointsTest(); - -protected: - int read_params( CvFileStorage* fs ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - bool calc_jacobians; -}; - - -CV_ProjectPointsTest::CV_ProjectPointsTest() - : CvArrTest( "3d-ProjectPoints", "cvProjectPoints2", "" ) -{ - test_array[INPUT].push(NULL); // rotation vector - test_array[OUTPUT].push(NULL); // rotation matrix - test_array[OUTPUT].push(NULL); // jacobian (J) - test_array[OUTPUT].push(NULL); // rotation vector (backward transform result) - test_array[OUTPUT].push(NULL); // inverse transform jacobian (J1) - test_array[OUTPUT].push(NULL); // J*J1 (or J1*J) == I(3x3) - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - element_wise_relative_error = false; - calc_jacobians = false; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_ProjectPointsTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_ProjectPointsTest::get_test_array_types_and_sizes( - int /*test_case_idx*/, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - int i, code; - - code = cvTsRandInt(rng) % 3; - types[INPUT][0] = CV_MAKETYPE(depth, 1); - - if( code == 0 ) - { - sizes[INPUT][0] = cvSize(1,1); - types[INPUT][0] = CV_MAKETYPE(depth, 3); - } - else if( code == 1 ) - sizes[INPUT][0] = cvSize(3,1); - else - sizes[INPUT][0] = cvSize(1,3); - - sizes[OUTPUT][0] = cvSize(3, 3); - types[OUTPUT][0] = CV_MAKETYPE(depth, 1); - - types[OUTPUT][1] = CV_MAKETYPE(depth, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][1] = cvSize(3,9); - else - sizes[OUTPUT][1] = cvSize(9,3); - - types[OUTPUT][2] = types[INPUT][0]; - sizes[OUTPUT][2] = sizes[INPUT][0]; - - types[OUTPUT][3] = types[OUTPUT][1]; - sizes[OUTPUT][3] = cvSize(sizes[OUTPUT][1].height, sizes[OUTPUT][1].width); - - types[OUTPUT][4] = types[OUTPUT][1]; - sizes[OUTPUT][4] = cvSize(3,3); - - calc_jacobians = 1;//cvTsRandInt(rng) % 3 != 0; - if( !calc_jacobians ) - sizes[OUTPUT][1] = sizes[OUTPUT][3] = sizes[OUTPUT][4] = cvSize(0,0); - - for( i = 0; i < 5; i++ ) - { - types[REF_OUTPUT][i] = types[OUTPUT][i]; - sizes[REF_OUTPUT][i] = sizes[OUTPUT][i]; - } -} - - -double CV_ProjectPointsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int j ) -{ - return j == 4 ? 1e-2 : 1e-2; -} - - -void CV_ProjectPointsTest::fill_array( int /*test_case_idx*/, int /*i*/, int /*j*/, CvMat* arr ) -{ - double r[3], theta0, theta1, f; - CvMat _r = cvMat( arr->rows, arr->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(arr->type)), r ); - CvRNG* rng = ts->get_rng(); - - r[0] = cvTsRandReal(rng)*CV_PI*2; - r[1] = cvTsRandReal(rng)*CV_PI*2; - r[2] = cvTsRandReal(rng)*CV_PI*2; - - theta0 = sqrt(r[0]*r[0] + r[1]*r[1] + r[2]*r[2]); - theta1 = fmod(theta0, CV_PI*2); - - if( theta1 > CV_PI ) - theta1 = -(CV_PI*2 - theta1); - - f = theta1/(theta0 ? theta0 : 1); - r[0] *= f; - r[1] *= f; - r[2] *= f; - - cvTsConvert( &_r, arr ); -} - - -int CV_ProjectPointsTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - return code; -} - - -void CV_ProjectPointsTest::run_func() -{ - CvMat *v2m_jac = 0, *m2v_jac = 0; - if( calc_jacobians ) - { - v2m_jac = &test_mat[OUTPUT][1]; - m2v_jac = &test_mat[OUTPUT][3]; - } - - cvProjectPoints2( &test_mat[INPUT][0], &test_mat[OUTPUT][0], v2m_jac ); - cvProjectPoints2( &test_mat[OUTPUT][0], &test_mat[OUTPUT][2], m2v_jac ); -} - - -void CV_ProjectPointsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - const CvMat* vec = &test_mat[INPUT][0]; - CvMat* m = &test_mat[REF_OUTPUT][0]; - CvMat* vec2 = &test_mat[REF_OUTPUT][2]; - CvMat* v2m_jac = 0, *m2v_jac = 0; - double theta0, theta1; - - if( calc_jacobians ) - { - v2m_jac = &test_mat[REF_OUTPUT][1]; - m2v_jac = &test_mat[REF_OUTPUT][3]; - } - - - cvTsProjectPoints( vec, m, v2m_jac ); - cvTsProjectPoints( m, vec2, m2v_jac ); - cvTsCopy( vec, vec2 ); - - theta0 = cvNorm( vec2, 0, CV_L2 ); - theta1 = fmod( theta0, CV_PI*2 ); - - if( theta1 > CV_PI ) - theta1 = -(CV_PI*2 - theta1); - cvScale( vec2, vec2, theta1/(theta0 ? theta0 : 1) ); - - if( calc_jacobians ) - { - //cvInvert( v2m_jac, m2v_jac, CV_SVD ); - if( cvNorm(&test_mat[OUTPUT][3],0,CV_C) < 1000 ) - { - cvTsGEMM( &test_mat[OUTPUT][1], &test_mat[OUTPUT][3], - 1, 0, 0, &test_mat[OUTPUT][4], - v2m_jac->rows == 3 ? 0 : CV_GEMM_A_T + CV_GEMM_B_T ); - } - else - { - cvTsSetIdentity( &test_mat[OUTPUT][4], cvScalarAll(1.) ); - cvTsCopy( &test_mat[REF_OUTPUT][2], &test_mat[OUTPUT][2] ); - } - cvTsSetIdentity( &test_mat[REF_OUTPUT][4], cvScalarAll(1.) ); - } -} - - -CV_ProjectPointsTest ProjectPoints_test; - -#endif - -using namespace cv; - -// --------------------------------- CV_CameraCalibrationTest -------------------------------------------- - -class CV_CameraCalibrationTest : public CvTest -{ -public: - CV_CameraCalibrationTest( const char* testName, const char* testFuncs ); - ~CV_CameraCalibrationTest(); - void clear(); -protected: - int compare(double* val, double* refVal, int len, - double eps, const char* paramName); - virtual void calibrate( int imageCount, int* pointCounts, - CvSize imageSize, CvPoint2D64f* imagePoints, CvPoint3D64f* objectPoints, - double* distortionCoeffs, double* cameraMatrix, double* translationVectors, - double* rotationMatrices, int flags ) = 0; - virtual void project( int pointCount, CvPoint3D64f* objectPoints, - double* rotationMatrix, double* translationVector, - double* cameraMatrix, double* distortion, CvPoint2D64f* imagePoints ) = 0; - - void run(int); -}; - -CV_CameraCalibrationTest::CV_CameraCalibrationTest( const char* testName, const char* testFuncs ): - CvTest( testName, testFuncs ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -CV_CameraCalibrationTest::~CV_CameraCalibrationTest() -{ - clear(); -} - -void CV_CameraCalibrationTest::clear() -{ - CvTest::clear(); -} - -int CV_CameraCalibrationTest::compare(double* val, double* ref_val, int len, - double eps, const char* param_name ) -{ - return cvTsCmpEps2_64f( ts, val, ref_val, len, eps, param_name ); -} - -void CV_CameraCalibrationTest::run( int start_from ) -{ - int code = CvTS::OK; - char filepath[200]; - char filename[200]; - - CvSize imageSize; - CvSize etalonSize; - int numImages; - - CvPoint2D64f* imagePoints; - CvPoint3D64f* objectPoints; - CvPoint2D64f* reprojectPoints; - - double* transVects; - double* rotMatrs; - - double* goodTransVects; - double* goodRotMatrs; - - double cameraMatrix[3*3]; - double distortion[5]={0,0,0,0,0}; - - double goodDistortion[4]; - - int* numbers; - FILE* file = 0; - FILE* datafile = 0; - int i,j; - int currImage; - int currPoint; - - int calibFlags; - char i_dat_file[100]; - int numPoints; - int numTests; - int currTest; - - imagePoints = 0; - objectPoints = 0; - reprojectPoints = 0; - numbers = 0; - - transVects = 0; - rotMatrs = 0; - goodTransVects = 0; - goodRotMatrs = 0; - int progress = 0; - - sprintf( filepath, "%scameracalibration/", ts->get_data_path() ); - sprintf( filename, "%sdatafiles.txt", filepath ); - datafile = fopen( filename, "r" ); - if( datafile == 0 ) - { - ts->printf( CvTS::LOG, "Could not open file with list of test files: %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - fscanf(datafile,"%d",&numTests); - - for( currTest = start_from; currTest < numTests; currTest++ ) - { - fscanf(datafile,"%s",i_dat_file); - sprintf(filename, "%s%s", filepath, i_dat_file); - file = fopen(filename,"r"); - - ts->update_context( this, currTest, true ); - - if( file == 0 ) - { - ts->printf( CvTS::LOG, - "Can't open current test file: %s\n",filename); - if( numTests == 1 ) - { - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - continue; // if there is more than one test, just skip the test - } - - fscanf(file,"%d %d\n",&(imageSize.width),&(imageSize.height)); - if( imageSize.width <= 0 || imageSize.height <= 0 ) - { - ts->printf( CvTS::LOG, "Image size in test file is incorrect\n" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - /* Read etalon size */ - fscanf(file,"%d %d\n",&(etalonSize.width),&(etalonSize.height)); - if( etalonSize.width <= 0 || etalonSize.height <= 0 ) - { - ts->printf( CvTS::LOG, "Pattern size in test file is incorrect\n" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - numPoints = etalonSize.width * etalonSize.height; - - /* Read number of images */ - fscanf(file,"%d\n",&numImages); - if( numImages <=0 ) - { - ts->printf( CvTS::LOG, "Number of images in test file is incorrect\n"); - code = CvTS::FAIL_INVALID_TEST_DATA; - goto _exit_; - } - - /* Need to allocate memory */ - imagePoints = (CvPoint2D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint2D64f)); - - objectPoints = (CvPoint3D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint3D64f)); - - reprojectPoints = (CvPoint2D64f*)cvAlloc( numPoints * - numImages * sizeof(CvPoint2D64f)); - - /* Alloc memory for numbers */ - numbers = (int*)cvAlloc( numImages * sizeof(int)); - - /* Fill it by numbers of points of each image*/ - for( currImage = 0; currImage < numImages; currImage++ ) - { - numbers[currImage] = etalonSize.width * etalonSize.height; - } - - /* Allocate memory for translate vectors and rotmatrixs*/ - transVects = (double*)cvAlloc(3 * 1 * numImages * sizeof(double)); - rotMatrs = (double*)cvAlloc(3 * 3 * numImages * sizeof(double)); - - goodTransVects = (double*)cvAlloc(3 * 1 * numImages * sizeof(double)); - goodRotMatrs = (double*)cvAlloc(3 * 3 * numImages * sizeof(double)); - - /* Read object points */ - i = 0;/* shift for current point */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < numPoints; currPoint++ ) - { - double x,y,z; - fscanf(file,"%lf %lf %lf\n",&x,&y,&z); - - (objectPoints+i)->x = x; - (objectPoints+i)->y = y; - (objectPoints+i)->z = z; - i++; - } - } - - /* Read image points */ - i = 0;/* shift for current point */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < numPoints; currPoint++ ) - { - double x,y; - fscanf(file,"%lf %lf\n",&x,&y); - - (imagePoints+i)->x = x; - (imagePoints+i)->y = y; - i++; - } - } - - /* Read good data computed before */ - - /* Focal lengths */ - double goodFcx,goodFcy; - fscanf(file,"%lf %lf",&goodFcx,&goodFcy); - - /* Principal points */ - double goodCx,goodCy; - fscanf(file,"%lf %lf",&goodCx,&goodCy); - - /* Read distortion */ - - fscanf(file,"%lf",goodDistortion+0); - fscanf(file,"%lf",goodDistortion+1); - fscanf(file,"%lf",goodDistortion+2); - fscanf(file,"%lf",goodDistortion+3); - - /* Read good Rot matrixes */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( i = 0; i < 3; i++ ) - for( j = 0; j < 3; j++ ) - fscanf(file, "%lf", goodRotMatrs + currImage * 9 + j * 3 + i); - } - - /* Read good Trans vectors */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( i = 0; i < 3; i++ ) - fscanf(file, "%lf", goodTransVects + currImage * 3 + i); - } - - calibFlags = 0 - // + CV_CALIB_FIX_PRINCIPAL_POINT - // + CV_CALIB_ZERO_TANGENT_DIST - // + CV_CALIB_FIX_ASPECT_RATIO - // + CV_CALIB_USE_INTRINSIC_GUESS - + CV_CALIB_FIX_K3 - + CV_CALIB_FIX_K4+CV_CALIB_FIX_K5 - + CV_CALIB_FIX_K6 - ; - memset( cameraMatrix, 0, 9*sizeof(cameraMatrix[0]) ); - cameraMatrix[0] = cameraMatrix[4] = 807.; - cameraMatrix[2] = (imageSize.width - 1)*0.5; - cameraMatrix[5] = (imageSize.height - 1)*0.5; - cameraMatrix[8] = 1.; - - /* Now we can calibrate camera */ - calibrate( numImages, - numbers, - imageSize, - imagePoints, - objectPoints, - distortion, - cameraMatrix, - transVects, - rotMatrs, - calibFlags ); - - /* ---- Reproject points to the image ---- */ - for( currImage = 0; currImage < numImages; currImage++ ) - { - int numPoints = etalonSize.width * etalonSize.height; - project( numPoints, - objectPoints + currImage * numPoints, - rotMatrs + currImage * 9, - transVects + currImage * 3, - cameraMatrix, - distortion, - reprojectPoints + currImage * numPoints); - } - - /* ----- Compute reprojection error ----- */ - i = 0; - double dx,dy; - double rx,ry; - double meanDx,meanDy; - double maxDx = 0.0; - double maxDy = 0.0; - - meanDx = 0; - meanDy = 0; - for( currImage = 0; currImage < numImages; currImage++ ) - { - for( currPoint = 0; currPoint < etalonSize.width * etalonSize.height; currPoint++ ) - { - rx = reprojectPoints[i].x; - ry = reprojectPoints[i].y; - dx = rx - imagePoints[i].x; - dy = ry - imagePoints[i].y; - - meanDx += dx; - meanDy += dy; - - dx = fabs(dx); - dy = fabs(dy); - - if( dx > maxDx ) - maxDx = dx; - - if( dy > maxDy ) - maxDy = dy; - i++; - } - } - - meanDx /= numImages * etalonSize.width * etalonSize.height; - meanDy /= numImages * etalonSize.width * etalonSize.height; - - /* ========= Compare parameters ========= */ - - /* ----- Compare focal lengths ----- */ - code = compare(cameraMatrix+0,&goodFcx,1,0.1,"fx"); - if( code < 0 ) - goto _exit_; - - code = compare(cameraMatrix+4,&goodFcy,1,0.1,"fy"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare principal points ----- */ - code = compare(cameraMatrix+2,&goodCx,1,0.1,"cx"); - if( code < 0 ) - goto _exit_; - - code = compare(cameraMatrix+5,&goodCy,1,0.1,"cy"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare distortion ----- */ - code = compare(distortion,goodDistortion,4,0.1,"[k1,k2,p1,p2]"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare rot matrixs ----- */ - code = compare(rotMatrs,goodRotMatrs, 9*numImages,0.05,"rotation matrices"); - if( code < 0 ) - goto _exit_; - - /* ----- Compare rot matrixs ----- */ - code = compare(transVects,goodTransVects, 3*numImages,0.1,"translation vectors"); - if( code < 0 ) - goto _exit_; - - if( maxDx > 1.0 ) - { - ts->printf( CvTS::LOG, - "Error in reprojection maxDx=%f > 1.0\n",maxDx); - code = CvTS::FAIL_BAD_ACCURACY; goto _exit_; - } - - if( maxDy > 1.0 ) - { - ts->printf( CvTS::LOG, - "Error in reprojection maxDy=%f > 1.0\n",maxDy); - code = CvTS::FAIL_BAD_ACCURACY; goto _exit_; - } - - progress = update_progress( progress, currTest, numTests, 0 ); - - cvFree(&imagePoints); - cvFree(&objectPoints); - cvFree(&reprojectPoints); - cvFree(&numbers); - - cvFree(&transVects); - cvFree(&rotMatrs); - cvFree(&goodTransVects); - cvFree(&goodRotMatrs); - - fclose(file); - file = 0; - } - -_exit_: - - if( file ) - fclose(file); - - if( datafile ) - fclose(datafile); - - /* Free all allocated memory */ - cvFree(&imagePoints); - cvFree(&objectPoints); - cvFree(&reprojectPoints); - cvFree(&numbers); - - cvFree(&transVects); - cvFree(&rotMatrs); - cvFree(&goodTransVects); - cvFree(&goodRotMatrs); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -// --------------------------------- CV_CameraCalibrationTest_C -------------------------------------------- - -class CV_CameraCalibrationTest_C : public CV_CameraCalibrationTest -{ -public: - CV_CameraCalibrationTest_C() : CV_CameraCalibrationTest( "calibrate-camera-c", "cvCalibrateCamera2" ) {} -protected: - virtual void calibrate( int imageCount, int* pointCounts, - CvSize imageSize, CvPoint2D64f* imagePoints, CvPoint3D64f* objectPoints, - double* distortionCoeffs, double* cameraMatrix, double* translationVectors, - double* rotationMatrices, int flags ); - virtual void project( int pointCount, CvPoint3D64f* objectPoints, - double* rotationMatrix, double* translationVector, - double* cameraMatrix, double* distortion, CvPoint2D64f* imagePoints ); -}; - -void CV_CameraCalibrationTest_C::calibrate( int imageCount, int* pointCounts, - CvSize imageSize, CvPoint2D64f* imagePoints, CvPoint3D64f* objectPoints, - double* distortionCoeffs, double* cameraMatrix, double* translationVectors, - double* rotationMatrices, int flags ) -{ - cvCalibrateCamera_64d( imageCount, - pointCounts, - imageSize, - imagePoints, - objectPoints, - distortionCoeffs, - cameraMatrix, - translationVectors, - rotationMatrices, - flags ); -} - -void CV_CameraCalibrationTest_C::project( int pointCount, CvPoint3D64f* objectPoints, - double* rotationMatrix, double* translationVector, - double* cameraMatrix, double* distortion, CvPoint2D64f* imagePoints ) -{ - cvProjectPointsSimple( pointCount, - objectPoints, - rotationMatrix, - translationVector, - cameraMatrix, - distortion, - imagePoints ); -} - -CV_CameraCalibrationTest_C calibrate_test_c; - -// --------------------------------- CV_CameraCalibrationTest_CPP -------------------------------------------- - -class CV_CameraCalibrationTest_CPP : public CV_CameraCalibrationTest -{ -public: - CV_CameraCalibrationTest_CPP() : CV_CameraCalibrationTest( "calibrate-camera-cpp", "cv::calibrateCamera" ) {} -protected: - virtual void calibrate( int imageCount, int* pointCounts, - CvSize imageSize, CvPoint2D64f* imagePoints, CvPoint3D64f* objectPoints, - double* distortionCoeffs, double* cameraMatrix, double* translationVectors, - double* rotationMatrices, int flags ); - virtual void project( int pointCount, CvPoint3D64f* objectPoints, - double* rotationMatrix, double* translationVector, - double* cameraMatrix, double* distortion, CvPoint2D64f* imagePoints ); -}; - -void CV_CameraCalibrationTest_CPP::calibrate( int imageCount, int* pointCounts, - CvSize _imageSize, CvPoint2D64f* _imagePoints, CvPoint3D64f* _objectPoints, - double* _distortionCoeffs, double* _cameraMatrix, double* translationVectors, - double* rotationMatrices, int flags ) -{ - vector > objectPoints( imageCount ); - vector > imagePoints( imageCount ); - Size imageSize = _imageSize; - Mat cameraMatrix, distCoeffs(1,4,CV_64F,Scalar::all(0)); - vector rvecs, tvecs; - - CvPoint3D64f* op = _objectPoints; - CvPoint2D64f* ip = _imagePoints; - vector >::iterator objectPointsIt = objectPoints.begin(); - vector >::iterator imagePointsIt = imagePoints.begin(); - for( int i = 0; i < imageCount; ++objectPointsIt, ++imagePointsIt, i++ ) - { - int num = pointCounts[i]; - objectPointsIt->resize( num ); - imagePointsIt->resize( num ); - vector::iterator oIt = objectPointsIt->begin(); - vector::iterator iIt = imagePointsIt->begin(); - for( int j = 0; j < num; ++oIt, ++iIt, j++, op++, ip++) - { - oIt->x = (float)op->x, oIt->y = (float)op->y, oIt->z = (float)op->z; - iIt->x = (float)ip->x, iIt->y = (float)ip->y; - } - } - - calibrateCamera( objectPoints, - imagePoints, - imageSize, - cameraMatrix, - distCoeffs, - rvecs, - tvecs, - flags ); - - assert( cameraMatrix.type() == CV_64FC1 ); - memcpy( _cameraMatrix, cameraMatrix.data, 9*sizeof(double) ); - - assert( cameraMatrix.type() == CV_64FC1 ); - memcpy( _distortionCoeffs, distCoeffs.data, 4*sizeof(double) ); - - vector::iterator rvecsIt = rvecs.begin(); - vector::iterator tvecsIt = tvecs.begin(); - double *rm = rotationMatrices, - *tm = translationVectors; - assert( rvecsIt->type() == CV_64FC1 ); - assert( tvecsIt->type() == CV_64FC1 ); - for( int i = 0; i < imageCount; ++rvecsIt, ++tvecsIt, i++, rm+=9, tm+=3 ) - { - Mat r9( 3, 3, CV_64FC1 ); - Rodrigues( *rvecsIt, r9 ); - memcpy( rm, r9.data, 9*sizeof(double) ); - memcpy( tm, tvecsIt->data, 3*sizeof(double) ); - } -} - -void CV_CameraCalibrationTest_CPP::project( int pointCount, CvPoint3D64f* _objectPoints, - double* rotationMatrix, double* translationVector, - double* _cameraMatrix, double* distortion, CvPoint2D64f* _imagePoints ) -{ - Mat objectPoints( pointCount, 3, CV_64FC1, _objectPoints ); - Mat rmat( 3, 3, CV_64FC1, rotationMatrix ), - rvec( 1, 3, CV_64FC1 ), - tvec( 1, 3, CV_64FC1, translationVector ); - Mat cameraMatrix( 3, 3, CV_64FC1, _cameraMatrix ); - Mat distCoeffs( 1, 4, CV_64FC1, distortion ); - vector imagePoints; - Rodrigues( rmat, rvec ); - - objectPoints.convertTo( objectPoints, CV_32FC1 ); - projectPoints( objectPoints, rvec, tvec, - cameraMatrix, distCoeffs, imagePoints ); - vector::const_iterator it = imagePoints.begin(); - for( int i = 0; it != imagePoints.end(); ++it, i++ ) - { - _imagePoints[i] = cvPoint2D64f( it->x, it->y ); - } -} - -CV_CameraCalibrationTest_CPP calibrate_test_cpp; - -//----------------------------------------- CV_CalibrationMatrixValuesTest -------------------------------- - -class CV_CalibrationMatrixValuesTest : public CvTest -{ -public: - CV_CalibrationMatrixValuesTest( const char* testName, const char* testFuncs ) : - CvTest( testName, testFuncs ) {} -protected: - void run(int); - virtual void calibMatrixValues( const Mat& cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, - Point2d& principalPoint, double& aspectRatio ) = 0; -}; - -void CV_CalibrationMatrixValuesTest::run(int) -{ - int code = CvTS::OK; - const double fcMinVal = 1e-5; - const double fcMaxVal = 1000; - const double apertureMaxVal = 0.01; - - RNG rng = *ts->get_rng(); - - double fx, fy, cx, cy, nx, ny; - Mat cameraMatrix( 3, 3, CV_64FC1 ); - cameraMatrix.setTo( Scalar(0) ); - fx = cameraMatrix.at(0,0) = rng.uniform( fcMinVal, fcMaxVal ); - fy = cameraMatrix.at(1,1) = rng.uniform( fcMinVal, fcMaxVal ); - cx = cameraMatrix.at(0,2) = rng.uniform( fcMinVal, fcMaxVal ); - cy = cameraMatrix.at(1,2) = rng.uniform( fcMinVal, fcMaxVal ); - cameraMatrix.at(2,2) = 1; - - Size imageSize( 600, 400 ); - - double apertureWidth = (double)rng * apertureMaxVal, - apertureHeight = (double)rng * apertureMaxVal; - - double fovx, fovy, focalLength, aspectRatio, - goodFovx, goodFovy, goodFocalLength, goodAspectRatio; - Point2d principalPoint, goodPrincipalPoint; - - - calibMatrixValues( cameraMatrix, imageSize, apertureWidth, apertureHeight, - fovx, fovy, focalLength, principalPoint, aspectRatio ); - - // calculate calibration matrix values - goodAspectRatio = fy / fx; - - if( apertureWidth != 0.0 && apertureHeight != 0.0 ) - { - nx = imageSize.width / apertureWidth; - ny = imageSize.height / apertureHeight; - } - else - { - nx = 1.0; - ny = goodAspectRatio; - } - - goodFovx = 2 * atan( imageSize.width / (2 * fx)) * 180.0 / CV_PI; - goodFovy = 2 * atan( imageSize.height / (2 * fy)) * 180.0 / CV_PI; - - goodFocalLength = fx / nx; - - goodPrincipalPoint.x = cx / nx; - goodPrincipalPoint.y = cy / ny; - - // check results - if( fabs(fovx - goodFovx) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "bad fovx (real=%f, good = %f\n", fovx, goodFovx ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - if( fabs(fovy - goodFovy) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "bad fovy (real=%f, good = %f\n", fovy, goodFovy ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - if( fabs(focalLength - goodFocalLength) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "bad focalLength (real=%f, good = %f\n", focalLength, goodFocalLength ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - if( fabs(aspectRatio - goodAspectRatio) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "bad aspectRatio (real=%f, good = %f\n", aspectRatio, goodAspectRatio ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - if( norm( principalPoint - goodPrincipalPoint ) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "bad principalPoint\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - CvRNG* _rng = ts->get_rng(); - *_rng = rng.state; - ts->set_failed_test_info( code ); -} - -//----------------------------------------- CV_CalibrationMatrixValuesTest_C -------------------------------- - -class CV_CalibrationMatrixValuesTest_C : public CV_CalibrationMatrixValuesTest -{ -public: - CV_CalibrationMatrixValuesTest_C() : - CV_CalibrationMatrixValuesTest( "calibMatrixValues-c", "cvCalibrationMatrixValues" ) {} -protected: - virtual void calibMatrixValues( const Mat& cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, - Point2d& principalPoint, double& aspectRatio ); -}; - -void CV_CalibrationMatrixValuesTest_C::calibMatrixValues( const Mat& _cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, - double& fovx, double& fovy, double& focalLength, - Point2d& principalPoint, double& aspectRatio ) -{ - CvMat cameraMatrix = _cameraMatrix; - CvPoint2D64f pp; - cvCalibrationMatrixValues( &cameraMatrix, imageSize, apertureWidth, apertureHeight, - &fovx, &fovy, &focalLength, &pp, &aspectRatio ); - principalPoint.x = pp.x; - principalPoint.y = pp.y; -} - -CV_CalibrationMatrixValuesTest_C calibMatrixValues_test_c; - -//----------------------------------------- CV_CalibrationMatrixValuesTest_CPP -------------------------------- - -class CV_CalibrationMatrixValuesTest_CPP : public CV_CalibrationMatrixValuesTest -{ -public: - CV_CalibrationMatrixValuesTest_CPP() : - CV_CalibrationMatrixValuesTest( "calibMatrixValues-cpp", "cv::calibrationMatrixValues" ) {} -protected: - virtual void calibMatrixValues( const Mat& cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength, - Point2d& principalPoint, double& aspectRatio ); -}; - -void CV_CalibrationMatrixValuesTest_CPP::calibMatrixValues( const Mat& cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, - double& fovx, double& fovy, double& focalLength, - Point2d& principalPoint, double& aspectRatio ) -{ - calibrationMatrixValues( cameraMatrix, imageSize, apertureWidth, apertureHeight, - fovx, fovy, focalLength, principalPoint, aspectRatio ); -} - -CV_CalibrationMatrixValuesTest_CPP calibMatrixValues_test_cpp; - -//----------------------------------------- CV_ProjectPointsTest -------------------------------- -void calcdfdx( const vector >& leftF, const vector >& rightF, double eps, Mat& dfdx ) -{ - const int fdim = 2; - CV_Assert( !leftF.empty() && !rightF.empty() && !leftF[0].empty() && !rightF[0].empty() ); - CV_Assert( leftF[0].size() == rightF[0].size() ); - CV_Assert( fabs(eps) > std::numeric_limits::epsilon() ); - int fcount = (int)leftF[0].size(), xdim = (int)leftF.size(); - - dfdx.create( fcount*fdim, xdim, CV_64FC1 ); - - vector >::const_iterator arrLeftIt = leftF.begin(); - vector >::const_iterator arrRightIt = rightF.begin(); - for( int xi = 0; xi < xdim; xi++, ++arrLeftIt, ++arrRightIt ) - { - CV_Assert( (int)arrLeftIt->size() == fcount ); - CV_Assert( (int)arrRightIt->size() == fcount ); - vector::const_iterator lIt = arrLeftIt->begin(); - vector::const_iterator rIt = arrRightIt->begin(); - for( int fi = 0; fi < dfdx.rows; fi+=fdim, ++lIt, ++rIt ) - { - dfdx.at(fi, xi ) = 0.5 * ((double)(rIt->x - lIt->x)) / eps; - dfdx.at(fi+1, xi ) = 0.5 * ((double)(rIt->y - lIt->y)) / eps; - } - } -} - -class CV_ProjectPointsTest : public CvTest -{ -public: - CV_ProjectPointsTest( const char* testName, const char* testFuncs ) : - CvTest( testName, testFuncs ) {} -protected: - void run(int); - virtual void project( const Mat& objectPoints, - const Mat& rvec, const Mat& tvec, - const Mat& cameraMatrix, - const Mat& distCoeffs, - vector& imagePoints, - Mat& dpdrot, Mat& dpdt, Mat& dpdf, - Mat& dpdc, Mat& dpddist, - double aspectRatio=0 ) = 0; -}; - -void CV_ProjectPointsTest::run(int) -{ - //typedef float matType; - - int code = CvTS::OK; - const int pointCount = 100; - - const float zMinVal = 10.0f, zMaxVal = 100.0f, - rMinVal = -0.3f, rMaxVal = 0.3f, - tMinVal = -2.0f, tMaxVal = 2.0f; - - const float imgPointErr = 1e-3f, - dEps = 1e-3f; - - double err; - - Size imgSize( 600, 800 ); - Mat_ objPoints( pointCount, 3), rvec( 1, 3), rmat, tvec( 1, 3 ), cameraMatrix( 3, 3 ), distCoeffs( 1, 4 ), - leftRvec, rightRvec, leftTvec, rightTvec, leftCameraMatrix, rightCameraMatrix, leftDistCoeffs, rightDistCoeffs; - - RNG rng = *ts->get_rng(); - - // generate data - cameraMatrix << 300.f, 0.f, imgSize.width/2.f, - 0.f, 300.f, imgSize.height/2.f, - 0.f, 0.f, 1.f; - distCoeffs << 0.1, 0.01, 0.001, 0.001; - - rvec(0,0) = rng.uniform( rMinVal, rMaxVal ); - rvec(0,1) = rng.uniform( rMinVal, rMaxVal ); - rvec(0,2) = rng.uniform( rMinVal, rMaxVal ); - Rodrigues( rvec, rmat ); - - tvec(0,0) = rng.uniform( tMinVal, tMaxVal ); - tvec(0,1) = rng.uniform( tMinVal, tMaxVal ); - tvec(0,2) = rng.uniform( tMinVal, tMaxVal ); - - for( int y = 0; y < objPoints.rows; y++ ) - { - Mat point(1, 3, CV_32FC1, objPoints.ptr(y) ); - float z = rng.uniform( zMinVal, zMaxVal ); - point.at(0,2) = z; - point.at(0,0) = (rng.uniform(2.f,(float)(imgSize.width-2)) - cameraMatrix(0,2)) / cameraMatrix(0,0) * z; - point.at(0,1) = (rng.uniform(2.f,(float)(imgSize.height-2)) - cameraMatrix(1,2)) / cameraMatrix(1,1) * z; - point = (point - tvec) * rmat; - } - - vector imgPoints; - vector > leftImgPoints; - vector > rightImgPoints; - Mat dpdrot, dpdt, dpdf, dpdc, dpddist, - valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist; - - project( objPoints, rvec, tvec, cameraMatrix, distCoeffs, - imgPoints, dpdrot, dpdt, dpdf, dpdc, dpddist, 0 ); - - // calculate and check image points - assert( (int)imgPoints.size() == pointCount ); - vector::const_iterator it = imgPoints.begin(); - for( int i = 0; i < pointCount; i++, ++it ) - { - Point3d p( objPoints(i,0), objPoints(i,1), objPoints(i,2) ); - double z = p.x*rmat(2,0) + p.y*rmat(2,1) + p.z*rmat(2,2) + tvec(0,2), - x = (p.x*rmat(0,0) + p.y*rmat(0,1) + p.z*rmat(0,2) + tvec(0,0)) / z, - y = (p.x*rmat(1,0) + p.y*rmat(1,1) + p.z*rmat(1,2) + tvec(0,1)) / z, - r2 = x*x + y*y, - r4 = r2*r2; - Point2f validImgPoint; - double a1 = 2*x*y, - a2 = r2 + 2*x*x, - a3 = r2 + 2*y*y, - cdist = 1+distCoeffs(0,0)*r2+distCoeffs(0,1)*r4; - validImgPoint.x = static_cast((double)cameraMatrix(0,0)*(x*cdist + (double)distCoeffs(0,2)*a1 + (double)distCoeffs(0,3)*a2) - + (double)cameraMatrix(0,2)); - validImgPoint.y = static_cast((double)cameraMatrix(1,1)*(y*cdist + (double)distCoeffs(0,2)*a3 + distCoeffs(0,3)*a1) - + (double)cameraMatrix(1,2)); - - Point2f ssdfp = *it; - if( fabs(it->x - validImgPoint.x) > imgPointErr || - fabs(it->y - validImgPoint.y) > imgPointErr ) - { - ts->printf( CvTS::LOG, "bad image point\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - } - - // check derivatives - // 1. rotation - leftImgPoints.resize(3); - rightImgPoints.resize(3); - for( int i = 0; i < 3; i++ ) - { - rvec.copyTo( leftRvec ); leftRvec(0,i) -= dEps; - project( objPoints, leftRvec, tvec, cameraMatrix, distCoeffs, - leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - rvec.copyTo( rightRvec ); rightRvec(0,i) += dEps; - project( objPoints, rightRvec, tvec, cameraMatrix, distCoeffs, - rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - } - calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdrot ); - err = norm( dpdrot, valDpdrot, NORM_INF ); - if( err > 3 ) - { - ts->printf( CvTS::LOG, "bad dpdrot: too big difference = %g\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // 2. translation - for( int i = 0; i < 3; i++ ) - { - tvec.copyTo( leftTvec ); leftTvec(0,i) -= dEps; - project( objPoints, rvec, leftTvec, cameraMatrix, distCoeffs, - leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - tvec.copyTo( rightTvec ); rightTvec(0,i) += dEps; - project( objPoints, rvec, rightTvec, cameraMatrix, distCoeffs, - rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - } - calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdt ); - if( norm( dpdt, valDpdt, NORM_INF ) > 0.2 ) - { - ts->printf( CvTS::LOG, "bad dpdtvec\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // 3. camera matrix - // 3.1. focus - leftImgPoints.resize(2); - rightImgPoints.resize(2); - cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(0,0) -= dEps; - project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs, - leftImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(1,1) -= dEps; - project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs, - leftImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(0,0) += dEps; - project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs, - rightImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(1,1) += dEps; - project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs, - rightImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdf ); - if ( norm( dpdf, valDpdf ) > 0.2 ) - { - ts->printf( CvTS::LOG, "bad dpdf\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - // 3.2. principal point - leftImgPoints.resize(2); - rightImgPoints.resize(2); - cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(0,2) -= dEps; - project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs, - leftImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( leftCameraMatrix ); leftCameraMatrix(1,2) -= dEps; - project( objPoints, rvec, tvec, leftCameraMatrix, distCoeffs, - leftImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(0,2) += dEps; - project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs, - rightImgPoints[0], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - cameraMatrix.copyTo( rightCameraMatrix ); rightCameraMatrix(1,2) += dEps; - project( objPoints, rvec, tvec, rightCameraMatrix, distCoeffs, - rightImgPoints[1], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpdc ); - if ( norm( dpdc, valDpdc ) > 0.2 ) - { - ts->printf( CvTS::LOG, "bad dpdc\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // 4. distortion - leftImgPoints.resize(distCoeffs.cols); - rightImgPoints.resize(distCoeffs.cols); - for( int i = 0; i < distCoeffs.cols; i++ ) - { - distCoeffs.copyTo( leftDistCoeffs ); leftDistCoeffs(0,i) -= dEps; - project( objPoints, rvec, tvec, cameraMatrix, leftDistCoeffs, - leftImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - distCoeffs.copyTo( rightDistCoeffs ); rightDistCoeffs(0,i) += dEps; - project( objPoints, rvec, tvec, cameraMatrix, rightDistCoeffs, - rightImgPoints[i], valDpdrot, valDpdt, valDpdf, valDpdc, valDpddist, 0 ); - } - calcdfdx( leftImgPoints, rightImgPoints, dEps, valDpddist ); - if( norm( dpddist, valDpddist ) > 0.3 ) - { - ts->printf( CvTS::LOG, "bad dpddist\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - -_exit_: - CvRNG* _rng = ts->get_rng(); - *_rng = rng.state; - ts->set_failed_test_info( code ); -} - -//----------------------------------------- CV_ProjectPointsTest_C -------------------------------- -class CV_ProjectPointsTest_C : public CV_ProjectPointsTest -{ -public: - CV_ProjectPointsTest_C() : - CV_ProjectPointsTest( "projectPoints-c", "cvProjectPoints" ) {} -protected: - virtual void project( const Mat& objectPoints, - const Mat& rvec, const Mat& tvec, - const Mat& cameraMatrix, - const Mat& distCoeffs, - vector& imagePoints, - Mat& dpdrot, Mat& dpdt, Mat& dpdf, - Mat& dpdc, Mat& dpddist, - double aspectRatio=0 ); -}; - -void CV_ProjectPointsTest_C::project( const Mat& opoints, const Mat& rvec, const Mat& tvec, - const Mat& cameraMatrix, const Mat& distCoeffs, vector& ipoints, - Mat& dpdrot, Mat& dpdt, Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio) -{ - int npoints = opoints.cols*opoints.rows*opoints.channels()/3; - ipoints.resize(npoints); - dpdrot.create(npoints*2, 3, CV_64F); - dpdt.create(npoints*2, 3, CV_64F); - dpdf.create(npoints*2, 2, CV_64F); - dpdc.create(npoints*2, 2, CV_64F); - dpddist.create(npoints*2, distCoeffs.rows + distCoeffs.cols - 1, CV_64F); - CvMat _objectPoints = opoints, _imagePoints = Mat(ipoints); - CvMat _rvec = rvec, _tvec = tvec, _cameraMatrix = cameraMatrix, _distCoeffs = distCoeffs; - CvMat _dpdrot = dpdrot, _dpdt = dpdt, _dpdf = dpdf, _dpdc = dpdc, _dpddist = dpddist; - - cvProjectPoints2( &_objectPoints, &_rvec, &_tvec, &_cameraMatrix, &_distCoeffs, - &_imagePoints, &_dpdrot, &_dpdt, &_dpdf, &_dpdc, &_dpddist, aspectRatio ); -} - -CV_ProjectPointsTest_C projectPointsTest_c; - -//----------------------------------------- CV_ProjectPointsTest_CPP -------------------------------- -class CV_ProjectPointsTest_CPP : public CV_ProjectPointsTest -{ -public: - CV_ProjectPointsTest_CPP() : - CV_ProjectPointsTest( "projectPoints-cpp", "cv::projectPoints" ) {} -protected: - virtual void project( const Mat& objectPoints, - const Mat& rvec, const Mat& tvec, - const Mat& cameraMatrix, - const Mat& distCoeffs, - vector& imagePoints, - Mat& dpdrot, Mat& dpdt, Mat& dpdf, - Mat& dpdc, Mat& dpddist, - double aspectRatio=0 ); -}; - -void CV_ProjectPointsTest_CPP::project( const Mat& objectPoints, const Mat& rvec, const Mat& tvec, - const Mat& cameraMatrix, const Mat& distCoeffs, vector& imagePoints, - Mat& dpdrot, Mat& dpdt, Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio) -{ - projectPoints( objectPoints, rvec, tvec, cameraMatrix, distCoeffs, imagePoints, - dpdrot, dpdt, dpdf, dpdc, dpddist, aspectRatio ); -} - -CV_ProjectPointsTest_CPP projectPointsTest_cpp; - -///////////////////////////////// Stereo Calibration ///////////////////////////////////// - -class CV_StereoCalibrationTest : public CvTest -{ -public: - CV_StereoCalibrationTest( const char* test_name, const char* test_funcs ); - ~CV_StereoCalibrationTest(); - void clear(); -protected: - bool checkPandROI( int test_case_idx, - const Mat& M, const Mat& D, const Mat& R, - const Mat& P, Size imgsize, Rect roi ); - - // covers of tested functions - virtual double calibrateStereoCamera( const vector >& objectPoints, - const vector >& imagePoints1, - const vector >& imagePoints2, - Mat& cameraMatrix1, Mat& distCoeffs1, - Mat& cameraMatrix2, Mat& distCoeffs2, - Size imageSize, Mat& R, Mat& T, - Mat& E, Mat& F, TermCriteria criteria, int flags ) = 0; - virtual void rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, - const Mat& cameraMatrix2, const Mat& distCoeffs2, - Size imageSize, const Mat& R, const Mat& T, - Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, - double alpha, Size newImageSize, - Rect* validPixROI1, Rect* validPixROI2, int flags ) = 0; - virtual bool rectifyUncalibrated( const Mat& points1, - const Mat& points2, const Mat& F, Size imgSize, - Mat& H1, Mat& H2, double threshold=5 ) = 0; - - void run(int); -}; - - -CV_StereoCalibrationTest::CV_StereoCalibrationTest( const char* test_name, const char* test_funcs ): -CvTest( test_name, test_funcs ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -CV_StereoCalibrationTest::~CV_StereoCalibrationTest() -{ - clear(); -} - -void CV_StereoCalibrationTest::clear() -{ - CvTest::clear(); -} - -bool CV_StereoCalibrationTest::checkPandROI( int test_case_idx, const Mat& M, const Mat& D, const Mat& R, - const Mat& P, Size imgsize, Rect roi ) -{ - const double eps = 0.05; - const int N = 21; - int x, y, k; - vector pts, upts; - - // step 1. check that all the original points belong to the destination image - for( y = 0; y < N; y++ ) - for( x = 0; x < N; x++ ) - pts.push_back(Point2f((float)x*imgsize.width/(N-1), (float)y*imgsize.height/(N-1))); - - undistortPoints(Mat(pts), upts, M, D, R, P ); - for( k = 0; k < N*N; k++ ) - if( upts[k].x < -imgsize.width*eps || upts[k].x > imgsize.width*(1+eps) || - upts[k].y < -imgsize.height*eps || upts[k].y > imgsize.height*(1+eps) ) - { - ts->printf(CvTS::LOG, "Test #%d. The point (%g, %g) was mapped to (%g, %g) which is out of image\n", - test_case_idx, pts[k].x, pts[k].y, upts[k].x, upts[k].y); - return false; - } - - // step 2. check that all the points inside ROI belong to the original source image - Mat temp(imgsize, CV_8U), utemp, map1, map2; - temp = Scalar::all(1); - initUndistortRectifyMap(M, D, R, P, imgsize, CV_16SC2, map1, map2); - remap(temp, utemp, map1, map2, INTER_LINEAR); - - if(roi.x < 0 || roi.y < 0 || roi.x + roi.width > imgsize.width || roi.y + roi.height > imgsize.height) - { - ts->printf(CvTS::LOG, "Test #%d. The ROI=(%d, %d, %d, %d) is outside of the imge rectangle\n", - test_case_idx, roi.x, roi.y, roi.width, roi.height); - return false; - } - double s = sum(utemp(roi))[0]; - if( s > roi.area() || roi.area() - s > roi.area()*(1-eps) ) - { - ts->printf(CvTS::LOG, "Test #%d. The ratio of black pixels inside the valid ROI (~%g%%) is too large\n", - test_case_idx, s*100./roi.area()); - return false; - } - - return true; -} - -void CV_StereoCalibrationTest::run( int ) -{ - const int ntests = 1; - const double maxReprojErr = 2; - const double maxScanlineDistErr_c = 3; - const double maxScanlineDistErr_uc = 4; - FILE* f = 0; - - for(int testcase = 1; testcase <= ntests; testcase++) - { - char filepath[1000]; - char buf[1000]; - sprintf( filepath, "%sstereo/case%d/stereo_calib.txt", ts->get_data_path(), testcase ); - f = fopen(filepath, "rt"); - Size patternSize; - vector imglist; - - if( !f || !fgets(buf, sizeof(buf)-3, f) || sscanf(buf, "%d%d", &patternSize.width, &patternSize.height) != 2 ) - { - ts->printf( CvTS::LOG, "The file %s can not be opened or has invalid content\n", filepath ); - ts->set_failed_test_info( f ? CvTS::FAIL_INVALID_TEST_DATA : CvTS::FAIL_MISSING_TEST_DATA ); - return; - } - - for(;;) - { - if( !fgets( buf, sizeof(buf)-3, f )) - break; - size_t len = strlen(buf); - while( len > 0 && isspace(buf[len-1])) - buf[--len] = '\0'; - if( buf[0] == '#') - continue; - sprintf(filepath, "%sstereo/case%d/%s", ts->get_data_path(), testcase, buf ); - imglist.push_back(string(filepath)); - } - fclose(f); - - if( imglist.size() == 0 || imglist.size() % 2 != 0 ) - { - ts->printf( CvTS::LOG, "The number of images is 0 or an odd number in the case #%d\n", testcase ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - int nframes = (int)(imglist.size()/2); - int npoints = patternSize.width*patternSize.height; - vector > objpt(nframes); - vector > imgpt1(nframes); - vector > imgpt2(nframes); - Size imgsize; - int total = 0; - - for( int i = 0; i < nframes; i++ ) - { - Mat left = imread(imglist[i*2]); - Mat right = imread(imglist[i*2+1]); - if(!left.data || !right.data) - { - ts->printf( CvTS::LOG, "Can not load images %s and %s, testcase %d\n", - imglist[i*2].c_str(), imglist[i*2+1].c_str(), testcase ); - ts->set_failed_test_info( CvTS::FAIL_MISSING_TEST_DATA ); - return; - } - imgsize = left.size(); - bool found1 = findChessboardCorners(left, patternSize, imgpt1[i]); - bool found2 = findChessboardCorners(right, patternSize, imgpt2[i]); - if(!found1 || !found2) - { - ts->printf( CvTS::LOG, "The function could not detect boards on the images %s and %s, testcase %d\n", - imglist[i*2].c_str(), imglist[i*2+1].c_str(), testcase ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - total += (int)imgpt1[i].size(); - for( int j = 0; j < npoints; j++ ) - objpt[i].push_back(Point3f((float)(j%patternSize.width), (float)(j/patternSize.width), 0.f)); - } - - // rectify (calibrated) - Mat M1 = Mat::eye(3,3,CV_64F), M2 = Mat::eye(3,3,CV_64F), D1(5,1,CV_64F), D2(5,1,CV_64F), R, T, E, F; - M1.at(0,2) = M2.at(0,2)=(imgsize.width-1)*0.5; - M1.at(1,2) = M2.at(1,2)=(imgsize.height-1)*0.5; - D1 = Scalar::all(0); - D2 = Scalar::all(0); - double err = calibrateStereoCamera(objpt, imgpt1, imgpt2, M1, D1, M2, D2, imgsize, R, T, E, F, - TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS, 30, 1e-6), - CV_CALIB_SAME_FOCAL_LENGTH - //+ CV_CALIB_FIX_ASPECT_RATIO - + CV_CALIB_FIX_PRINCIPAL_POINT - + CV_CALIB_ZERO_TANGENT_DIST - + CV_CALIB_FIX_K3 - + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5 //+ CV_CALIB_FIX_K6 - ); - err /= nframes*npoints; - if( err > maxReprojErr ) - { - ts->printf( CvTS::LOG, "The average reprojection error is too big (=%g), testcase %d\n", err, testcase); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - Mat R1, R2, P1, P2, Q; - Rect roi1, roi2; - rectify(M1, D1, M2, D2, imgsize, R, T, R1, R2, P1, P2, Q, 1, imgsize, &roi1, &roi2, 0); - Mat eye33 = Mat::eye(3,3,CV_64F); - Mat R1t = R1.t(), R2t = R2.t(); - - if( norm(R1t*R1 - eye33) > 0.01 || - norm(R2t*R2 - eye33) > 0.01 || - abs(determinant(F)) > 0.01) - { - ts->printf( CvTS::LOG, "The computed (by rectify) R1 and R2 are not orthogonal," - "or the computed (by calibrate) F is not singular, testcase %d\n", testcase); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - if(!checkPandROI(testcase, M1, D1, R1, P1, imgsize, roi1)) - { - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - - if(!checkPandROI(testcase, M2, D2, R2, P2, imgsize, roi2)) - { - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - - // rectifyUncalibrated - CV_Assert( imgpt1.size() == imgpt2.size() ); - Mat _imgpt1( total, 1, CV_32FC2 ), _imgpt2( total, 1, CV_32FC2 ); - vector >::const_iterator iit1 = imgpt1.begin(); - vector >::const_iterator iit2 = imgpt2.begin(); - for( int pi = 0; iit1 != imgpt1.end(); ++iit1, ++iit2 ) - { - vector::const_iterator pit1 = iit1->begin(); - vector::const_iterator pit2 = iit2->begin(); - CV_Assert( iit1->size() == iit2->size() ); - for( ; pit1 != iit1->end(); ++pit1, ++pit2, pi++ ) - { - _imgpt1.at(pi,0) = Point2f( pit1->x, pit1->y ); - _imgpt2.at(pi,0) = Point2f( pit2->x, pit2->y ); - } - } - - Mat _M1, _M2, _D1, _D2; - vector _R1, _R2, _T1, _T2; - calibrateCamera( objpt, imgpt1, imgsize, _M1, _D1, _R1, _T1, 0 ); - calibrateCamera( objpt, imgpt2, imgsize, _M2, _D2, _R2, _T1, 0 ); - undistortPoints( _imgpt1, _imgpt1, _M1, _D1, Mat(), _M1 ); - undistortPoints( _imgpt2, _imgpt2, _M2, _D2, Mat(), _M2 ); - - Mat matF, _H1, _H2; - matF = findFundamentalMat( _imgpt1, _imgpt2 ); - rectifyUncalibrated( _imgpt1, _imgpt2, matF, imgsize, _H1, _H2 ); - - Mat rectifPoints1, rectifPoints2; - perspectiveTransform( _imgpt1, rectifPoints1, _H1 ); - perspectiveTransform( _imgpt2, rectifPoints2, _H2 ); - - bool verticalStereo = abs(P2.at(0,3)) < abs(P2.at(1,3)); - double maxDiff_c = 0, maxDiff_uc = 0; - for( int i = 0, k = 0; i < nframes; i++ ) - { - vector temp[2]; - undistortPoints(Mat(imgpt1[i]), temp[0], M1, D1, R1, P1); - undistortPoints(Mat(imgpt2[i]), temp[1], M2, D2, R2, P2); - - for( int j = 0; j < npoints; j++, k++ ) - { - double diff_c = verticalStereo ? abs(temp[0][j].x - temp[1][j].x) : abs(temp[0][j].y - temp[1][j].y); - Point2f d = rectifPoints1.at(k,0) - rectifPoints2.at(k,0); - double diff_uc = verticalStereo ? abs(d.x) : abs(d.y); - maxDiff_c = max(maxDiff_c, diff_c); - maxDiff_uc = max(maxDiff_uc, diff_uc); - if( maxDiff_c > maxScanlineDistErr_c ) - { - ts->printf( CvTS::LOG, "The distance between %s coordinates is too big(=%g) (used calibrated stereo), testcase %d\n", - verticalStereo ? "x" : "y", diff_c, testcase); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - if( maxDiff_uc > maxScanlineDistErr_uc ) - { - ts->printf( CvTS::LOG, "The distance between %s coordinates is too big(=%g) (used uncalibrated stereo), testcase %d\n", - verticalStereo ? "x" : "y", diff_uc, testcase); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - } - } - - ts->printf( CvTS::LOG, "Testcase %d. Max distance (calibrated) =%g\n" - "Max distance (uncalibrated) =%g\n", testcase, maxDiff_c, maxDiff_uc ); - } -} - -//-------------------------------- CV_StereoCalibrationTest_C ------------------------------ - -class CV_StereoCalibrationTest_C : public CV_StereoCalibrationTest -{ -public: - CV_StereoCalibrationTest_C() : CV_StereoCalibrationTest( "calibrate-stereo-c", - "cvStereoCalibrate, cvStereoRectify, cvStereoRectifyUncalibrated" ) {} -protected: - virtual double calibrateStereoCamera( const vector >& objectPoints, - const vector >& imagePoints1, - const vector >& imagePoints2, - Mat& cameraMatrix1, Mat& distCoeffs1, - Mat& cameraMatrix2, Mat& distCoeffs2, - Size imageSize, Mat& R, Mat& T, - Mat& E, Mat& F, TermCriteria criteria, int flags ); - virtual void rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, - const Mat& cameraMatrix2, const Mat& distCoeffs2, - Size imageSize, const Mat& R, const Mat& T, - Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, - double alpha, Size newImageSize, - Rect* validPixROI1, Rect* validPixROI2, int flags ); - virtual bool rectifyUncalibrated( const Mat& points1, - const Mat& points2, const Mat& F, Size imgSize, - Mat& H1, Mat& H2, double threshold=5 ); -}; - -double CV_StereoCalibrationTest_C::calibrateStereoCamera( const vector >& objectPoints, - const vector >& imagePoints1, - const vector >& imagePoints2, - Mat& cameraMatrix1, Mat& distCoeffs1, - Mat& cameraMatrix2, Mat& distCoeffs2, - Size imageSize, Mat& R, Mat& T, - Mat& E, Mat& F, TermCriteria criteria, int flags ) -{ - cameraMatrix1.create( 3, 3, CV_64F ); - cameraMatrix2.create( 3, 3, CV_64F); - distCoeffs1.create( 1, 5, CV_64F); - distCoeffs2.create( 1, 5, CV_64F); - R.create(3, 3, CV_64F); - T.create(3, 1, CV_64F); - E.create(3, 3, CV_64F); - F.create(3, 3, CV_64F); - - int nimages = (int)objectPoints.size(), total = 0; - for( int i = 0; i < nimages; i++ ) - { - total += (int)objectPoints[i].size(); - } - - Mat npoints( 1, nimages, CV_32S ), - objPt( 1, total, DataType::type ), - imgPt( 1, total, DataType::type ), - imgPt2( 1, total, DataType::type ); - - Point2f* imgPtData2 = imgPt2.ptr(); - Point3f* objPtData = objPt.ptr(); - Point2f* imgPtData = imgPt.ptr(); - for( int i = 0, ni = 0, j = 0; i < nimages; i++, j += ni ) - { - ni = (int)objectPoints[i].size(); - ((int*)npoints.data)[i] = ni; - std::copy(objectPoints[i].begin(), objectPoints[i].end(), objPtData + j); - std::copy(imagePoints1[i].begin(), imagePoints1[i].end(), imgPtData + j); - std::copy(imagePoints2[i].begin(), imagePoints2[i].end(), imgPtData2 + j); - } - CvMat _objPt = objPt, _imgPt = imgPt, _imgPt2 = imgPt2, _npoints = npoints; - CvMat _cameraMatrix1 = cameraMatrix1, _distCoeffs1 = distCoeffs1; - CvMat _cameraMatrix2 = cameraMatrix2, _distCoeffs2 = distCoeffs2; - CvMat matR = R, matT = T, matE = E, matF = F; - - return cvStereoCalibrate(&_objPt, &_imgPt, &_imgPt2, &_npoints, &_cameraMatrix1, - &_distCoeffs1, &_cameraMatrix2, &_distCoeffs2, imageSize, - &matR, &matT, &matE, &matF, criteria, flags ); -} - -void CV_StereoCalibrationTest_C::rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, - const Mat& cameraMatrix2, const Mat& distCoeffs2, - Size imageSize, const Mat& R, const Mat& T, - Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, - double alpha, Size newImageSize, - Rect* validPixROI1, Rect* validPixROI2, int flags ) -{ - int rtype = CV_64F; - R1.create(3, 3, rtype); - R2.create(3, 3, rtype); - P1.create(3, 4, rtype); - P2.create(3, 4, rtype); - Q.create(4, 4, rtype); - CvMat _cameraMatrix1 = cameraMatrix1, _distCoeffs1 = distCoeffs1; - CvMat _cameraMatrix2 = cameraMatrix2, _distCoeffs2 = distCoeffs2; - CvMat matR = R, matT = T, _R1 = R1, _R2 = R2, _P1 = P1, _P2 = P2, matQ = Q; - cvStereoRectify( &_cameraMatrix1, &_cameraMatrix2, &_distCoeffs1, &_distCoeffs2, - imageSize, &matR, &matT, &_R1, &_R2, &_P1, &_P2, &matQ, flags, - alpha, newImageSize, (CvRect*)validPixROI1, (CvRect*)validPixROI2); -} - -bool CV_StereoCalibrationTest_C::rectifyUncalibrated( const Mat& points1, - const Mat& points2, const Mat& F, Size imgSize, Mat& H1, Mat& H2, double threshold ) -{ - H1.create(3, 3, CV_64F); - H2.create(3, 3, CV_64F); - CvMat _pt1 = points1, _pt2 = points2, matF, *pF=0, _H1 = H1, _H2 = H2; - if( F.size() == Size(3, 3) ) - pF = &(matF = F); - return cvStereoRectifyUncalibrated(&_pt1, &_pt2, pF, imgSize, &_H1, &_H2, threshold) > 0; -} - -CV_StereoCalibrationTest_C stereocalib_test_c; - -//-------------------------------- CV_StereoCalibrationTest_CPP ------------------------------ - -class CV_StereoCalibrationTest_CPP : public CV_StereoCalibrationTest -{ -public: - CV_StereoCalibrationTest_CPP() : CV_StereoCalibrationTest( "calibrate-stereo-cpp", - "stereoCalibrate, stereoRectify, stereoRectifyUncalibrated" ) {} -protected: - virtual double calibrateStereoCamera( const vector >& objectPoints, - const vector >& imagePoints1, - const vector >& imagePoints2, - Mat& cameraMatrix1, Mat& distCoeffs1, - Mat& cameraMatrix2, Mat& distCoeffs2, - Size imageSize, Mat& R, Mat& T, - Mat& E, Mat& F, TermCriteria criteria, int flags ); - virtual void rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, - const Mat& cameraMatrix2, const Mat& distCoeffs2, - Size imageSize, const Mat& R, const Mat& T, - Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, - double alpha, Size newImageSize, - Rect* validPixROI1, Rect* validPixROI2, int flags ); - virtual bool rectifyUncalibrated( const Mat& points1, - const Mat& points2, const Mat& F, Size imgSize, - Mat& H1, Mat& H2, double threshold=5 ); -}; - -double CV_StereoCalibrationTest_CPP::calibrateStereoCamera( const vector >& objectPoints, - const vector >& imagePoints1, - const vector >& imagePoints2, - Mat& cameraMatrix1, Mat& distCoeffs1, - Mat& cameraMatrix2, Mat& distCoeffs2, - Size imageSize, Mat& R, Mat& T, - Mat& E, Mat& F, TermCriteria criteria, int flags ) -{ - return stereoCalibrate( objectPoints, imagePoints1, imagePoints2, - cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, - imageSize, R, T, E, F, criteria, flags ); -} - -void CV_StereoCalibrationTest_CPP::rectify( const Mat& cameraMatrix1, const Mat& distCoeffs1, - const Mat& cameraMatrix2, const Mat& distCoeffs2, - Size imageSize, const Mat& R, const Mat& T, - Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, - double alpha, Size newImageSize, - Rect* validPixROI1, Rect* validPixROI2, int flags ) -{ - stereoRectify( cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, - imageSize, R, T, R1, R2, P1, P2, Q, alpha, newImageSize,validPixROI1, validPixROI2, flags ); -} - -bool CV_StereoCalibrationTest_CPP::rectifyUncalibrated( const Mat& points1, - const Mat& points2, const Mat& F, Size imgSize, Mat& H1, Mat& H2, double threshold ) -{ - return stereoRectifyUncalibrated( points1, points2, F, imgSize, H1, H2, threshold ); -} - -CV_StereoCalibrationTest_CPP stereocalib_test_cpp; - diff --git a/tests/cv/src/acameracalibration_artificial.cpp b/tests/cv/src/acameracalibration_artificial.cpp deleted file mode 100644 index 62b4b8e..0000000 --- a/tests/cv/src/acameracalibration_artificial.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include - -#include "cvchessboardgenerator.h" - -using namespace cv; -using namespace std; - -//template ostream& operator<<(ostream& out, const Mat_& mat) -//{ -// for(Mat_::const_iterator pos = mat.begin(), end = mat.end(); pos != end; ++pos) -// out << *pos << " "; -// return out; -//} -//ostream& operator<<(ostream& out, const Mat& mat) { return out << Mat_(mat); } - -Mat calcRvec(const vector& points, const Size& cornerSize) -{ - Point3f p00 = points[0]; - Point3f p10 = points[1]; - Point3f p01 = points[cornerSize.width]; - - Vec3d ex(p10.x - p00.x, p10.y - p00.y, p10.z - p00.z); - Vec3d ey(p01.x - p00.x, p01.y - p00.y, p01.z - p00.z); - Vec3d ez = ex.cross(ey); - - Mat rot(3, 3, CV_64F); - *rot.ptr(0) = ex; - *rot.ptr(1) = ey; - *rot.ptr(2) = ez * (1.0/norm(ez)); - - Mat res; - Rodrigues(rot.t(), res); - return res.reshape(1, 1); -} - -class CV_CalibrateCameraArtificialTest : public CvTest -{ -public: - CV_CalibrateCameraArtificialTest() : CvTest( "calibrate-camera-artificial", "cvCalibrateCamera2") - { - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - } - ~CV_CalibrateCameraArtificialTest() {} -protected: - int r; - - const static int JUST_FIND_CORNERS = 0; - const static int USE_CORNERS_SUBPIX = 1; - const static int USE_4QUAD_CORNERS = 2; - const static int ARTIFICIAL_CORNERS = 4; - - - bool checkErr(double a, double a0, double eps, double delta) - { - return fabs(a - a0) > eps * (fabs(a0) + delta); - } - - void compareCameraMatrs(const Mat_& camMat, const Mat& camMat_est) - { - if ( camMat_est.at(0, 1) != 0 || camMat_est.at(1, 0) != 0 || - camMat_est.at(2, 0) != 0 || camMat_est.at(2, 1) != 0 || - camMat_est.at(2, 2) != 1) - { - ts->printf( CvTS::LOG, "Bad shape of camera matrix returned \n"); - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - } - - double fx_e = camMat_est.at(0, 0), fy_e = camMat_est.at(1, 1); - double cx_e = camMat_est.at(0, 2), cy_e = camMat_est.at(1, 2); - - double fx = camMat(0, 0), fy = camMat(1, 1), cx = camMat(0, 2), cy = camMat(1, 2); - - const double eps = 1e-2; - const double dlt = 1e-5; - - bool fail = checkErr(fx_e, fx, eps, dlt) || checkErr(fy_e, fy, eps, dlt) || - checkErr(cx_e, cx, eps, dlt) || checkErr(cy_e, cy, eps, dlt); - - if (fail) - { - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - ts->printf( CvTS::LOG, "%d) Expected [Fx Fy Cx Cy] = [%.3f %.3f %.3f %.3f]\n", r, fx, fy, cx, cy); - ts->printf( CvTS::LOG, "%d) Estimated [Fx Fy Cx Cy] = [%.3f %.3f %.3f %.3f]\n", r, fx_e, fy_e, cx_e, cy_e); - } - - void compareDistCoeffs(const Mat_& distCoeffs, const Mat& distCoeffs_est) - { - const double *dt_e = distCoeffs_est.ptr(); - - double k1_e = dt_e[0], k2_e = dt_e[1], k3_e = dt_e[4]; - double p1_e = dt_e[2], p2_e = dt_e[3]; - - double k1 = distCoeffs(0, 0), k2 = distCoeffs(0, 1), k3 = distCoeffs(0, 4); - double p1 = distCoeffs(0, 2), p2 = distCoeffs(0, 3); - - const double eps = 5e-2; - const double dlt = 1e-3; - - const double eps_k3 = 5; - const double dlt_k3 = 1e-3; - - bool fail = checkErr(k1_e, k1, eps, dlt) || checkErr(k2_e, k2, eps, dlt) || checkErr(k3_e, k3, eps_k3, dlt_k3) || - checkErr(p1_e, p1, eps, dlt) || checkErr(p2_e, p2, eps, dlt); - - if (fail) - { - // commented according to vp123's recomendation. TODO - improve accuaracy - //ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); ss - } - ts->printf( CvTS::LOG, "%d) DistCoeff exp=(%.2f, %.2f, %.4f, %.4f %.2f)\n", r, k1, k2, p1, p2, k3); - ts->printf( CvTS::LOG, "%d) DistCoeff est=(%.2f, %.2f, %.4f, %.4f %.2f)\n", r, k1_e, k2_e, p1_e, p2_e, k3_e); - ts->printf( CvTS::LOG, "%d) AbsError = [%.5f %.5f %.5f %.5f %.5f]\n", r, fabs(k1-k1_e), fabs(k2-k2_e), fabs(p1-p1_e), fabs(p2-p2_e), fabs(k3-k3_e)); - } - - void compareShiftVecs(const vector& tvecs, const vector& tvecs_est) - { - const double eps = 1e-2; - const double dlt = 1e-4; - - int err_count = 0; - const int errMsgNum = 4; - for(size_t i = 0; i < tvecs.size(); ++i) - { - const Point3d& tvec = *tvecs[i].ptr(); - const Point3d& tvec_est = *tvecs_est[i].ptr(); - - if (norm(tvec_est - tvec) > eps* (norm(tvec) + dlt)) - { - if (err_count++ < errMsgNum) - { - if (err_count == errMsgNum) - ts->printf( CvTS::LOG, "%d) ...\n", r); - else - { - ts->printf( CvTS::LOG, "%d) Bad accuracy in returned tvecs. Index = %d\n", r, i); - ts->printf( CvTS::LOG, "%d) norm(tvec_est - tvec) = %f, norm(tvec_exp) = %f \n", r, norm(tvec_est - tvec), norm(tvec)); - } - } - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - } - } - - void compareRotationVecs(const vector& rvecs, const vector& rvecs_est) - { - const double eps = 2e-2; - const double dlt = 1e-4; - - Mat rmat, rmat_est; - int err_count = 0; - const int errMsgNum = 4; - for(size_t i = 0; i < rvecs.size(); ++i) - { - Rodrigues(rvecs[i], rmat); - Rodrigues(rvecs_est[i], rmat_est); - - if (norm(rmat_est, rmat) > eps* (norm(rmat) + dlt)) - { - if (err_count++ < errMsgNum) - { - if (err_count == errMsgNum) - ts->printf( CvTS::LOG, "%d) ...\n", r); - else - { - ts->printf( CvTS::LOG, "%d) Bad accuracy in returned rvecs (rotation matrs). Index = %d\n", r, i); - ts->printf( CvTS::LOG, "%d) norm(rot_mat_est - rot_mat_exp) = %f, norm(rot_mat_exp) = %f \n", r, norm(rmat_est, rmat), norm(rmat)); - - } - } - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - } - } - - double reprojectErrorWithoutIntrinsics(const vector& cb3d, const vector& rvecs_exp, const vector& tvecs_exp, - const vector& rvecs_est, const vector& tvecs_est) - { - const static Mat eye33 = Mat::eye(3, 3, CV_64F); - const static Mat zero15 = Mat::zeros(1, 5, CV_64F); - Mat chessboard3D(cb3d); - vector uv_exp, uv_est; - double res = 0; - - for(size_t i = 0; i < rvecs_exp.size(); ++i) - { - projectPoints(chessboard3D, rvecs_exp[i], tvecs_exp[i], eye33, zero15, uv_exp); - projectPoints(chessboard3D, rvecs_est[i], tvecs_est[i], eye33, zero15, uv_est); - for(size_t j = 0; j < cb3d.size(); ++j) - res += norm(uv_exp[i] - uv_est[i]); - } - return res; - } - - Size2f sqSile; - - vector chessboard3D; - vector boards, rvecs_exp, tvecs_exp, rvecs_spnp, tvecs_spnp; - vector< vector > objectPoints; - vector< vector > imagePoints_art; - vector< vector > imagePoints_findCb; - - - void prepareForTest(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, size_t brdsNum, const ChessBoardGenerator& cbg) - { - sqSile = Size2f(1.f, 1.f); - Size cornersSize = cbg.cornersSize(); - - chessboard3D.clear(); - for(int j = 0; j < cornersSize.height; ++j) - for(int i = 0; i < cornersSize.width; ++i) - chessboard3D.push_back(Point3f(sqSile.width * i, sqSile.height * j, 0)); - - boards.resize(brdsNum); - rvecs_exp.resize(brdsNum); - tvecs_exp.resize(brdsNum); - objectPoints.clear(); - objectPoints.resize(brdsNum, chessboard3D); - imagePoints_art.clear(); - imagePoints_findCb.clear(); - - vector corners_art, corners_fcb; - for(size_t i = 0; i < brdsNum; ++i) - { - for(;;) - { - boards[i] = cbg(bg, camMat, distCoeffs, sqSile, corners_art); - if(findChessboardCorners(boards[i], cornersSize, corners_fcb)) - break; - } - - //cv::namedWindow("CB"); imshow("CB", boards[i]); cv::waitKey(); - - imagePoints_art.push_back(corners_art); - imagePoints_findCb.push_back(corners_fcb); - - tvecs_exp[i].create(1, 3, CV_64F); - *tvecs_exp[i].ptr() = cbg.corners3d[0]; - rvecs_exp[i] = calcRvec(cbg.corners3d, cbg.cornersSize()); - } - - } - - void runTest(const Size& imgSize, const Mat_& camMat, const Mat_& distCoeffs, size_t brdsNum, const Size& cornersSize, int flag = 0) - { - const TermCriteria tc(TermCriteria::EPS|TermCriteria::MAX_ITER, 30, 0.1); - - vector< vector > imagePoints; - - switch(flag) - { - case JUST_FIND_CORNERS: imagePoints = imagePoints_findCb; break; - case ARTIFICIAL_CORNERS: imagePoints = imagePoints_art; break; - - case USE_CORNERS_SUBPIX: - for(size_t i = 0; i < brdsNum; ++i) - { - Mat gray; - cvtColor(boards[i], gray, CV_BGR2GRAY); - vector tmp = imagePoints_findCb[i]; - cornerSubPix(gray, tmp, Size(5, 5), Size(-1,-1), tc); - imagePoints.push_back(tmp); - } - break; - case USE_4QUAD_CORNERS: - for(size_t i = 0; i < brdsNum; ++i) - { - Mat gray; - cvtColor(boards[i], gray, CV_BGR2GRAY); - vector tmp = imagePoints_findCb[i]; - find4QuadCornerSubpix(gray, tmp, Size(5, 5)); - imagePoints.push_back(tmp); - } - break; - default: - throw std::exception(); - } - - Mat camMat_est = Mat::eye(3, 3, CV_64F), distCoeffs_est = Mat::zeros(1, 5, CV_64F); - vector rvecs_est, tvecs_est; - - int flags = /*CV_CALIB_FIX_K3|*/CV_CALIB_FIX_K4|CV_CALIB_FIX_K5|CV_CALIB_FIX_K6; //CALIB_FIX_K3; //CALIB_FIX_ASPECT_RATIO | | CALIB_ZERO_TANGENT_DIST; - double rep_error = calibrateCamera(objectPoints, imagePoints, imgSize, camMat_est, distCoeffs_est, rvecs_est, tvecs_est, flags); - rep_error /= brdsNum * cornersSize.area(); - - const double thres = 1; - if (rep_error > thres) - { - ts->printf( CvTS::LOG, "%d) Too big reproject error = %f\n", r, rep_error); - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - - compareCameraMatrs(camMat, camMat_est); - compareDistCoeffs(distCoeffs, distCoeffs_est); - compareShiftVecs(tvecs_exp, tvecs_est); - compareRotationVecs(rvecs_exp, rvecs_est); - - double rep_errorWOI = reprojectErrorWithoutIntrinsics(chessboard3D, rvecs_exp, tvecs_exp, rvecs_est, tvecs_est); - rep_errorWOI /= brdsNum * cornersSize.area(); - - const double thres2 = 0.01; - if (rep_errorWOI > thres2) - { - ts->printf( CvTS::LOG, "%d) Too big reproject error without intrinsics = %f\n", r, rep_errorWOI); - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - - ts->printf( CvTS::LOG, "%d) Testing solvePnP...\n", r); - rvecs_spnp.resize(brdsNum); - tvecs_spnp.resize(brdsNum); - for(size_t i = 0; i < brdsNum; ++i) - solvePnP(Mat(objectPoints[i]), Mat(imagePoints[i]), camMat, distCoeffs, rvecs_spnp[i], tvecs_spnp[i]); - - compareShiftVecs(tvecs_exp, tvecs_spnp); - compareRotationVecs(rvecs_exp, rvecs_spnp); - } - - void run(int) - { - - ts->set_failed_test_info(CvTS::OK); - RNG& rng = theRNG(); - - int progress = 0; - int repeat_num = 3; - for(r = 0; r < repeat_num; ++r) - { - const int brds_num = 20; - - Mat bg(Size(640, 480), CV_8UC3); - randu(bg, Scalar::all(32), Scalar::all(255)); - GaussianBlur(bg, bg, Size(5, 5), 2); - - double fx = 300 + (20 * (double)rng - 10); - double fy = 300 + (20 * (double)rng - 10); - - double cx = bg.cols/2 + (40 * (double)rng - 20); - double cy = bg.rows/2 + (40 * (double)rng - 20); - - Mat_ camMat(3, 3); - camMat << fx, 0., cx, 0, fy, cy, 0., 0., 1.; - - double k1 = 0.5 + (double)rng/5; - double k2 = (double)rng/5; - double k3 = (double)rng/5; - - double p1 = 0.001 + (double)rng/10; - double p2 = 0.001 + (double)rng/10; - - Mat_ distCoeffs(1, 5, 0.0); - distCoeffs << k1, k2, p1, p2, k3; - - ChessBoardGenerator cbg(Size(9, 8)); - cbg.min_cos = 0.9; - cbg.cov = 0.8; - - progress = update_progress(progress, r, repeat_num, 0); - ts->printf( CvTS::LOG, "\n"); - prepareForTest(bg, camMat, distCoeffs, brds_num, cbg); - - ts->printf( CvTS::LOG, "artificial corners\n"); - runTest(bg.size(), camMat, distCoeffs, brds_num, cbg.cornersSize(), ARTIFICIAL_CORNERS); - progress = update_progress(progress, r, repeat_num, 0); - - ts->printf( CvTS::LOG, "findChessboard corners\n"); - runTest(bg.size(), camMat, distCoeffs, brds_num, cbg.cornersSize(), JUST_FIND_CORNERS); - progress = update_progress(progress, r, repeat_num, 0); - - ts->printf( CvTS::LOG, "cornersSubPix corners\n"); - runTest(bg.size(), camMat, distCoeffs, brds_num, cbg.cornersSize(), USE_CORNERS_SUBPIX); - progress = update_progress(progress, r, repeat_num, 0); - - ts->printf( CvTS::LOG, "4quad corners\n"); - runTest(bg.size(), camMat, distCoeffs, brds_num, cbg.cornersSize(), USE_4QUAD_CORNERS); - progress = update_progress(progress, r, repeat_num, 0); - } - } -}; - -CV_CalibrateCameraArtificialTest calibrateCameraArtificialTest; diff --git a/tests/cv/src/acamshift.cpp b/tests/cv/src/acamshift.cpp deleted file mode 100644 index 63322b3..0000000 --- a/tests/cv/src/acamshift.cpp +++ /dev/null @@ -1,533 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -class CV_TrackBaseTest : public CvTest -{ -public: - CV_TrackBaseTest( const char* test_name, const char* test_funcs ); - virtual ~CV_TrackBaseTest(); - void clear(); - int write_default_params(CvFileStorage* fs); - -protected: - int read_params( CvFileStorage* fs ); - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void generate_object(); - - int min_log_size, max_log_size; - CvMat* img; - CvBox2D box0; - CvSize img_size; - CvTermCriteria criteria; - int img_type; -}; - - -CV_TrackBaseTest::CV_TrackBaseTest( const char* test_name, const char* test_funcs ): - CvTest( test_name, test_funcs ) -{ - img = 0; - test_case_count = 100; - min_log_size = 5; - max_log_size = 8; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -CV_TrackBaseTest::~CV_TrackBaseTest() -{ - clear(); -} - - -void CV_TrackBaseTest::clear() -{ - cvReleaseMat( &img ); - CvTest::clear(); -} - - -int CV_TrackBaseTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "min_log_size", min_log_size ); - write_param( fs, "max_log_size", max_log_size ); - } - return 0; -} - - -int CV_TrackBaseTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count ); - min_log_size = cvReadInt( find_param( fs, "min_log_size" ), min_log_size ); - max_log_size = cvReadInt( find_param( fs, "max_log_size" ), max_log_size ); - - min_log_size = cvTsClipInt( min_log_size, 1, 10 ); - max_log_size = cvTsClipInt( max_log_size, 1, 10 ); - if( min_log_size > max_log_size ) - { - int t; - CV_SWAP( min_log_size, max_log_size, t ); - } - - return 0; -} - - -void CV_TrackBaseTest::generate_object() -{ - int x, y; - double cx = box0.center.x; - double cy = box0.center.y; - double width = box0.size.width*0.5; - double height = box0.size.height*0.5; - double angle = box0.angle*CV_PI/180.; - double a = sin(angle), b = -cos(angle); - double inv_ww = 1./(width*width), inv_hh = 1./(height*height); - - img = cvCreateMat( img_size.height, img_size.width, img_type ); - cvZero( img ); - - // use the straightforward algorithm: for every pixel check if it is inside the ellipse - for( y = 0; y < img_size.height; y++ ) - { - uchar* ptr = img->data.ptr + img->step*y; - float* fl = (float*)ptr; - double x_ = (y - cy)*b, y_ = (y - cy)*a; - - for( x = 0; x < img_size.width; x++ ) - { - double x1 = (x - cx)*a - x_; - double y1 = (x - cx)*b + y_; - - if( x1*x1*inv_hh + y1*y1*inv_ww <= 1. ) - { - if( img_type == CV_8U ) - ptr[x] = (uchar)1; - else - fl[x] = (float)1.f; - } - } - } -} - - -int CV_TrackBaseTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - CvTest::prepare_test_case( test_case_idx ); - float m; - - clear(); - - box0.size.width = (float)exp((cvTsRandReal(rng) * (max_log_size - min_log_size) + min_log_size)*CV_LOG2); - box0.size.height = (float)exp((cvTsRandReal(rng) * (max_log_size - min_log_size) + min_log_size)*CV_LOG2); - box0.angle = (float)(cvTsRandReal(rng)*180.); - - if( box0.size.width > box0.size.height ) - { - float t; - CV_SWAP( box0.size.width, box0.size.height, t ); - } - - m = MAX( box0.size.width, box0.size.height ); - img_size.width = cvRound(cvTsRandReal(rng)*m*0.5 + m + 1); - img_size.height = cvRound(cvTsRandReal(rng)*m*0.5 + m + 1); - img_type = cvTsRandInt(rng) % 2 ? CV_32F : CV_8U; - img_type = CV_8U; - - box0.center.x = (float)(img_size.width*0.5 + (cvTsRandReal(rng)-0.5)*(img_size.width - m)); - box0.center.y = (float)(img_size.height*0.5 + (cvTsRandReal(rng)-0.5)*(img_size.height - m)); - - criteria = cvTermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 10, 0.1 ); - - generate_object(); - - return 1; -} - - -void CV_TrackBaseTest::run_func(void) -{ -} - - -int CV_TrackBaseTest::validate_test_results( int /*test_case_idx*/ ) -{ - return 0; -} - - -CV_TrackBaseTest track_basetest( "track", "" ); - - - -///////////////////////// CamShift ////////////////////////////// - -class CV_CamShiftTest : public CV_TrackBaseTest -{ -public: - CV_CamShiftTest(); - -protected: - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void generate_object(); - - CvBox2D box; - CvRect init_rect; - CvConnectedComp comp; - int area0; -}; - - -CV_CamShiftTest::CV_CamShiftTest() : - CV_TrackBaseTest( "track-camshift", "cvCamShift" ) -{ -} - - -int CV_CamShiftTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - double m; - int code = CV_TrackBaseTest::prepare_test_case( test_case_idx ); - int i, area; - - if( code <= 0 ) - return code; - - area0 = cvCountNonZero(img); - - for(i = 0; i < 100; i++) - { - CvMat temp; - - m = MAX(box0.size.width,box0.size.height)*0.8; - init_rect.x = cvFloor(box0.center.x - m*(0.45 + cvTsRandReal(rng)*0.2)); - init_rect.y = cvFloor(box0.center.y - m*(0.45 + cvTsRandReal(rng)*0.2)); - init_rect.width = cvCeil(box0.center.x + m*(0.45 + cvTsRandReal(rng)*0.2) - init_rect.x); - init_rect.height = cvCeil(box0.center.y + m*(0.45 + cvTsRandReal(rng)*0.2) - init_rect.y); - - if( init_rect.x < 0 || init_rect.y < 0 || - init_rect.x + init_rect.width >= img_size.width || - init_rect.y + init_rect.height >= img_size.height ) - continue; - - cvGetSubRect( img, &temp, init_rect ); - area = cvCountNonZero( &temp ); - - if( area >= 0.1*area0 ) - break; - } - - return i < 100 ? code : 0; -} - - -void CV_CamShiftTest::run_func(void) -{ - cvCamShift( img, init_rect, criteria, &comp, &box ); -} - - -int CV_CamShiftTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - - double m = MAX(box0.size.width, box0.size.height), delta; - double diff_angle; - - if( cvIsNaN(box.size.width) || cvIsInf(box.size.width) || box.size.width <= 0 || - cvIsNaN(box.size.height) || cvIsInf(box.size.height) || box.size.height <= 0 || - cvIsNaN(box.center.x) || cvIsInf(box.center.x) || - cvIsNaN(box.center.y) || cvIsInf(box.center.y) || - cvIsNaN(box.angle) || cvIsInf(box.angle) || box.angle < -180 || box.angle > 180 || - cvIsNaN(comp.area) || cvIsInf(comp.area) || comp.area <= 0 ) - { - ts->printf( CvTS::LOG, "Invalid CvBox2D or CvConnectedComp was returned by cvCamShift\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - box.angle = (float)(180 - box.angle); - - if( fabs(box.size.width - box0.size.width) > box0.size.width*0.2 || - fabs(box.size.height - box0.size.height) > box0.size.height*0.3 ) - { - ts->printf( CvTS::LOG, "Incorrect CvBox2D size (=%.1f x %.1f, should be %.1f x %.1f)\n", - box.size.width, box.size.height, box0.size.width, box0.size.height ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( fabs(box.center.x - box0.center.x) > m*0.1 || - fabs(box.center.y - box0.center.y) > m*0.1 ) - { - ts->printf( CvTS::LOG, "Incorrect CvBox2D position (=(%.1f, %.1f), should be (%.1f, %.1f))\n", - box.center.x, box.center.y, box0.center.x, box0.center.y ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( box.angle < 0 ) - box.angle += 180; - - diff_angle = fabs(box0.angle - box.angle); - diff_angle = MIN( diff_angle, fabs(box0.angle - box.angle + 180)); - - if( fabs(diff_angle) > 30 && box0.size.height > box0.size.width*1.2 ) - { - ts->printf( CvTS::LOG, "Incorrect CvBox2D angle (=%1.f, should be %1.f)\n", - box.angle, box0.angle ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - delta = m*0.7; - - if( comp.rect.x < box0.center.x - delta || - comp.rect.y < box0.center.y - delta || - comp.rect.x + comp.rect.width > box0.center.x + delta || - comp.rect.y + comp.rect.height > box0.center.y + delta ) - { - ts->printf( CvTS::LOG, - "Incorrect CvConnectedComp ((%d,%d,%d,%d) is not within (%.1f,%.1f,%.1f,%.1f))\n", - comp.rect.x, comp.rect.y, comp.rect.x + comp.rect.width, comp.rect.y + comp.rect.height, - box0.center.x - delta, box0.center.y - delta, box0.center.x + delta, box0.center.y + delta ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( fabs(comp.area - area0) > area0*0.15 ) - { - ts->printf( CvTS::LOG, - "Incorrect CvConnectedComp area (=%.1f, should be %d)\n", comp.area, area0 ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( code < 0 ) - { -#if defined _DEBUG && defined WIN32 - IplImage* dst = cvCreateImage( img_size, 8, 3 ); - cvNamedWindow( "test", 1 ); - cvCmpS( img, 0, img, CV_CMP_GT ); - cvCvtColor( img, dst, CV_GRAY2BGR ); - cvRectangle( dst, cvPoint(init_rect.x, init_rect.y), - cvPoint(init_rect.x + init_rect.width, init_rect.y + init_rect.height), - CV_RGB(255,0,0), 3, 8, 0 ); - cvEllipseBox( dst, box, CV_RGB(0,255,0), 3, 8, 0 ); - cvShowImage( "test", dst ); - cvReleaseImage( &dst ); - cvWaitKey(); -#endif - ts->set_failed_test_info( code ); - } - return code; -} - - -CV_CamShiftTest camshift_test; - - -///////////////////////// MeanShift ////////////////////////////// - -class CV_MeanShiftTest : public CV_TrackBaseTest -{ -public: - CV_MeanShiftTest(); - -protected: - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void generate_object(); - - CvRect init_rect; - CvConnectedComp comp; - int area0, area; -}; - - -CV_MeanShiftTest::CV_MeanShiftTest() : - CV_TrackBaseTest( "track-meanshift", "cvMeanShift" ) -{ -} - - -int CV_MeanShiftTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - double m; - int code = CV_TrackBaseTest::prepare_test_case( test_case_idx ); - int i; - - if( code <= 0 ) - return code; - - area0 = cvCountNonZero(img); - - for(i = 0; i < 100; i++) - { - CvMat temp; - - m = (box0.size.width + box0.size.height)*0.5; - init_rect.x = cvFloor(box0.center.x - m*(0.4 + cvTsRandReal(rng)*0.2)); - init_rect.y = cvFloor(box0.center.y - m*(0.4 + cvTsRandReal(rng)*0.2)); - init_rect.width = cvCeil(box0.center.x + m*(0.4 + cvTsRandReal(rng)*0.2) - init_rect.x); - init_rect.height = cvCeil(box0.center.y + m*(0.4 + cvTsRandReal(rng)*0.2) - init_rect.y); - - if( init_rect.x < 0 || init_rect.y < 0 || - init_rect.x + init_rect.width >= img_size.width || - init_rect.y + init_rect.height >= img_size.height ) - continue; - - cvGetSubRect( img, &temp, init_rect ); - area = cvCountNonZero( &temp ); - - if( area >= 0.5*area0 ) - break; - } - - return i < 100 ? code : 0; -} - - -void CV_MeanShiftTest::run_func(void) -{ - cvMeanShift( img, init_rect, criteria, &comp ); -} - - -int CV_MeanShiftTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - CvPoint2D32f c; - double m = MAX(box0.size.width, box0.size.height), delta; - - if( cvIsNaN(comp.area) || cvIsInf(comp.area) || comp.area <= 0 ) - { - ts->printf( CvTS::LOG, "Invalid CvConnectedComp was returned by cvMeanShift\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - c.x = (float)(comp.rect.x + comp.rect.width*0.5); - c.y = (float)(comp.rect.y + comp.rect.height*0.5); - - if( fabs(c.x - box0.center.x) > m*0.1 || - fabs(c.y - box0.center.y) > m*0.1 ) - { - ts->printf( CvTS::LOG, "Incorrect CvBox2D position (=(%.1f, %.1f), should be (%.1f, %.1f))\n", - c.x, c.y, box0.center.x, box0.center.y ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - delta = m*0.7; - - if( comp.rect.x < box0.center.x - delta || - comp.rect.y < box0.center.y - delta || - comp.rect.x + comp.rect.width > box0.center.x + delta || - comp.rect.y + comp.rect.height > box0.center.y + delta ) - { - ts->printf( CvTS::LOG, - "Incorrect CvConnectedComp ((%d,%d,%d,%d) is not within (%.1f,%.1f,%.1f,%.1f))\n", - comp.rect.x, comp.rect.y, comp.rect.x + comp.rect.width, comp.rect.y + comp.rect.height, - box0.center.x - delta, box0.center.y - delta, box0.center.x + delta, box0.center.y + delta ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( fabs((double)(comp.area - area0)) > fabs((double)(area - area0)) + area0*0.05 ) - { - ts->printf( CvTS::LOG, - "Incorrect CvConnectedComp area (=%.1f, should be %d)\n", comp.area, area0 ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( code < 0 ) - { -#if defined _DEBUG && defined WIN32 - IplImage* dst = cvCreateImage( img_size, 8, 3 ); - cvNamedWindow( "test", 1 ); - cvCmpS( img, 0, img, CV_CMP_GT ); - cvCvtColor( img, dst, CV_GRAY2BGR ); - cvRectangle( dst, cvPoint(init_rect.x, init_rect.y), - cvPoint(init_rect.x + init_rect.width, init_rect.y + init_rect.height), - CV_RGB(255,0,0), 3, 8, 0 ); - cvRectangle( dst, cvPoint(comp.rect.x, comp.rect.y), - cvPoint(comp.rect.x + comp.rect.width, comp.rect.y + comp.rect.height), - CV_RGB(0,255,0), 3, 8, 0 ); - cvShowImage( "test", dst ); - cvReleaseImage( &dst ); - cvWaitKey(); -#endif - ts->set_failed_test_info( code ); - } - return code; -} - - -CV_MeanShiftTest meanshift_test; - -/* End of file. */ diff --git a/tests/cv/src/acanny.cpp b/tests/cv/src/acanny.cpp deleted file mode 100644 index 157ba71..0000000 --- a/tests/cv/src/acanny.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_CannyTest : public CvArrTest -{ -public: - CV_CannyTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int ); - int validate_test_results( int /*test_case_idx*/ ); - - int aperture_size, use_true_gradient; - double threshold1, threshold2; - bool test_cpp; -}; - - -CV_CannyTest::CV_CannyTest() - : CvArrTest( "canny", "cvCanny, cvSobel", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - element_wise_relative_error = true; - aperture_size = use_true_gradient = 0; - threshold1 = threshold2 = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; - test_cpp = false; -} - - -void CV_CannyTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - double thresh_range; - - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8U; - - aperture_size = cvTsRandInt(rng) % 2 ? 5 : 3; - thresh_range = aperture_size == 3 ? 300 : 1000; - - threshold1 = cvTsRandReal(rng)*thresh_range; - threshold2 = cvTsRandReal(rng)*thresh_range*0.3; - - if( cvTsRandInt(rng) % 2 ) - CV_SWAP( threshold1, threshold2, thresh_range ); - - use_true_gradient = cvTsRandInt(rng) % 2; - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -int CV_CannyTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - CvMat* src = &test_mat[INPUT][0]; - cvSmooth( src, src, CV_GAUSSIAN, 11, 11, 5, 5 ); - } - - return code; -} - - -double CV_CannyTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CV_CannyTest::run_func() -{ - if(!test_cpp) - cvCanny( test_array[INPUT][0], test_array[OUTPUT][0], threshold1, threshold2, - aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0)); - else - { - cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::Canny(cv::cvarrToMat(test_array[INPUT][0]), _out, threshold1, threshold2, - aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0)); - } -} - - -static void -icvTsCannyFollow( int x, int y, float lowThreshold, const CvMat* mag, CvMat* dst ) -{ - static const int ofs[][2] = {{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1}}; - int i; - - dst->data.ptr[dst->step*y + x] = (uchar)255; - - for( i = 0; i < 8; i++ ) - { - int x1 = x + ofs[i][0]; - int y1 = y + ofs[i][1]; - if( (unsigned)x1 < (unsigned)mag->cols && - (unsigned)y1 < (unsigned)mag->rows && - mag->data.fl[y1*mag->cols+x1] > lowThreshold && - !dst->data.ptr[dst->step*y1+x1] ) - icvTsCannyFollow( x1, y1, lowThreshold, mag, dst ); - } -} - - -static void -icvTsCanny( const CvMat* src, CvMat* dst, - double threshold1, double threshold2, - int aperture_size, int use_true_gradient ) -{ - int m = aperture_size; - CvMat* _src = cvCreateMat( src->rows + m - 1, src->cols + m - 1, CV_16S ); - CvMat* dx = cvCreateMat( src->rows, src->cols, CV_16S ); - CvMat* dy = cvCreateMat( src->rows, src->cols, CV_16S ); - CvMat* kernel = cvCreateMat( m, m, CV_32F ); - CvPoint anchor = {m/2, m/2}; - CvMat* mag = cvCreateMat( src->rows, src->cols, CV_32F ); - const double tan_pi_8 = tan(CV_PI/8.); - const double tan_3pi_8 = tan(CV_PI*3/8); - float lowThreshold = (float)MIN(threshold1, threshold2); - float highThreshold = (float)MAX(threshold1, threshold2); - - int x, y, width = src->cols, height = src->rows; - - cvTsConvert( src, dx ); - cvTsPrepareToFilter( dx, _src, anchor, CV_TS_BORDER_REPLICATE ); - cvTsCalcSobelKernel2D( 1, 0, m, 0, kernel ); - cvTsConvolve2D( _src, dx, kernel, anchor ); - cvTsCalcSobelKernel2D( 0, 1, m, 0, kernel ); - cvTsConvolve2D( _src, dy, kernel, anchor ); - - /* estimate magnitude and angle */ - for( y = 0; y < height; y++ ) - { - const short* _dx = (short*)(dx->data.ptr + dx->step*y); - const short* _dy = (short*)(dy->data.ptr + dy->step*y); - float* _mag = (float*)(mag->data.ptr + mag->step*y); - - for( x = 0; x < width; x++ ) - { - float mval = use_true_gradient ? - (float)sqrt((double)(_dx[x]*_dx[x] + _dy[x]*_dy[x])) : - (float)(abs(_dx[x]) + abs(_dy[x])); - _mag[x] = mval; - } - } - - /* nonmaxima suppression */ - for( y = 0; y < height; y++ ) - { - const short* _dx = (short*)(dx->data.ptr + dx->step*y); - const short* _dy = (short*)(dy->data.ptr + dy->step*y); - float* _mag = (float*)(mag->data.ptr + mag->step*y); - - for( x = 0; x < width; x++ ) - { - int y1 = 0, y2 = 0, x1 = 0, x2 = 0; - double tg; - float a = _mag[x], b = 0, c = 0; - - if( a <= lowThreshold ) - continue; - - if( _dx[x] ) - tg = (double)_dy[x]/_dx[x]; - else - tg = DBL_MAX*CV_SIGN(_dy[x]); - - if( fabs(tg) < tan_pi_8 ) - { - y1 = y2 = y; x1 = x + 1; x2 = x - 1; - } - else if( tan_pi_8 <= tg && tg <= tan_3pi_8 ) - { - y1 = y + 1; y2 = y - 1; x1 = x + 1; x2 = x - 1; - } - else if( -tan_3pi_8 <= tg && tg <= -tan_pi_8 ) - { - y1 = y - 1; y2 = y + 1; x1 = x + 1; x2 = x - 1; - } - else - { - assert( fabs(tg) > tan_3pi_8 ); - x1 = x2 = x; y1 = y + 1; y2 = y - 1; - } - - if( (unsigned)y1 < (unsigned)height && (unsigned)x1 < (unsigned)width ) - b = (float)fabs((double)mag->data.fl[y1*width+x1]); - - if( (unsigned)y2 < (unsigned)height && (unsigned)x2 < (unsigned)width ) - c = (float)fabs((double)mag->data.fl[y2*width+x2]); - - if( (a > b || (a == b && ((x1 == x+1 && y1 == y) || (x1 == x && y1 == y+1)))) && a > c ) - ; - else - _mag[x] = -a; - } - } - - cvTsZero( dst ); - - /* hysteresis threshold */ - for( y = 0; y < height; y++ ) - { - const float* _mag = (float*)(mag->data.ptr + mag->step*y); - uchar* _dst = dst->data.ptr + dst->step*y; - - for( x = 0; x < width; x++ ) - if( _mag[x] > highThreshold && !_dst[x] ) - icvTsCannyFollow( x, y, lowThreshold, mag, dst ); - } - - cvReleaseMat( &_src ); - cvReleaseMat( &dx ); - cvReleaseMat( &dy ); - cvReleaseMat( &kernel ); - cvReleaseMat( &mag ); -} - - -void CV_CannyTest::prepare_to_validation( int ) -{ - icvTsCanny( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - threshold1, threshold2, aperture_size, use_true_gradient ); - - /*cv::Mat output(&test_mat[OUTPUT][0]); - cv::Mat ref_output(&test_mat[REF_OUTPUT][0]); - - cv::absdiff(output, ref_output, output); - cv::namedWindow("ref test", 0); - cv::imshow("ref test", ref_output); - cv::namedWindow("test", 0); - cv::imshow("test", output); - cv::waitKey();*/ -} - - -int CV_CannyTest::validate_test_results( int test_case_idx ) -{ - int code = CvTS::OK, nz0; - prepare_to_validation(test_case_idx); - - double err = cvNorm(&test_mat[OUTPUT][0], &test_mat[REF_OUTPUT][0], CV_L1); - if( err == 0 ) - goto _exit_; - - if( err != cvRound(err) || cvRound(err)%255 != 0 ) - { - ts->printf( CvTS::LOG, "Some of the pixels, produced by Canny, are not 0's or 255's; the difference is %g\n", err ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - nz0 = cvCountNonZero(&test_mat[REF_OUTPUT][0]); - err = (err/255/MAX(nz0,100))*100; - if( err > 1 ) - { - ts->printf( CvTS::LOG, "Too high percentage of non-matching edge pixels = %g%%\n", err); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_CannyTest canny_test; - -/* End of file. */ diff --git a/tests/cv/src/acascadeandhog.cpp b/tests/cv/src/acascadeandhog.cpp deleted file mode 100644 index 5b3e8e5..0000000 --- a/tests/cv/src/acascadeandhog.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -using namespace cv; -using namespace std; - -//#define GET_STAT - -#define DIST_E "distE" -#define S_E "sE" -#define NO_PAIR_E "noPairE" -//#define TOTAL_NO_PAIR_E "totalNoPairE" - -#define DETECTOR_NAMES "detector_names" -#define DETECTORS "detectors" -#define IMAGE_FILENAMES "image_filenames" -#define VALIDATION "validation" -#define FILENAME "fn" - -#define C_SCALE_CASCADE "scale_cascade" - -class CV_DetectorTest : public CvTest -{ -public: - CV_DetectorTest( const char* test_name ); - virtual int init( CvTS* system ); -protected: - virtual int prepareData( FileStorage& fs ); - virtual void run( int startFrom ); - virtual string& getValidationFilename(); - - virtual void readDetector( const FileNode& fn ) = 0; - virtual void writeDetector( FileStorage& fs, int di ) = 0; - int runTestCase( int detectorIdx, vector >& objects ); - virtual int detectMultiScale( int di, const Mat& img, vector& objects ) = 0; - int validate( int detectorIdx, vector >& objects ); - - struct - { - float dist; - float s; - float noPair; - //float totalNoPair; - } eps; - vector detectorNames; - vector detectorFilenames; - vector imageFilenames; - vector images; - string validationFilename; - FileStorage validationFS; -}; - -CV_DetectorTest::CV_DetectorTest( const char* test_name ) : CvTest( test_name, "detectMultiScale" ) -{ -} - -int CV_DetectorTest::init(CvTS *system) -{ - clear(); - ts = system; - string dataPath = ts->get_data_path(); - validationFS.open( dataPath + getValidationFilename(), FileStorage::READ ); - return prepareData( validationFS ); -} - -string& CV_DetectorTest::getValidationFilename() -{ - return validationFilename; -} - -int CV_DetectorTest::prepareData( FileStorage& _fs ) -{ - if( !_fs.isOpened() ) - test_case_count = -1; - else - { - FileNode fn = _fs.getFirstTopLevelNode(); - - fn[DIST_E] >> eps.dist; - fn[S_E] >> eps.s; - fn[NO_PAIR_E] >> eps.noPair; -// fn[TOTAL_NO_PAIR_E] >> eps.totalNoPair; - - // read detectors - if( fn[DETECTOR_NAMES].node->data.seq != 0 ) - { - FileNodeIterator it = fn[DETECTOR_NAMES].begin(); - for( ; it != fn[DETECTOR_NAMES].end(); ) - { - string name; - it >> name; - detectorNames.push_back(name); - readDetector(fn[DETECTORS][name]); - } - } - test_case_count = (int)detectorNames.size(); - - // read images filenames and images - string dataPath = ts->get_data_path(); - if( fn[IMAGE_FILENAMES].node->data.seq != 0 ) - { - for( FileNodeIterator it = fn[IMAGE_FILENAMES].begin(); it != fn[IMAGE_FILENAMES].end(); ) - { - string filename; - it >> filename; - imageFilenames.push_back(filename); - Mat img = imread( dataPath+filename, 1 ); - images.push_back( img ); - } - } - } - return CvTS::OK; -} - -void CV_DetectorTest::run( int start_from ) -{ - int code = CvTS::OK; - start_from = 0; - -#ifdef GET_STAT - validationFS.release(); - string filename = ts->get_data_path(); - filename += getValidationFilename(); - validationFS.open( filename, FileStorage::WRITE ); - validationFS << FileStorage::getDefaultObjectName(validationFilename) << "{"; - - validationFS << DIST_E << eps.dist; - validationFS << S_E << eps.s; - validationFS << NO_PAIR_E << eps.noPair; -// validationFS << TOTAL_NO_PAIR_E << eps.totalNoPair; - - // write detector names - validationFS << DETECTOR_NAMES << "["; - vector::const_iterator nit = detectorNames.begin(); - for( ; nit != detectorNames.end(); ++nit ) - { - validationFS << *nit; - } - validationFS << "]"; // DETECTOR_NAMES - - // write detectors - validationFS << DETECTORS << "{"; - assert( detectorNames.size() == detectorFilenames.size() ); - nit = detectorNames.begin(); - for( int di = 0; di < detectorNames.size(), nit != detectorNames.end(); ++nit, di++ ) - { - validationFS << *nit << "{"; - writeDetector( validationFS, di ); - validationFS << "}"; - } - validationFS << "}"; - - // write image filenames - validationFS << IMAGE_FILENAMES << "["; - vector::const_iterator it = imageFilenames.begin(); - for( int ii = 0; it != imageFilenames.end(); ++it, ii++ ) - { - char buf[10]; - sprintf( buf, "%s%d", "img_", ii ); - cvWriteComment( validationFS.fs, buf, 0 ); - validationFS << *it; - } - validationFS << "]"; // IMAGE_FILENAMES - - validationFS << VALIDATION << "{"; -#endif - - int progress = 0; - for( int di = 0; di < test_case_count; di++ ) - { - progress = update_progress( progress, di, test_case_count, 0 ); -#ifdef GET_STAT - validationFS << detectorNames[di] << "{"; -#endif - vector > objects; - int temp_code = runTestCase( di, objects ); -#ifndef GET_STAT - if (temp_code == CvTS::OK) - temp_code = validate( di, objects ); -#endif - if (temp_code != CvTS::OK) - code = temp_code; -#ifdef GET_STAT - validationFS << "}"; // detectorNames[di] -#endif - } - -#ifdef GET_STAT - validationFS << "}"; // VALIDATION - validationFS << "}"; // getDefaultObjectName -#endif - if ( test_case_count <= 0 || imageFilenames.size() <= 0 ) - { - ts->printf( CvTS::LOG, "validation file is not determined or not correct" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - } - ts->set_failed_test_info( code ); -} - -int CV_DetectorTest::runTestCase( int detectorIdx, vector >& objects ) -{ - string dataPath = ts->get_data_path(), detectorFilename; - if( !detectorFilenames[detectorIdx].empty() ) - detectorFilename = dataPath + detectorFilenames[detectorIdx]; - - for( int ii = 0; ii < (int)imageFilenames.size(); ++ii ) - { - vector imgObjects; - Mat image = images[ii]; - if( image.empty() ) - { - char msg[30]; - sprintf( msg, "%s %d %s", "image ", ii, " can not be read" ); - ts->printf( CvTS::LOG, msg ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - int code = detectMultiScale( detectorIdx, image, imgObjects ); - if( code != CvTS::OK ) - return code; - - objects.push_back( imgObjects ); - -#ifdef GET_STAT - char buf[10]; - sprintf( buf, "%s%d", "img_", ii ); - string imageIdxStr = buf; - validationFS << imageIdxStr << "[:"; - for( vector::const_iterator it = imgObjects.begin(); - it != imgObjects.end(); ++it ) - { - validationFS << it->x << it->y << it->width << it->height; - } - validationFS << "]"; // imageIdxStr -#endif - } - return CvTS::OK; -} - - -bool isZero( uchar i ) {return i == 0;} - -int CV_DetectorTest::validate( int detectorIdx, vector >& objects ) -{ - assert( imageFilenames.size() == objects.size() ); - int imageIdx = 0; - int totalNoPair = 0, totalValRectCount = 0; - - for( vector >::const_iterator it = objects.begin(); - it != objects.end(); ++it, imageIdx++ ) // for image - { - Size imgSize = images[imageIdx].size(); - float dist = min(imgSize.height, imgSize.width) * eps.dist; - float wDiff = imgSize.width * eps.s; - float hDiff = imgSize.height * eps.s; - - int noPair = 0; - - // read validation rectangles - char buf[10]; - sprintf( buf, "%s%d", "img_", imageIdx ); - string imageIdxStr = buf; - FileNode node = validationFS.getFirstTopLevelNode()[VALIDATION][detectorNames[detectorIdx]][imageIdxStr]; - vector valRects; - if( node.node->data.seq != 0 ) - { - for( FileNodeIterator it = node.begin(); it != node.end(); ) - { - Rect r; - it >> r.x >> r.y >> r.width >> r.height; - valRects.push_back(r); - } - } - totalValRectCount += (int)valRects.size(); - - // compare rectangles - vector map(valRects.size(), 0); - for( vector::const_iterator cr = it->begin(); - cr != it->end(); ++cr ) - { - // find nearest rectangle - Point2f cp1 = Point2f( cr->x + (float)cr->width/2.0f, cr->y + (float)cr->height/2.0f ); - int minIdx = -1, vi = 0; - float minDist = (float)norm( Point(imgSize.width, imgSize.height) ); - for( vector::const_iterator vr = valRects.begin(); - vr != valRects.end(); ++vr, vi++ ) - { - Point2f cp2 = Point2f( vr->x + (float)vr->width/2.0f, vr->y + (float)vr->height/2.0f ); - float curDist = (float)norm(cp1-cp2); - if( curDist < minDist ) - { - minIdx = vi; - minDist = curDist; - } - } - if( minIdx == -1 ) - { - noPair++; - } - else - { - Rect vr = valRects[minIdx]; - if( map[minIdx] != 0 || (minDist > dist) || (abs(cr->width - vr.width) > wDiff) || - (abs(cr->height - vr.height) > hDiff) ) - noPair++; - else - map[minIdx] = 1; - } - } - noPair += (int)count_if( map.begin(), map.end(), isZero ); - totalNoPair += noPair; - if( noPair > cvRound(valRects.size()*eps.noPair)+1 ) - break; - } - if( imageIdx < (int)imageFilenames.size() ) - { - char msg[500]; - sprintf( msg, "detector %s has overrated count of rectangles without pair on %s-image\n", - detectorNames[detectorIdx].c_str(), imageFilenames[imageIdx].c_str() ); - ts->printf( CvTS::LOG, msg ); - return CvTS::FAIL_BAD_ACCURACY; - } - if ( totalNoPair > cvRound(totalValRectCount*eps./*total*/noPair)+1 ) - { - ts->printf( CvTS::LOG, "overrated count of rectangles without pair on all images set" ); - return CvTS::FAIL_BAD_ACCURACY; - } - - return CvTS::OK; -} - -//----------------------------------------------- CascadeDetectorTest ----------------------------------- -class CV_CascadeDetectorTest : public CV_DetectorTest -{ -public: - CV_CascadeDetectorTest( const char* test_name ); -protected: - virtual void readDetector( const FileNode& fn ); - virtual void writeDetector( FileStorage& fs, int di ); - virtual int detectMultiScale( int di, const Mat& img, vector& objects ); - vector flags; -}; - -CV_CascadeDetectorTest::CV_CascadeDetectorTest(const char *test_name) - : CV_DetectorTest( test_name ) -{ - validationFilename = "cascadeandhog/cascade.xml"; -} - -void CV_CascadeDetectorTest::readDetector( const FileNode& fn ) -{ - string filename; - int flag; - fn[FILENAME] >> filename; - detectorFilenames.push_back(filename); - fn[C_SCALE_CASCADE] >> flag; - if( flag ) - flags.push_back( 0 ); - else - flags.push_back( CV_HAAR_SCALE_IMAGE ); -} - -void CV_CascadeDetectorTest::writeDetector( FileStorage& fs, int di ) -{ - int sc = flags[di] & CV_HAAR_SCALE_IMAGE ? 0 : 1; - fs << FILENAME << detectorFilenames[di]; - fs << C_SCALE_CASCADE << sc; -} - -int CV_CascadeDetectorTest::detectMultiScale( int di, const Mat& img, - vector& objects) -{ - string dataPath = ts->get_data_path(), filename; - filename = dataPath + detectorFilenames[di]; - CascadeClassifier cascade( filename ); - if( cascade.empty() ) - { - ts->printf( CvTS::LOG, "cascade %s can not be opened"); - return CvTS::FAIL_INVALID_TEST_DATA; - } - Mat grayImg; - cvtColor( img, grayImg, CV_BGR2GRAY ); - equalizeHist( grayImg, grayImg ); - cascade.detectMultiScale( grayImg, objects, 1.1, 3, flags[di] ); - return CvTS::OK; -} - -//----------------------------------------------- HOGDetectorTest ----------------------------------- -class CV_HOGDetectorTest : public CV_DetectorTest -{ -public: - CV_HOGDetectorTest( const char* test_name ); -protected: - virtual void readDetector( const FileNode& fn ); - virtual void writeDetector( FileStorage& fs, int di ); - virtual int detectMultiScale( int di, const Mat& img, vector& objects ); -}; - -CV_HOGDetectorTest::CV_HOGDetectorTest(const char *test_name) -: CV_DetectorTest( test_name ) -{ - validationFilename = "cascadeandhog/hog.xml"; -} - -void CV_HOGDetectorTest::readDetector( const FileNode& fn ) -{ - string filename; - if( fn[FILENAME].node->data.seq != 0 ) - fn[FILENAME] >> filename; - detectorFilenames.push_back( filename); -} - -void CV_HOGDetectorTest::writeDetector( FileStorage& fs, int di ) -{ - fs << FILENAME << detectorFilenames[di]; -} - -int CV_HOGDetectorTest::detectMultiScale( int di, const Mat& img, - vector& objects) -{ - HOGDescriptor hog; - if( detectorFilenames[di].empty() ) - hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector()); - else - assert(0); - hog.detectMultiScale(img, objects); - return CvTS::OK; -} - -CV_CascadeDetectorTest cascadeTest("cascade-detector"); -CV_HOGDetectorTest hogTest("hog-detector"); diff --git a/tests/cv/src/achesscorners.cpp b/tests/cv/src/achesscorners.cpp deleted file mode 100644 index f9b6233..0000000 --- a/tests/cv/src/achesscorners.cpp +++ /dev/null @@ -1,455 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include "cvchessboardgenerator.h" - -#include -#include - -using namespace std; -using namespace cv; - -#define _L2_ERR - -void show_points( const Mat& gray, const Mat& u, const vector& v, Size pattern_size, bool was_found ) -{ - Mat rgb( gray.size(), CV_8U); - merge(vector(3, gray), rgb); - - for(size_t i = 0; i < v.size(); i++ ) - circle( rgb, v[i], 3, CV_RGB(255, 0, 0), CV_FILLED); - - if( !u.empty() ) - { - const Point2f* u_data = u.ptr(); - size_t count = u.cols * u.rows; - for(size_t i = 0; i < count; i++ ) - circle( rgb, u_data[i], 3, CV_RGB(0, 255, 0), CV_FILLED); - } - if (!v.empty()) - { - Mat corners((int)v.size(), 1, CV_32FC2, (void*)&v[0]); - drawChessboardCorners( rgb, pattern_size, corners, was_found ); - } - //namedWindow( "test", 0 ); imshow( "test", rgb ); waitKey(0); -} - - -enum Pattern { CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID }; - -class CV_ChessboardDetectorTest : public CvTest -{ -public: - CV_ChessboardDetectorTest( Pattern pattern, const char* testName, const char* funcName ); -protected: - void run(int); - void run_batch(const string& filename); - bool checkByGenerator(); - - Pattern pattern; -}; - -CV_ChessboardDetectorTest::CV_ChessboardDetectorTest( Pattern _pattern, const char* testName, const char* funcName ): - CvTest( testName, funcName ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - pattern = _pattern; -} - -double calcError(const vector& v, const Mat& u) -{ - int count_exp = u.cols * u.rows; - const Point2f* u_data = u.ptr(); - - double err = numeric_limits::max(); - for( int k = 0; k < 2; ++k ) - { - double err1 = 0; - for( int j = 0; j < count_exp; ++j ) - { - int j1 = k == 0 ? j : count_exp - j - 1; - double dx = fabs( v[j].x - u_data[j1].x ); - double dy = fabs( v[j].y - u_data[j1].y ); - -#if defined(_L2_ERR) - err1 += dx*dx + dy*dy; -#else - dx = MAX( dx, dy ); - if( dx > err1 ) - err1 = dx; -#endif //_L2_ERR - //printf("dx = %f\n", dx); - } - //printf("\n"); - err = min(err, err1); - } - -#if defined(_L2_ERR) - err = sqrt(err/count_exp); -#endif //_L2_ERR - - return err; -} - -const double rough_success_error_level = 2.5; -const double precise_success_error_level = 2; - - -/* ///////////////////// chess_corner_test ///////////////////////// */ -void CV_ChessboardDetectorTest::run( int /*start_from */) -{ - /*if (!checkByGenerator()) - return;*/ - switch( pattern ) - { - case CHESSBOARD: - checkByGenerator(); - run_batch("chessboard_list.dat"); - run_batch("chessboard_list_subpixel.dat"); - break; - case CIRCLES_GRID: - run_batch("circles_list.dat"); - break; - case ASYMMETRIC_CIRCLES_GRID: - run_batch("acircles_list.dat"); - break; - } -} - -void CV_ChessboardDetectorTest::run_batch( const string& filename ) -{ - CvTS& ts = *this->ts; - ts.set_failed_test_info( CvTS::OK ); - - ts.printf(CvTS::LOG, "\nRunning batch %s\n", filename.c_str()); -//#define WRITE_POINTS 1 -#ifndef WRITE_POINTS - double max_rough_error = 0, max_precise_error = 0; -#endif - string folder; - switch( pattern ) - { - case CHESSBOARD: - folder = string(ts.get_data_path()) + "cameracalibration/"; - break; - case CIRCLES_GRID: - folder = string(ts.get_data_path()) + "cameracalibration/circles/"; - break; - case ASYMMETRIC_CIRCLES_GRID: - folder = string(ts.get_data_path()) + "cameracalibration/asymmetric_circles/"; - break; - } - - FileStorage fs( folder + filename, FileStorage::READ ); - FileNode board_list = fs["boards"]; - - if( !fs.isOpened() || board_list.empty() || !board_list.isSeq() || board_list.size() % 2 != 0 ) - { - ts.printf( CvTS::LOG, "%s can not be readed or is not valid\n", (folder + filename).c_str() ); - ts.printf( CvTS::LOG, "fs.isOpened=%d, board_list.empty=%d, board_list.isSeq=%d,board_list.size()%2=%d\n", - fs.isOpened(), (int)board_list.empty(), board_list.isSeq(), board_list.size()%2); - ts.set_failed_test_info( CvTS::FAIL_MISSING_TEST_DATA ); - return; - } - - int progress = 0; - int max_idx = board_list.node->data.seq->total/2; - double sum_error = 0.0; - int count = 0; - - for(int idx = 0; idx < max_idx; ++idx ) - { - ts.update_context( this, idx, true ); - - /* read the image */ - string img_file = board_list[idx * 2]; - Mat gray = imread( folder + img_file, 0); - - if( gray.empty() ) - { - ts.printf( CvTS::LOG, "one of chessboard images can't be read: %s\n", img_file.c_str() ); - ts.set_failed_test_info( CvTS::FAIL_MISSING_TEST_DATA ); - continue; - } - - string filename = folder + (string)board_list[idx * 2 + 1]; - Mat expected; - { - CvMat *u = (CvMat*)cvLoad( filename.c_str() ); - if(!u ) - { - ts.printf( CvTS::LOG, "one of chessboard corner files can't be read: %s\n", filename.c_str() ); - ts.set_failed_test_info( CvTS::FAIL_MISSING_TEST_DATA ); - continue; - } - expected = Mat(u, true); - cvReleaseMat( &u ); - } - size_t count_exp = static_cast(expected.cols * expected.rows); - Size pattern_size = expected.size(); - - vector v; - bool result = false; - switch( pattern ) - { - case CHESSBOARD: - result = findChessboardCorners(gray, pattern_size, v, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE); - break; - case CIRCLES_GRID: - result = findCirclesGrid(gray, pattern_size, v, CALIB_CB_SYMMETRIC_GRID); - break; - case ASYMMETRIC_CIRCLES_GRID: - result = findCirclesGrid(gray, pattern_size, v, CALIB_CB_ASYMMETRIC_GRID); - break; - } - show_points( gray, Mat(), v, pattern_size, result ); - if( !result || v.size() != count_exp ) - { - ts.printf( CvTS::LOG, "chessboard is not found in %s\n", img_file.c_str() ); - ts.set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - continue; - } - -#ifndef WRITE_POINTS - double err = calcError(v, expected); -#if 0 - if( err > rough_success_error_level ) - { - ts.printf( CvTS::LOG, "bad accuracy of corner guesses\n" ); - ts.set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - continue; - } -#endif - max_rough_error = MAX( max_rough_error, err ); -#endif - if( pattern == CHESSBOARD ) - cornerSubPix( gray, v, Size(5, 5), Size(-1,-1), TermCriteria(TermCriteria::EPS|TermCriteria::MAX_ITER, 30, 0.1)); - //find4QuadCornerSubpix(gray, v, Size(5, 5)); - show_points( gray, expected, v, pattern_size, result ); - -#ifndef WRITE_POINTS -// printf("called find4QuadCornerSubpix\n"); - err = calcError(v, expected); - sum_error += err; - count++; -#if 1 - if( err > precise_success_error_level ) - { - ts.printf( CvTS::LOG, "Image %s: bad accuracy of adjusted corners %f\n", img_file.c_str(), err ); - ts.set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - continue; - } -#endif - ts.printf(CvTS::LOG, "Error on %s is %f\n", img_file.c_str(), err); - max_precise_error = MAX( max_precise_error, err ); -#else - Mat mat_v(pattern_size, CV_32FC2, (void*)&v[0]); - CvMat cvmat_v = mat_v; - cvSave( filename.c_str(), &cvmat_v ); -#endif - progress = update_progress( progress, idx, max_idx, 0 ); - } - - sum_error /= count; - ts.printf(CvTS::LOG, "Average error is %f\n", sum_error); -} - -double calcErrorMinError(const Size& cornSz, const vector& corners_found, const vector& corners_generated) -{ - Mat m1(cornSz, CV_32FC2, (Point2f*)&corners_generated[0]); - Mat m2; flip(m1, m2, 0); - - Mat m3; flip(m1, m3, 1); m3 = m3.t(); flip(m3, m3, 1); - - Mat m4 = m1.t(); flip(m4, m4, 1); - - double min1 = min(calcError(corners_found, m1), calcError(corners_found, m2)); - double min2 = min(calcError(corners_found, m3), calcError(corners_found, m4)); - return min(min1, min2); -} - -bool validateData(const ChessBoardGenerator& cbg, const Size& imgSz, - const vector& corners_generated) -{ - Size cornersSize = cbg.cornersSize(); - Mat_ mat(cornersSize.height, cornersSize.width, (Point2f*)&corners_generated[0]); - - double minNeibDist = std::numeric_limits::max(); - double tmp = 0; - for(int i = 1; i < mat.rows - 2; ++i) - for(int j = 1; j < mat.cols - 2; ++j) - { - const Point2f& cur = mat(i, j); - - tmp = norm( cur - mat(i + 1, j + 1) ); - if (tmp < minNeibDist) - tmp = minNeibDist; - - tmp = norm( cur - mat(i - 1, j + 1 ) ); - if (tmp < minNeibDist) - tmp = minNeibDist; - - tmp = norm( cur - mat(i + 1, j - 1) ); - if (tmp < minNeibDist) - tmp = minNeibDist; - - tmp = norm( cur - mat(i - 1, j - 1) ); - if (tmp < minNeibDist) - tmp = minNeibDist; - } - - const double threshold = 0.25; - double cbsize = (max(cornersSize.width, cornersSize.height) + 1) * minNeibDist; - int imgsize = min(imgSz.height, imgSz.width); - return imgsize * threshold < cbsize; -} - -bool CV_ChessboardDetectorTest::checkByGenerator() -{ - bool res = true; - //theRNG() = 0x58e6e895b9913160; - //cv::DefaultRngAuto dra; - //theRNG() = *ts->get_rng(); - - Mat bg(Size(800, 600), CV_8UC3, Scalar::all(255)); - randu(bg, Scalar::all(0), Scalar::all(255)); - GaussianBlur(bg, bg, Size(7,7), 3.0); - - Mat_ camMat(3, 3); - camMat << 300.f, 0.f, bg.cols/2.f, 0, 300.f, bg.rows/2.f, 0.f, 0.f, 1.f; - - Mat_ distCoeffs(1, 5); - distCoeffs << 1.2f, 0.2f, 0.f, 0.f, 0.f; - - const Size sizes[] = { Size(6, 6), Size(8, 6), Size(11, 12), Size(5, 4) }; - const size_t sizes_num = sizeof(sizes)/sizeof(sizes[0]); - const int test_num = 16; - int progress = 0; - for(int i = 0; i < test_num; ++i) - { - progress = update_progress( progress, i, test_num, 0 ); - ChessBoardGenerator cbg(sizes[i % sizes_num]); - - vector corners_generated; - - Mat cb = cbg(bg, camMat, distCoeffs, corners_generated); - - if(!validateData(cbg, cb.size(), corners_generated)) - { - ts->printf( CvTS::LOG, "Chess board skipped - too small" ); - continue; - } - - /*cb = cb * 0.8 + Scalar::all(30); - GaussianBlur(cb, cb, Size(3, 3), 0.8); */ - //cv::addWeighted(cb, 0.8, bg, 0.2, 20, cb); - //cv::namedWindow("CB"); cv::imshow("CB", cb); cv::waitKey(); - - vector corners_found; - int flags = i % 8; // need to check branches for all flags - bool found = findChessboardCorners(cb, cbg.cornersSize(), corners_found, flags); - if (!found) - { - ts->printf( CvTS::LOG, "Chess board corners not found\n" ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - res = false; - continue; - } - - double err = calcErrorMinError(cbg.cornersSize(), corners_found, corners_generated); - if( err > rough_success_error_level ) - { - ts->printf( CvTS::LOG, "bad accuracy of corner guesses" ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - res = false; - continue; - } - } - - /* ***** negative ***** */ - { - vector corners_found; - bool found = findChessboardCorners(bg, Size(8, 7), corners_found); - if (found) - res = false; - - ChessBoardGenerator cbg(Size(8, 7)); - - vector cg; - Mat cb = cbg(bg, camMat, distCoeffs, cg); - - found = findChessboardCorners(cb, Size(3, 4), corners_found); - if (found) - res = false; - - Point2f c = std::accumulate(cg.begin(), cg.end(), Point2f(), plus()) * (1.f/cg.size()); - - Mat_ aff(2, 3); - aff << 1.0, 0.0, -(double)c.x, 0.0, 1.0, 0.0; - Mat sh; - warpAffine(cb, sh, aff, cb.size()); - - found = findChessboardCorners(sh, cbg.cornersSize(), corners_found); - if (found) - res = false; - - vector< vector > cnts(1); - vector& cnt = cnts[0]; - cnt.push_back(cg[ 0]); cnt.push_back(cg[0+2]); - cnt.push_back(cg[7+0]); cnt.push_back(cg[7+2]); - cv::drawContours(cb, cnts, -1, Scalar::all(128), CV_FILLED); - - found = findChessboardCorners(cb, cbg.cornersSize(), corners_found); - if (found) - res = false; - - cv::drawChessboardCorners(cb, cbg.cornersSize(), Mat(corners_found), found); - } - - return res; -} - -CV_ChessboardDetectorTest chessboard_detector_test ( CHESSBOARD, "chessboard-detector", "cvFindChessboardCorners" ); -CV_ChessboardDetectorTest circlesgrid_detector_test ( CIRCLES_GRID, "circlesgrid-detector", "findCirclesGrid" ); -CV_ChessboardDetectorTest asymmetric_circlesgrid_detector_test ( ASYMMETRIC_CIRCLES_GRID, "asymmetric-circlesgrid-detector", "findCirclesGrid" ); - -/* End of file. */ diff --git a/tests/cv/src/acolor.cpp b/tests/cv/src/acolor.cpp deleted file mode 100644 index 3608eb5..0000000 --- a/tests/cv/src/acolor.cpp +++ /dev/null @@ -1,1803 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -/////////////////////////// base test class for color transformations ///////////////////////// - -static const char* cvtcolor_param_names[] = { "op", "size", "depth", 0 }; -static const int cvtcolor_depths_8_16_32[] = { CV_8U, CV_16U, CV_32F, -1 }; -static const int cvtcolor_depths_8_32[] = { CV_8U, CV_32F, -1 }; -static const int cvtcolor_depths_8[] = { CV_8U, -1 }; - -static const CvSize cvtcolor_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize cvtcolor_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; - -class CV_ColorCvtBaseTestImpl : public CvArrTest -{ -public: - CV_ColorCvtBaseTestImpl( const char* test_name, const char* test_funcs, - bool custom_inv_transform, bool allow_32f, bool allow_16u ); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - int write_default_params(CvFileStorage* fs); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - - // input --- fwd_transform -> ref_output[0] - virtual void convert_forward( const CvMat* src, CvMat* dst ); - // ref_output[0] --- inv_transform ---> ref_output[1] (or input -- copy --> ref_output[1]) - virtual void convert_backward( const CvMat* src, const CvMat* dst, CvMat* dst2 ); - - // called from default implementation of convert_forward - virtual void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - - // called from default implementation of convert_backward - virtual void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); - - const char* fwd_code_str; - const char* inv_code_str; - - void run_func(); - bool allow_16u, allow_32f; - int blue_idx; - bool inplace; - bool custom_inv_transform; - int fwd_code, inv_code; - int timing_code; - bool test_cpp; - bool hue_channel; -}; - - -CV_ColorCvtBaseTestImpl::CV_ColorCvtBaseTestImpl( const char* test_name, const char* test_funcs, - bool _custom_inv_transform, bool _allow_32f, bool _allow_16u ) - : CvArrTest( test_name, test_funcs, "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - allow_16u = _allow_16u; - allow_32f = _allow_32f; - custom_inv_transform = _custom_inv_transform; - fwd_code = inv_code = timing_code = -1; - element_wise_relative_error = false; - - size_list = cvtcolor_sizes; - whole_size_list = cvtcolor_whole_sizes; - depth_list = cvtcolor_depths_8_16_32; - - fwd_code_str = inv_code_str = 0; - - default_timing_param_names = 0; - test_cpp = false; - hue_channel = false; -} - - -int CV_ColorCvtBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE && fwd_code_str != 0 ) - { - start_write_param( fs ); - cvStartWriteStruct( fs, "op", CV_NODE_SEQ+CV_NODE_FLOW ); - if( strcmp( fwd_code_str, "" ) != 0 ) - cvWriteString( fs, 0, fwd_code_str ); - if( strcmp( inv_code_str, "" ) != 0 ) - cvWriteString( fs, 0, inv_code_str ); - cvEndWriteStruct(fs); - } - return code; -} - - -void CV_ColorCvtBaseTestImpl::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT ) - { - int depth = CV_MAT_DEPTH(type); - *low = cvScalarAll(0.); - *high = cvScalarAll( depth == CV_8U ? 256 : depth == CV_16U ? 65536 : 1. ); - } -} - - -void CV_ColorCvtBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth, cn; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( allow_16u && allow_32f ) - { - depth = cvTsRandInt(rng) % 3; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : CV_32F; - } - else if( allow_16u || allow_32f ) - { - depth = cvTsRandInt(rng) % 2; - depth = depth == 0 ? CV_8U : allow_16u ? CV_16U : CV_32F; - } - else - depth = CV_8U; - - cn = (cvTsRandInt(rng) & 1) + 3; - blue_idx = cvTsRandInt(rng) & 1 ? 2 : 0; - - types[INPUT][0] = CV_MAKETYPE(depth, cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, 3); - if( test_array[OUTPUT].size() > 1 ) - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_MAKETYPE(depth, cn); - - inplace = cn == 3 && cvTsRandInt(rng) % 2 != 0; - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -void CV_ColorCvtBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - int depth = CV_MAT_DEPTH(types[INPUT][0]); - const char* op_str = cvReadString( find_timing_param( "op" ), "none" ); - timing_code = strcmp( op_str, inv_code_str ) == 0 ? inv_code : fwd_code; - types[INPUT][0] = types[OUTPUT][0] = CV_MAKETYPE(depth, 3); - if( test_array[OUTPUT].size() > 1 ) - types[OUTPUT][1] = types[OUTPUT][0]; -} - - -int CV_ColorCvtBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - if( inplace ) - cvTsCopy( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ); - if( ts->get_testing_mode() == CvTS::TIMING_MODE && timing_code != fwd_code ) - { - int save_timing_code = timing_code; - timing_code = fwd_code; - run_func(); // initialize the intermediate image for backward color space transformation - timing_code = save_timing_code; - } - } - return code; -} - - -void CV_ColorCvtBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "op" ), fwd_code_str )); - ptr += strlen(ptr); - params_left--; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_ColorCvtBaseTestImpl::run_func() -{ - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - CvArr* out0 = test_array[OUTPUT][0]; - cv::Mat _out0 = cv::cvarrToMat(out0), _out1 = cv::cvarrToMat(test_array[OUTPUT][1]); - - if(!test_cpp) - cvCvtColor( inplace ? out0 : test_array[INPUT][0], out0, fwd_code ); - else - cv::cvtColor( cv::cvarrToMat(inplace ? out0 : test_array[INPUT][0]), _out0, fwd_code, _out0.channels()); - - if( inplace ) - { - cvCopy( out0, test_array[OUTPUT][1] ); - out0 = test_array[OUTPUT][1]; - } - if(!test_cpp) - cvCvtColor( out0, test_array[OUTPUT][1], inv_code ); - else - cv::cvtColor(cv::cvarrToMat(out0), _out1, inv_code, _out1.channels()); - } - else if( timing_code == fwd_code ) - cvCvtColor( test_array[INPUT][0], test_array[OUTPUT][0], timing_code ); - else - cvCvtColor( test_array[OUTPUT][0], test_array[OUTPUT][1], timing_code ); -} - - -void CV_ColorCvtBaseTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - convert_forward( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0] ); - convert_backward( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - &test_mat[REF_OUTPUT][1] ); - int depth = CV_MAT_DEPTH(test_mat[REF_OUTPUT][0].type); - if( depth == CV_8U && hue_channel ) - { - for( int y = 0; y < test_mat[REF_OUTPUT][0].rows; y++ ) - for( int x = 0; x < test_mat[REF_OUTPUT][0].cols; x++ ) - { - uchar* h0 = test_mat[REF_OUTPUT][0].data.ptr + test_mat[REF_OUTPUT][0].step*y + x*3; - uchar* h = test_mat[OUTPUT][0].data.ptr + test_mat[OUTPUT][0].step*y + x*3; - if( abs(*h - *h0) == 180 ) - if( *h == 0 ) *h = 180; - } - } -} - - -void CV_ColorCvtBaseTestImpl::convert_forward( const CvMat* src, CvMat* dst ) -{ - const float c8u = 0.0039215686274509803f; // 1./255 - const float c16u = 1.5259021896696422e-005f; // 1./65535 - int depth = CV_MAT_DEPTH(src->type); - int cn = CV_MAT_CN(src->type), dst_cn = CV_MAT_CN(dst->type); - int cols = src->cols, dst_cols_n = dst->cols*dst_cn; - float* src_buf = (float*)cvAlloc( src->cols*3*sizeof(src_buf[0]) ); - float* dst_buf = (float*)cvAlloc( dst->cols*3*sizeof(dst_buf[0]) ); - int i, j; - - assert( (cn == 3 || cn == 4) && (dst_cn == 3 || dst_cn == 1) ); - - for( i = 0; i < src->rows; i++ ) - { - switch( depth ) - { - case CV_8U: - { - const uchar* src_row = (const uchar*)(src->data.ptr + i*src->step); - uchar* dst_row = (uchar*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - src_buf[j*3] = src_row[j*cn + blue_idx]*c8u; - src_buf[j*3+1] = src_row[j*cn + 1]*c8u; - src_buf[j*3+2] = src_row[j*cn + (blue_idx^2)]*c8u; - } - - convert_row_bgr2abc_32f_c3( src_buf, dst_buf, cols ); - - for( j = 0; j < dst_cols_n; j++ ) - { - int t = cvRound( dst_buf[j] ); - dst_row[j] = CV_CAST_8U(t); - } - } - break; - case CV_16U: - { - const ushort* src_row = (const ushort*)(src->data.ptr + i*src->step); - ushort* dst_row = (ushort*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - src_buf[j*3] = src_row[j*cn + blue_idx]*c16u; - src_buf[j*3+1] = src_row[j*cn + 1]*c16u; - src_buf[j*3+2] = src_row[j*cn + (blue_idx^2)]*c16u; - } - - convert_row_bgr2abc_32f_c3( src_buf, dst_buf, cols ); - - for( j = 0; j < dst_cols_n; j++ ) - { - int t = cvRound( dst_buf[j] ); - dst_row[j] = CV_CAST_16U(t); - } - } - break; - case CV_32F: - { - const float* src_row = (const float*)(src->data.ptr + i*src->step); - float* dst_row = (float*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - src_buf[j*3] = src_row[j*cn + blue_idx]; - src_buf[j*3+1] = src_row[j*cn + 1]; - src_buf[j*3+2] = src_row[j*cn + (blue_idx^2)]; - } - - convert_row_bgr2abc_32f_c3( src_buf, dst_row, cols ); - } - break; - default: - assert(0); - } - } - - cvFree( &src_buf ); - cvFree( &dst_buf ); -} - - -void CV_ColorCvtBaseTestImpl::convert_row_bgr2abc_32f_c3( const float* /*src_row*/, - float* /*dst_row*/, int /*n*/ ) -{ -} - - -void CV_ColorCvtBaseTestImpl::convert_row_abc2bgr_32f_c3( const float* /*src_row*/, - float* /*dst_row*/, int /*n*/ ) -{ -} - - -void CV_ColorCvtBaseTestImpl::convert_backward( const CvMat* src, const CvMat* dst, CvMat* dst2 ) -{ - if( custom_inv_transform ) - { - int depth = CV_MAT_DEPTH(src->type); - int src_cn = CV_MAT_CN(dst->type), cn = CV_MAT_CN(dst2->type); - int cols_n = src->cols*src_cn, dst_cols = dst->cols; - float* src_buf = (float*)cvAlloc( src->cols*3*sizeof(src_buf[0]) ); - float* dst_buf = (float*)cvAlloc( dst->cols*3*sizeof(dst_buf[0]) ); - int i, j; - - assert( cn == 3 || cn == 4 ); - - for( i = 0; i < src->rows; i++ ) - { - switch( depth ) - { - case CV_8U: - { - const uchar* src_row = (const uchar*)(dst->data.ptr + i*dst->step); - uchar* dst_row = (uchar*)(dst2->data.ptr + i*dst2->step); - - for( j = 0; j < cols_n; j++ ) - src_buf[j] = src_row[j]; - - convert_row_abc2bgr_32f_c3( src_buf, dst_buf, dst_cols ); - - for( j = 0; j < dst_cols; j++ ) - { - int b = cvRound( dst_buf[j*3]*255. ); - int g = cvRound( dst_buf[j*3+1]*255. ); - int r = cvRound( dst_buf[j*3+2]*255. ); - dst_row[j*cn + blue_idx] = CV_CAST_8U(b); - dst_row[j*cn + 1] = CV_CAST_8U(g); - dst_row[j*cn + (blue_idx^2)] = CV_CAST_8U(r); - if( cn == 4 ) - dst_row[j*cn + 3] = 255; - } - } - break; - case CV_16U: - { - const ushort* src_row = (const ushort*)(dst->data.ptr + i*dst->step); - ushort* dst_row = (ushort*)(dst2->data.ptr + i*dst2->step); - - for( j = 0; j < cols_n; j++ ) - src_buf[j] = src_row[j]; - - convert_row_abc2bgr_32f_c3( src_buf, dst_buf, dst_cols ); - - for( j = 0; j < dst_cols; j++ ) - { - int b = cvRound( dst_buf[j*3]*65535. ); - int g = cvRound( dst_buf[j*3+1]*65535. ); - int r = cvRound( dst_buf[j*3+2]*65535. ); - dst_row[j*cn + blue_idx] = CV_CAST_16U(b); - dst_row[j*cn + 1] = CV_CAST_16U(g); - dst_row[j*cn + (blue_idx^2)] = CV_CAST_16U(r); - if( cn == 4 ) - dst_row[j*cn + 3] = 65535; - } - } - break; - case CV_32F: - { - const float* src_row = (const float*)(dst->data.ptr + i*dst->step); - float* dst_row = (float*)(dst2->data.ptr + i*dst2->step); - - convert_row_abc2bgr_32f_c3( src_row, dst_buf, dst_cols ); - - for( j = 0; j < dst_cols; j++ ) - { - float b = dst_buf[j*3]; - float g = dst_buf[j*3+1]; - float r = dst_buf[j*3+2]; - dst_row[j*cn + blue_idx] = b; - dst_row[j*cn + 1] = g; - dst_row[j*cn + (blue_idx^2)] = r; - if( cn == 4 ) - dst_row[j*cn + 3] = 1.f; - } - } - break; - default: - assert(0); - } - } - - cvFree( &src_buf ); - cvFree( &dst_buf ); - } - else - { - int i, j, k; - int elem_size = CV_ELEM_SIZE(src->type), elem_size1 = CV_ELEM_SIZE(src->type & CV_MAT_DEPTH_MASK); - int width_n = src->cols*elem_size; - - for( i = 0; i < src->rows; i++ ) - { - memcpy( dst2->data.ptr + i*dst2->step, src->data.ptr + i*src->step, width_n ); - if( CV_MAT_CN(src->type) == 4 ) - { - // clear the alpha channel - uchar* ptr = dst2->data.ptr + i*dst2->step + elem_size1*3; - for( j = 0; j < width_n; j += elem_size ) - { - for( k = 0; k < elem_size1; k++ ) - ptr[j + k] = 0; - } - } - } - } -} - - -CV_ColorCvtBaseTestImpl cvtcolor( "color", "", false, false, false ); - - -class CV_ColorCvtBaseTest : public CV_ColorCvtBaseTestImpl -{ -public: - CV_ColorCvtBaseTest( const char* test_name, const char* test_funcs, - bool custom_inv_transform, bool allow_32f, bool allow_16u ); -}; - - -CV_ColorCvtBaseTest::CV_ColorCvtBaseTest( const char* test_name, const char* test_funcs, - bool _custom_inv_transform, bool _allow_32f, bool _allow_16u ) - : CV_ColorCvtBaseTestImpl( test_name, test_funcs, _custom_inv_transform, _allow_32f, _allow_16u ) -{ - default_timing_param_names = cvtcolor_param_names; - depth_list = 0; - cn_list = 0; - size_list = whole_size_list = 0; -} - -#undef INIT_FWD_INV_CODES -#define INIT_FWD_INV_CODES( fwd, inv ) \ - fwd_code = CV_##fwd; inv_code = CV_##inv; \ - fwd_code_str = #fwd; inv_code_str = #inv - -//// rgb <=> gray -class CV_ColorGrayTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorGrayTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_ColorGrayTest::CV_ColorGrayTest() - : CV_ColorCvtBaseTest( "color-gray", "cvCvtColor", true, true, true ) -{ - INIT_FWD_INV_CODES( BGR2GRAY, GRAY2BGR ); -} - - -void CV_ColorGrayTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int cn = CV_MAT_CN(types[INPUT][0]); - types[OUTPUT][0] = types[REF_OUTPUT][0] = types[INPUT][0] & CV_MAT_DEPTH_MASK; - inplace = false; - - if( cn == 3 ) - { - if( blue_idx == 0 ) - fwd_code = CV_BGR2GRAY, inv_code = CV_GRAY2BGR; - else - fwd_code = CV_RGB2GRAY, inv_code = CV_GRAY2RGB; - } - else - { - if( blue_idx == 0 ) - fwd_code = CV_BGRA2GRAY, inv_code = CV_GRAY2BGRA; - else - fwd_code = CV_RGBA2GRAY, inv_code = CV_GRAY2RGBA; - } -} - - -void CV_ColorGrayTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ColorCvtBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[OUTPUT][0] &= CV_MAT_DEPTH_MASK; -} - - -double CV_ColorGrayTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? 2 : depth == CV_16U ? 16 : 1e-5; -} - - -void CV_ColorGrayTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - double scale = depth == CV_8U ? 255 : depth == CV_16U ? 65535 : 1; - double cr = 0.299*scale; - double cg = 0.587*scale; - double cb = 0.114*scale; - int j; - - for( j = 0; j < n; j++ ) - dst_row[j] = (float)(src_row[j*3]*cb + src_row[j*3+1]*cg + src_row[j*3+2]*cr); -} - - -void CV_ColorGrayTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int j, depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float scale = depth == CV_8U ? (1.f/255) : depth == CV_16U ? 1.f/65535 : 1.f; - for( j = 0; j < n; j++ ) - dst_row[j*3] = dst_row[j*3+1] = dst_row[j*3+2] = src_row[j]*scale; -} - - -CV_ColorGrayTest color_gray_test; - - -//// rgb <=> ycrcb -class CV_ColorYCrCbTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorYCrCbTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorYCrCbTest::CV_ColorYCrCbTest() - : CV_ColorCvtBaseTest( "color-ycc", "cvCvtColor", true, true, true ) -{ - INIT_FWD_INV_CODES( BGR2YCrCb, YCrCb2BGR ); -} - - -void CV_ColorYCrCbTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_BGR2YCrCb, inv_code = CV_YCrCb2BGR; - else - fwd_code = CV_RGB2YCrCb, inv_code = CV_YCrCb2RGB; -} - - -double CV_ColorYCrCbTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? 2 : depth == CV_16U ? 32 : 1e-3; -} - - -void CV_ColorYCrCbTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - double scale = depth == CV_8U ? 255 : depth == CV_16U ? 65535 : 1; - double bias = depth == CV_8U ? 128 : depth == CV_16U ? 32768 : 0.5; - - double M[] = { 0.299, 0.587, 0.114, - 0.49981, -0.41853, -0.08128, - -0.16864, -0.33107, 0.49970 }; - int j; - for( j = 0; j < 9; j++ ) - M[j] *= scale; - - for( j = 0; j < n*3; j += 3 ) - { - double r = src_row[j+2]; - double g = src_row[j+1]; - double b = src_row[j]; - double y = M[0]*r + M[1]*g + M[2]*b; - double cr = M[3]*r + M[4]*g + M[5]*b + bias; - double cb = M[6]*r + M[7]*g + M[8]*b + bias; - dst_row[j] = (float)y; - dst_row[j+1] = (float)cr; - dst_row[j+2] = (float)cb; - } -} - - -void CV_ColorYCrCbTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - double bias = depth == CV_8U ? 128 : depth == CV_16U ? 32768 : 0.5; - double scale = depth == CV_8U ? 1./255 : depth == CV_16U ? 1./65535 : 1; - double M[] = { 1, 1.40252, 0, - 1, -0.71440, -0.34434, - 1, 0, 1.77305 }; - int j; - for( j = 0; j < 9; j++ ) - M[j] *= scale; - - for( j = 0; j < n*3; j += 3 ) - { - double y = src_row[j]; - double cr = src_row[j+1] - bias; - double cb = src_row[j+2] - bias; - double r = M[0]*y + M[1]*cr + M[2]*cb; - double g = M[3]*y + M[4]*cr + M[5]*cb; - double b = M[6]*y + M[7]*cr + M[8]*cb; - dst_row[j] = (float)b; - dst_row[j+1] = (float)g; - dst_row[j+2] = (float)r; - } -} - - -CV_ColorYCrCbTest color_ycrcb_test; - - - -//// rgb <=> hsv -class CV_ColorHSVTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorHSVTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorHSVTest::CV_ColorHSVTest() - : CV_ColorCvtBaseTest( "color-hsv", "cvCvtColor", true, true, false ) -{ - INIT_FWD_INV_CODES( BGR2HSV, HSV2BGR ); - depth_list = cvtcolor_depths_8_32; - hue_channel = true; -} - - -void CV_ColorHSVTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_BGR2HSV, inv_code = CV_HSV2BGR; - else - fwd_code = CV_RGB2HSV, inv_code = CV_HSV2RGB; -} - - -double CV_ColorHSVTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? (j == 0 ? 4 : 16) : depth == CV_16U ? 32 : 1e-3; -} - - -void CV_ColorHSVTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float h_scale = depth == CV_8U ? 30.f : 60.f; - float scale = depth == CV_8U ? 255.f : depth == CV_16U ? 65535.f : 1.f; - int j; - - for( j = 0; j < n*3; j += 3 ) - { - float r = src_row[j+2]; - float g = src_row[j+1]; - float b = src_row[j]; - float vmin = MIN(r,g); - float v = MAX(r,g); - float s, h, diff; - vmin = MIN(vmin,b); - v = MAX(v,b); - diff = v - vmin; - if( diff == 0 ) - s = h = 0; - else - { - s = diff/(v + FLT_EPSILON); - diff = 1.f/diff; - - h = r == v ? (g - b)*diff : - g == v ? 2 + (b - r)*diff : 4 + (r - g)*diff; - - if( h < 0 ) - h += 6; - } - - dst_row[j] = h*h_scale; - dst_row[j+1] = s*scale; - dst_row[j+2] = v*scale; - } -} - -// taken from http://www.cs.rit.edu/~ncs/color/t_convert.html -void CV_ColorHSVTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float h_scale = depth == CV_8U ? 1.f/30 : 1.f/60; - float scale = depth == CV_8U ? 1.f/255 : depth == CV_16U ? 1.f/65535 : 1; - int j; - - for( j = 0; j < n*3; j += 3 ) - { - float h = src_row[j]*h_scale; - float s = src_row[j+1]*scale; - float v = src_row[j+2]*scale; - float r = v, g = v, b = v; - - if( h < 0 ) - h += 6; - else if( h >= 6 ) - h -= 6; - - if( s != 0 ) - { - int i = cvFloor(h); - float f = h - i; - float p = v*(1 - s); - float q = v*(1 - s*f); - float t = v*(1 - s*(1 - f)); - - if( i == 0 ) - r = v, g = t, b = p; - else if( i == 1 ) - r = q, g = v, b = p; - else if( i == 2 ) - r = p, g = v, b = t; - else if( i == 3 ) - r = p, g = q, b = v; - else if( i == 4 ) - r = t, g = p, b = v; - else - r = v, g = p, b = q; - } - - dst_row[j] = b; - dst_row[j+1] = g; - dst_row[j+2] = r; - } -} - - -CV_ColorHSVTest color_hsv_test; - - - -//// rgb <=> hls -class CV_ColorHLSTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorHLSTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorHLSTest::CV_ColorHLSTest() - : CV_ColorCvtBaseTest( "color-hls", "cvCvtColor", true, true, false ) -{ - INIT_FWD_INV_CODES( BGR2HLS, HLS2BGR ); - depth_list = cvtcolor_depths_8_32; - hue_channel = true; -} - - -void CV_ColorHLSTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_BGR2HLS, inv_code = CV_HLS2BGR; - else - fwd_code = CV_RGB2HLS, inv_code = CV_HLS2RGB; -} - - -double CV_ColorHLSTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? (j == 0 ? 4 : 16) : depth == CV_16U ? 32 : 1e-4; -} - - -void CV_ColorHLSTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float h_scale = depth == CV_8U ? 30.f : 60.f; - float scale = depth == CV_8U ? 255.f : depth == CV_16U ? 65535.f : 1.f; - int j; - - for( j = 0; j < n*3; j += 3 ) - { - float r = src_row[j+2]; - float g = src_row[j+1]; - float b = src_row[j]; - float vmin = MIN(r,g); - float v = MAX(r,g); - float s, h, l, diff; - vmin = MIN(vmin,b); - v = MAX(v,b); - diff = v - vmin; - - if( diff == 0 ) - s = h = 0, l = v; - else - { - l = (v + vmin)*0.5f; - s = l <= 0.5f ? diff / (v + vmin) : diff / (2 - v - vmin); - diff = 1.f/diff; - - h = r == v ? (g - b)*diff : - g == v ? 2 + (b - r)*diff : 4 + (r - g)*diff; - - if( h < 0 ) - h += 6; - } - - dst_row[j] = h*h_scale; - dst_row[j+1] = l*scale; - dst_row[j+2] = s*scale; - } -} - - -void CV_ColorHLSTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float h_scale = depth == CV_8U ? 1.f/30 : 1.f/60; - float scale = depth == CV_8U ? 1.f/255 : depth == CV_16U ? 1.f/65535 : 1; - int j; - - for( j = 0; j < n*3; j += 3 ) - { - float h = src_row[j]*h_scale; - float l = src_row[j+1]*scale; - float s = src_row[j+2]*scale; - float r = l, g = l, b = l; - - if( h < 0 ) - h += 6; - else if( h >= 6 ) - h -= 6; - - if( s != 0 ) - { - float m2 = l <= 0.5f ? l*(1.f + s) : l + s - l*s; - float m1 = 2*l - m2; - float h1 = h + 2; - - if( h1 >= 6 ) - h1 -= 6; - if( h1 < 1 ) - r = m1 + (m2 - m1)*h1; - else if( h1 < 3 ) - r = m2; - else if( h1 < 4 ) - r = m1 + (m2 - m1)*(4 - h1); - else - r = m1; - - h1 = h; - - if( h1 < 1 ) - g = m1 + (m2 - m1)*h1; - else if( h1 < 3 ) - g = m2; - else if( h1 < 4 ) - g = m1 + (m2 - m1)*(4 - h1); - else - g = m1; - - h1 = h - 2; - if( h1 < 0 ) - h1 += 6; - - if( h1 < 1 ) - b = m1 + (m2 - m1)*h1; - else if( h1 < 3 ) - b = m2; - else if( h1 < 4 ) - b = m1 + (m2 - m1)*(4 - h1); - else - b = m1; - } - - dst_row[j] = b; - dst_row[j+1] = g; - dst_row[j+2] = r; - } -} - - -CV_ColorHLSTest color_hls_test; - - -static const double RGB2XYZ[] = -{ - 0.412453, 0.357580, 0.180423, - 0.212671, 0.715160, 0.072169, - 0.019334, 0.119193, 0.950227 -}; - - -static const double XYZ2RGB[] = -{ - 3.240479, -1.53715, -0.498535, - -0.969256, 1.875991, 0.041556, - 0.055648, -0.204043, 1.057311 -}; - -static const float Xn = 0.950456f; -static const float Zn = 1.088754f; - - -//// rgb <=> xyz -class CV_ColorXYZTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorXYZTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorXYZTest::CV_ColorXYZTest() - : CV_ColorCvtBaseTest( "color-xyz", "cvCvtColor", true, true, true ) -{ - INIT_FWD_INV_CODES( BGR2XYZ, XYZ2BGR ); -} - - -void CV_ColorXYZTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_BGR2XYZ, inv_code = CV_XYZ2BGR; - else - fwd_code = CV_RGB2XYZ, inv_code = CV_XYZ2RGB; -} - - -double CV_ColorXYZTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? (j == 0 ? 2 : 8) : depth == CV_16U ? (j == 0 ? 64 : 128) : 1e-1; -} - - -void CV_ColorXYZTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - double scale = depth == CV_8U ? 255 : depth == CV_16U ? 65535 : 1; - - double M[9]; - int j; - for( j = 0; j < 9; j++ ) - M[j] = RGB2XYZ[j]*scale; - - for( j = 0; j < n*3; j += 3 ) - { - double r = src_row[j+2]; - double g = src_row[j+1]; - double b = src_row[j]; - double x = M[0]*r + M[1]*g + M[2]*b; - double y = M[3]*r + M[4]*g + M[5]*b; - double z = M[6]*r + M[7]*g + M[8]*b; - dst_row[j] = (float)x; - dst_row[j+1] = (float)y; - dst_row[j+2] = (float)z; - } -} - - -void CV_ColorXYZTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - double scale = depth == CV_8U ? 1./255 : depth == CV_16U ? 1./65535 : 1; - - double M[9]; - int j; - for( j = 0; j < 9; j++ ) - M[j] = XYZ2RGB[j]*scale; - - for( j = 0; j < n*3; j += 3 ) - { - double x = src_row[j]; - double y = src_row[j+1]; - double z = src_row[j+2]; - double r = M[0]*x + M[1]*y + M[2]*z; - double g = M[3]*x + M[4]*y + M[5]*z; - double b = M[6]*x + M[7]*y + M[8]*z; - dst_row[j] = (float)b; - dst_row[j+1] = (float)g; - dst_row[j+2] = (float)r; - } -} - - -CV_ColorXYZTest color_xyz_test; - - -//// rgb <=> L*a*b* -class CV_ColorLabTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorLabTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorLabTest::CV_ColorLabTest() - : CV_ColorCvtBaseTest( "color-lab", "cvCvtColor", true, true, false ) -{ - INIT_FWD_INV_CODES( BGR2Lab, Lab2BGR ); - depth_list = cvtcolor_depths_8_32; -} - - -void CV_ColorLabTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_LBGR2Lab, inv_code = CV_Lab2LBGR; - else - fwd_code = CV_LRGB2Lab, inv_code = CV_Lab2LRGB; -} - - -double CV_ColorLabTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 32 : 1e-3; -} - - -static const double _1_3 = 0.333333333333; - -void CV_ColorLabTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float Lscale = depth == CV_8U ? 255.f/100.f : depth == CV_16U ? 65535.f/100.f : 1.f; - float ab_bias = depth == CV_8U ? 128.f : depth == CV_16U ? 32768.f : 0.f; - int j; - float M[9]; - - for( j = 0; j < 9; j++ ) - M[j] = (float)RGB2XYZ[j]; - - for( j = 0; j < n*3; j += 3 ) - { - float r = src_row[j+2]; - float g = src_row[j+1]; - float b = src_row[j]; - - float X = (r*M[0] + g*M[1] + b*M[2])*(1.f/Xn); - float Y = r*M[3] + g*M[4] + b*M[5]; - float Z = (r*M[6] + g*M[7] + b*M[8])*(1.f/Zn); - float fX, fY, fZ; - - float L, a; - - if( Y > 0.008856 ) - { - fY = (float)pow((double)Y,_1_3); - L = 116.f*fY - 16.f; - } - else - { - fY = 7.787f*Y + 16.f/116.f; - L = 903.3f*Y; - } - - if( X > 0.008856 ) - fX = (float)pow((double)X,_1_3); - else - fX = 7.787f*X + 16.f/116.f; - - if( Z > 0.008856 ) - fZ = (float)pow((double)Z,_1_3); - else - fZ = 7.787f*Z + 16.f/116.f; - - a = 500.f*(fX - fY); - b = 200.f*(fY - fZ); - - dst_row[j] = L*Lscale; - dst_row[j+1] = a + ab_bias; - dst_row[j+2] = b + ab_bias; - } -} - - -void CV_ColorLabTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float Lscale = depth == CV_8U ? 100.f/255.f : depth == CV_16U ? 100.f/65535.f : 1.f; - float ab_bias = depth == CV_8U ? 128.f : depth == CV_16U ? 32768.f : 0.f; - int j; - float M[9]; - - for( j = 0; j < 9; j++ ) - M[j] = (float)XYZ2RGB[j]; - - for( j = 0; j < n*3; j += 3 ) - { - float L = src_row[j]*Lscale; - float a = src_row[j+1] - ab_bias; - float b = src_row[j+2] - ab_bias; - - float P = (L + 16.f)*(1.f/116.f); - float X = (P + a*0.002f); - float Z = (P - b*0.005f); - float Y = P*P*P; - X = Xn*X*X*X; - Z = Zn*Z*Z*Z; - - float r = M[0]*X + M[1]*Y + M[2]*Z; - float g = M[3]*X + M[4]*Y + M[5]*Z; - b = M[6]*X + M[7]*Y + M[8]*Z; - - dst_row[j] = b; - dst_row[j+1] = g; - dst_row[j+2] = r; - } -} - - -CV_ColorLabTest color_lab_test; - - -//// rgb <=> L*u*v* -class CV_ColorLuvTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorLuvTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ); - void convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ); -}; - - -CV_ColorLuvTest::CV_ColorLuvTest() - : CV_ColorCvtBaseTest( "color-luv", "cvCvtColor", true, true, false ) -{ - INIT_FWD_INV_CODES( BGR2Luv, Luv2BGR ); - depth_list = cvtcolor_depths_8_32; -} - - -void CV_ColorLuvTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( blue_idx == 0 ) - fwd_code = CV_LBGR2Luv, inv_code = CV_Luv2LBGR; - else - fwd_code = CV_LRGB2Luv, inv_code = CV_Luv2LRGB; -} - - -double CV_ColorLuvTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_8U ? 48 : depth == CV_16U ? 32 : 5e-2; -} - - -void CV_ColorLuvTest::convert_row_bgr2abc_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float Lscale = depth == CV_8U ? 255.f/100.f : depth == CV_16U ? 65535.f/100.f : 1.f; - int j; - - float M[9]; - float un = 4.f*Xn/(Xn + 15.f*1.f + 3*Zn); - float vn = 9.f*1.f/(Xn + 15.f*1.f + 3*Zn); - float u_scale = 1.f, u_bias = 0.f; - float v_scale = 1.f, v_bias = 0.f; - - for( j = 0; j < 9; j++ ) - M[j] = (float)RGB2XYZ[j]; - - if( depth == CV_8U ) - { - u_scale = 0.720338983f; - u_bias = 96.5254237f; - v_scale = 0.99609375f; - v_bias = 139.453125f; - } - - for( j = 0; j < n*3; j += 3 ) - { - float r = src_row[j+2]; - float g = src_row[j+1]; - float b = src_row[j]; - - float X = r*M[0] + g*M[1] + b*M[2]; - float Y = r*M[3] + g*M[4] + b*M[5]; - float Z = r*M[6] + g*M[7] + b*M[8]; - float d = X + 15*Y + 3*Z, L, u, v; - - if( d == 0 ) - L = u = v = 0; - else - { - if( Y > 0.008856f ) - L = (float)(116.*pow((double)Y,_1_3) - 16.); - else - L = 903.3f * Y; - - d = 1.f/d; - u = 13*L*(4*X*d - un); - v = 13*L*(9*Y*d - vn); - } - dst_row[j] = L*Lscale; - dst_row[j+1] = u*u_scale + u_bias; - dst_row[j+2] = v*v_scale + v_bias; - } -} - - -void CV_ColorLuvTest::convert_row_abc2bgr_32f_c3( const float* src_row, float* dst_row, int n ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - float Lscale = depth == CV_8U ? 100.f/255.f : depth == CV_16U ? 100.f/65535.f : 1.f; - int j; - float M[9]; - float un = 4.f*Xn/(Xn + 15.f*1.f + 3*Zn); - float vn = 9.f*1.f/(Xn + 15.f*1.f + 3*Zn); - float u_scale = 1.f, u_bias = 0.f; - float v_scale = 1.f, v_bias = 0.f; - - for( j = 0; j < 9; j++ ) - M[j] = (float)XYZ2RGB[j]; - - if( depth == CV_8U ) - { - u_scale = 1.f/0.720338983f; - u_bias = 96.5254237f; - v_scale = 1.f/0.99609375f; - v_bias = 139.453125f; - } - - for( j = 0; j < n*3; j += 3 ) - { - float L = src_row[j]*Lscale; - float u = (src_row[j+1] - u_bias)*u_scale; - float v = (src_row[j+2] - v_bias)*v_scale; - float X, Y, Z; - - if( L >= 8 ) - { - Y = (L + 16.f)*(1.f/116.f); - Y = Y*Y*Y; - } - else - { - Y = L * (1.f/903.3f); - if( L == 0 ) - L = 0.001f; - } - - u = u/(13*L) + un; - v = v/(13*L) + vn; - - X = -9*Y*u/((u - 4)*v - u*v); - Z = (9*Y - 15*v*Y - v*X)/(3*v); - - float r = M[0]*X + M[1]*Y + M[2]*Z; - float g = M[3]*X + M[4]*Y + M[5]*Z; - float b = M[6]*X + M[7]*Y + M[8]*Z; - - dst_row[j] = b; - dst_row[j+1] = g; - dst_row[j+2] = r; - } -} - - -CV_ColorLuvTest color_luv_test; - - - -//// rgb <=> another rgb -class CV_ColorRGBTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorRGBTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void convert_forward( const CvMat* src, CvMat* dst ); - void convert_backward( const CvMat* src, const CvMat* dst, CvMat* dst2 ); - int dst_bits; -}; - - -CV_ColorRGBTest::CV_ColorRGBTest() - : CV_ColorCvtBaseTest( "color-rgb", "cvCvtColor", true, true, true ) -{ - dst_bits = 0; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -void CV_ColorRGBTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int cn = CV_MAT_CN(types[INPUT][0]); - - dst_bits = 24; - - if( cvTsRandInt(rng) % 3 == 0 ) - { - types[INPUT][0] = types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_MAKETYPE(CV_8U,cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(CV_8U,2); - if( cvTsRandInt(rng) & 1 ) - { - if( blue_idx == 0 ) - fwd_code = CV_BGR2BGR565, inv_code = CV_BGR5652BGR; - else - fwd_code = CV_RGB2BGR565, inv_code = CV_BGR5652RGB; - dst_bits = 16; - } - else - { - if( blue_idx == 0 ) - fwd_code = CV_BGR2BGR555, inv_code = CV_BGR5552BGR; - else - fwd_code = CV_RGB2BGR555, inv_code = CV_BGR5552RGB; - dst_bits = 15; - } - } - else - { - if( cn == 3 ) - { - fwd_code = CV_RGB2BGR, inv_code = CV_BGR2RGB; - blue_idx = 2; - } - else if( blue_idx == 0 ) - fwd_code = CV_BGRA2BGR, inv_code = CV_BGR2BGRA; - else - fwd_code = CV_RGBA2BGR, inv_code = CV_BGR2RGBA; - } - - if( CV_MAT_CN(types[INPUT][0]) != CV_MAT_CN(types[OUTPUT][0]) ) - inplace = false; -} - - -double CV_ColorRGBTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CV_ColorRGBTest::convert_forward( const CvMat* src, CvMat* dst ) -{ - int depth = CV_MAT_DEPTH(src->type); - int cn = CV_MAT_CN(src->type); -/*#if defined _DEBUG || defined DEBUG - int dst_cn = CV_MAT_CN(dst->type); -#endif*/ - int i, j, cols = src->cols; - int g_rshift = dst_bits == 16 ? 2 : 3; - int r_lshift = dst_bits == 16 ? 11 : 10; - - //assert( (cn == 3 || cn == 4) && (dst_cn == 3 || (dst_cn == 2 && depth == CV_8U)) ); - - for( i = 0; i < src->rows; i++ ) - { - switch( depth ) - { - case CV_8U: - { - const uchar* src_row = (const uchar*)(src->data.ptr + i*src->step); - uchar* dst_row = (uchar*)(dst->data.ptr + i*dst->step); - - if( dst_bits == 24 ) - { - for( j = 0; j < cols; j++ ) - { - uchar b = src_row[j*cn + blue_idx]; - uchar g = src_row[j*cn + 1]; - uchar r = src_row[j*cn + (blue_idx^2)]; - dst_row[j*3] = b; - dst_row[j*3+1] = g; - dst_row[j*3+2] = r; - } - } - else - { - for( j = 0; j < cols; j++ ) - { - int b = src_row[j*cn + blue_idx] >> 3; - int g = src_row[j*cn + 1] >> g_rshift; - int r = src_row[j*cn + (blue_idx^2)] >> 3; - ((ushort*)dst_row)[j] = (ushort)(b | (g << 5) | (r << r_lshift)); - if( cn == 4 && src_row[j*4+3] ) - ((ushort*)dst_row)[j] |= 1 << (r_lshift+5); - } - } - } - break; - case CV_16U: - { - const ushort* src_row = (const ushort*)(src->data.ptr + i*src->step); - ushort* dst_row = (ushort*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - ushort b = src_row[j*cn + blue_idx]; - ushort g = src_row[j*cn + 1]; - ushort r = src_row[j*cn + (blue_idx^2)]; - dst_row[j*3] = b; - dst_row[j*3+1] = g; - dst_row[j*3+2] = r; - } - } - break; - case CV_32F: - { - const float* src_row = (const float*)(src->data.ptr + i*src->step); - float* dst_row = (float*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - float b = src_row[j*cn + blue_idx]; - float g = src_row[j*cn + 1]; - float r = src_row[j*cn + (blue_idx^2)]; - dst_row[j*3] = b; - dst_row[j*3+1] = g; - dst_row[j*3+2] = r; - } - } - break; - default: - assert(0); - } - } -} - - -void CV_ColorRGBTest::convert_backward( const CvMat* /*src*/, const CvMat* src, CvMat* dst ) -{ - int depth = CV_MAT_DEPTH(src->type); - int cn = CV_MAT_CN(dst->type); -/*#if defined _DEBUG || defined DEBUG - int src_cn = CV_MAT_CN(src->type); -#endif*/ - int i, j, cols = src->cols; - int g_lshift = dst_bits == 16 ? 2 : 3; - int r_rshift = dst_bits == 16 ? 11 : 10; - - //assert( (cn == 3 || cn == 4) && (src_cn == 3 || (src_cn == 2 && depth == CV_8U)) ); - - for( i = 0; i < src->rows; i++ ) - { - switch( depth ) - { - case CV_8U: - { - const uchar* src_row = (const uchar*)(src->data.ptr + i*src->step); - uchar* dst_row = (uchar*)(dst->data.ptr + i*dst->step); - - if( dst_bits == 24 ) - { - for( j = 0; j < cols; j++ ) - { - uchar b = src_row[j*3]; - uchar g = src_row[j*3 + 1]; - uchar r = src_row[j*3 + 2]; - - dst_row[j*cn + blue_idx] = b; - dst_row[j*cn + 1] = g; - dst_row[j*cn + (blue_idx^2)] = r; - - if( cn == 4 ) - dst_row[j*cn + 3] = 255; - } - } - else - { - for( j = 0; j < cols; j++ ) - { - ushort val = ((ushort*)src_row)[j]; - uchar b = (uchar)(val << 3); - uchar g = (uchar)((val >> 5) << g_lshift); - uchar r = (uchar)((val >> r_rshift) << 3); - - dst_row[j*cn + blue_idx] = b; - dst_row[j*cn + 1] = g; - dst_row[j*cn + (blue_idx^2)] = r; - - if( cn == 4 ) - { - uchar alpha = r_rshift == 11 || (val & 0x8000) != 0 ? 255 : 0; - dst_row[j*cn + 3] = alpha; - } - } - } - } - break; - case CV_16U: - { - const ushort* src_row = (const ushort*)(src->data.ptr + i*src->step); - ushort* dst_row = (ushort*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - ushort b = src_row[j*3]; - ushort g = src_row[j*3 + 1]; - ushort r = src_row[j*3 + 2]; - - dst_row[j*cn + blue_idx] = b; - dst_row[j*cn + 1] = g; - dst_row[j*cn + (blue_idx^2)] = r; - - if( cn == 4 ) - dst_row[j*cn + 3] = 65535; - } - } - break; - case CV_32F: - { - const float* src_row = (const float*)(src->data.ptr + i*src->step); - float* dst_row = (float*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < cols; j++ ) - { - float b = src_row[j*3]; - float g = src_row[j*3 + 1]; - float r = src_row[j*3 + 2]; - - dst_row[j*cn + blue_idx] = b; - dst_row[j*cn + 1] = g; - dst_row[j*cn + (blue_idx^2)] = r; - - if( cn == 4 ) - dst_row[j*cn + 3] = 1.f; - } - } - break; - default: - assert(0); - } - } -} - - -CV_ColorRGBTest color_rgb_test; - - -//// rgb <=> bayer - -static const char* cvtcolor_bayer_param_names[] = { "size", "depth", 0 }; - -class CV_ColorBayerTest : public CV_ColorCvtBaseTest -{ -public: - CV_ColorBayerTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CV_ColorBayerTest::CV_ColorBayerTest() - : CV_ColorCvtBaseTest( "color-bayer", "cvCvtColor", false, false, false ) -{ - test_array[OUTPUT].pop(); - test_array[REF_OUTPUT].pop(); - - fwd_code_str = "BayerBG2BGR"; - inv_code_str = ""; - fwd_code = CV_BayerBG2BGR; - inv_code = -1; - - default_timing_param_names = cvtcolor_bayer_param_names; - depth_list = cvtcolor_depths_8; -} - - -void CV_ColorBayerTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_ColorCvtBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - types[INPUT][0] = CV_8UC1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8UC3; - inplace = false; - - fwd_code = cvTsRandInt(rng)%4 + CV_BayerBG2BGR; -} - - -void CV_ColorBayerTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ColorCvtBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT][0] &= CV_MAT_DEPTH_MASK; -} - - -double CV_ColorBayerTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 1; -} - - -void CV_ColorBayerTest::run_func() -{ - if(!test_cpp) - cvCvtColor( test_array[INPUT][0], test_array[OUTPUT][0], fwd_code ); - else - { - cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::cvtColor(cv::cvarrToMat(test_array[INPUT][0]), _out, fwd_code, _out.channels()); - } -} - - -void CV_ColorBayerTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_OUTPUT][0]; - int i, j, cols = src->cols - 2; - int code = fwd_code; - int bi = 0; - int step = src->step; - - if( fwd_code == CV_BayerRG2BGR || fwd_code == CV_BayerGR2BGR ) - bi ^= 2; - - for( i = 1; i < src->rows - 1; i++ ) - { - const uchar* ptr = src->data.ptr + i*step + 1; - uchar* dst_row = dst->data.ptr + i*dst->step + 3; - int save_code = code; - if( cols <= 0 ) - { - dst_row[-3] = dst_row[-2] = dst_row[-1] = 0; - dst_row[cols*3] = dst_row[cols*3+1] = dst_row[cols*3+2] = 0; - continue; - } - - for( j = 0; j < cols; j++ ) - { - int b, g, r; - if( !(code & 1) ) - { - b = ptr[j]; - g = (ptr[j-1] + ptr[j+1] + ptr[j-step] + ptr[j+step])>>2; - r = (ptr[j-step-1] + ptr[j-step+1] + ptr[j+step-1] + ptr[j+step+1]) >> 2; - } - else - { - b = (ptr[j-1] + ptr[j+1]) >> 1; - g = ptr[j]; - r = (ptr[j-step] + ptr[j+step]) >> 1; - } - code ^= 1; - dst_row[j*3 + bi] = (uchar)b; - dst_row[j*3 + 1] = (uchar)g; - dst_row[j*3 + (bi^2)] = (uchar)r; - } - - dst_row[-3] = dst_row[0]; - dst_row[-2] = dst_row[1]; - dst_row[-1] = dst_row[2]; - dst_row[cols*3] = dst_row[cols*3-3]; - dst_row[cols*3+1] = dst_row[cols*3-2]; - dst_row[cols*3+2] = dst_row[cols*3-1]; - - code = save_code ^ 1; - bi ^= 2; - } - - if( src->rows <= 2 ) - { - memset( dst->data.ptr, 0, (cols+2)*3 ); - memset( dst->data.ptr + (dst->rows-1)*dst->step, 0, (cols+2)*3 ); - } - else - { - uchar* top_row = dst->data.ptr; - uchar* bottom_row = dst->data.ptr + dst->step*(dst->rows-1); - int dstep = dst->step; - - for( j = 0; j < (cols+2)*3; j++ ) - { - top_row[j] = top_row[j + dstep]; - bottom_row[j] = bottom_row[j - dstep]; - } - } -} - -CV_ColorBayerTest color_bayer_test; diff --git a/tests/cv/src/acomposeRT.cpp b/tests/cv/src/acomposeRT.cpp deleted file mode 100644 index 4d4bf4d..0000000 --- a/tests/cv/src/acomposeRT.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -using namespace cv; -using namespace std; - - -class Differential -{ -public: - typedef Mat_ mat_t; - - Differential(double eps_, const mat_t& rv1_, const mat_t& tv1_, const mat_t& rv2_, const mat_t& tv2_) - : rv1(rv1_), tv1(tv1_), rv2(rv2_), tv2(tv2_), eps(eps_), ev(3, 1) {} - - void dRv1(mat_t& dr3_dr1, mat_t& dt3_dr1) - { - dr3_dr1.create(3, 3); dt3_dr1.create(3, 3); - - for(int i = 0; i < 3; ++i) - { - ev.setTo(Scalar(0)); ev(i, 0) = eps; - - composeRT( rv1 + ev, tv1, rv2, tv2, rv3_p, tv3_p); - composeRT( rv1 - ev, tv1, rv2, tv2, rv3_m, tv3_m); - - dr3_dr1.col(i) = rv3_p - rv3_m; - dt3_dr1.col(i) = tv3_p - tv3_m; - } - dr3_dr1 /= 2 * eps; dt3_dr1 /= 2 * eps; - } - - void dRv2(mat_t& dr3_dr2, mat_t& dt3_dr2) - { - dr3_dr2.create(3, 3); dt3_dr2.create(3, 3); - - for(int i = 0; i < 3; ++i) - { - ev.setTo(Scalar(0)); ev(i, 0) = eps; - - composeRT( rv1, tv1, rv2 + ev, tv2, rv3_p, tv3_p); - composeRT( rv1, tv1, rv2 - ev, tv2, rv3_m, tv3_m); - - dr3_dr2.col(i) = rv3_p - rv3_m; - dt3_dr2.col(i) = tv3_p - tv3_m; - } - dr3_dr2 /= 2 * eps; dt3_dr2 /= 2 * eps; - } - - void dTv1(mat_t& drt3_dt1, mat_t& dt3_dt1) - { - drt3_dt1.create(3, 3); dt3_dt1.create(3, 3); - - for(int i = 0; i < 3; ++i) - { - ev.setTo(Scalar(0)); ev(i, 0) = eps; - - composeRT( rv1, tv1 + ev, rv2, tv2, rv3_p, tv3_p); - composeRT( rv1, tv1 - ev, rv2, tv2, rv3_m, tv3_m); - - drt3_dt1.col(i) = rv3_p - rv3_m; - dt3_dt1.col(i) = tv3_p - tv3_m; - } - drt3_dt1 /= 2 * eps; dt3_dt1 /= 2 * eps; - } - - void dTv2(mat_t& dr3_dt2, mat_t& dt3_dt2) - { - dr3_dt2.create(3, 3); dt3_dt2.create(3, 3); - - for(int i = 0; i < 3; ++i) - { - ev.setTo(Scalar(0)); ev(i, 0) = eps; - - composeRT( rv1, tv1, rv2, tv2 + ev, rv3_p, tv3_p); - composeRT( rv1, tv1, rv2, tv2 - ev, rv3_m, tv3_m); - - dr3_dt2.col(i) = rv3_p - rv3_m; - dt3_dt2.col(i) = tv3_p - tv3_m; - } - dr3_dt2 /= 2 * eps; dt3_dt2 /= 2 * eps; - } - -private: - const mat_t& rv1, tv1, rv2, tv2; - double eps; - Mat_ ev; - - Differential& operator=(const Differential&); - Mat rv3_m, tv3_m, rv3_p, tv3_p; -}; - -class CV_composeRT_Test : public CvTest -{ -public: - CV_composeRT_Test() - : CvTest( "composeRT", "cvComposeRT") - { - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - } - ~CV_composeRT_Test() {} -protected: - - void run(int) - { - CvTS& ts = *this->ts; - ts.set_failed_test_info(CvTS::OK); - - Mat_ rvec1(3, 1), tvec1(3, 1), rvec2(3, 1), tvec2(3, 1); - - randu(rvec1, Scalar(0), Scalar(6.29)); - randu(rvec2, Scalar(0), Scalar(6.29)); - - randu(tvec1, Scalar(-2), Scalar(2)); - randu(tvec2, Scalar(-2), Scalar(2)); - - Mat rvec3, tvec3; - composeRT(rvec1, tvec1, rvec2, tvec2, rvec3, tvec3); - - Mat rvec3_exp, tvec3_exp; - - Mat rmat1, rmat2; - Rodrigues(rvec1, rmat1); - Rodrigues(rvec2, rmat2); - Rodrigues(rmat2 * rmat1, rvec3_exp); - - tvec3_exp = rmat2 * tvec1 + tvec2; - - const double thres = 1e-5; - if (norm(rvec3_exp, rvec3) > thres || norm(tvec3_exp, tvec3) > thres) - ts.set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - - const double eps = 1e-3; - Differential diff(eps, rvec1, tvec1, rvec2, tvec2); - - Mat dr3dr1, dr3dt1, dr3dr2, dr3dt2, dt3dr1, dt3dt1, dt3dr2, dt3dt2; - - composeRT(rvec1, tvec1, rvec2, tvec2, rvec3, tvec3, - dr3dr1, dr3dt1, dr3dr2, dr3dt2, dt3dr1, dt3dt1, dt3dr2, dt3dt2); - - Mat_ dr3_dr1, dt3_dr1; - diff.dRv1(dr3_dr1, dt3_dr1); - - if (norm(dr3_dr1, dr3dr1) > thres || norm(dt3_dr1, dt3dr1) > thres) - { - ts.printf( CvTS::LOG, "Invalid derivates by r1\n" ); - ts.set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - - Mat_ dr3_dr2, dt3_dr2; - diff.dRv2(dr3_dr2, dt3_dr2); - - if (norm(dr3_dr2, dr3dr2) > thres || norm(dt3_dr2, dt3dr2) > thres) - { - ts.printf( CvTS::LOG, "Invalid derivates by r2\n" ); - ts.set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - - Mat_ dr3_dt1, dt3_dt1; - diff.dTv1(dr3_dt1, dt3_dt1); - - if (norm(dr3_dt1, dr3dt1) > thres || norm(dt3_dt1, dt3dt1) > thres) - { - ts.printf( CvTS::LOG, "Invalid derivates by t1\n" ); - ts.set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - - Mat_ dr3_dt2, dt3_dt2; - diff.dTv2(dr3_dt2, dt3_dt2); - - if (norm(dr3_dt2, dr3dt2) > thres || norm(dt3_dt2, dt3dt2) > thres) - { - ts.printf( CvTS::LOG, "Invalid derivates by t2\n" ); - ts.set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - } - } -}; - -CV_composeRT_Test composeRT_test; diff --git a/tests/cv/src/acondens.cpp b/tests/cv/src/acondens.cpp deleted file mode 100644 index 97bbdee..0000000 --- a/tests/cv/src/acondens.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -/* Testing parameters */ -static char TestName[] = "State estimation of linear system by means of ConDens Algorithm"; -static char TestClass[] = "Algorithm"; -static int Dim; -static int Steps; -static int SamplesNum; - -static int read_param = 0; -static double EPSILON = 1.000; - -static void CondProbDens(CvConDensation* CD, float* Measurement) -{ - float Prob = 1; - for(int i = 0; i < CD->SamplesNum;i++) - { - - Prob =1; - for(int j =0; j < CD->DP;j++) - { - Prob*=(float)exp(-0.05*(Measurement[j] - CD->flSamples[i][j])*(Measurement[j]-CD->flSamples[i][j])); - } - - CD->flConfidence[i] = Prob; - } - -} -static int fcaConDens( void ) -{ - AtsRandState noisegen; - AtsRandState dynam; - double Error = 0; - CvConDensation* ConDens; - - /* Initialization global parameters */ - if( !read_param ) - { - read_param = 1; - /* Reading test-parameters */ - trsiRead( &Dim,"7","Dimension of dynamical system"); - trsiRead( &Steps,"100","Length of trajectory to track"); - trsiRead( &SamplesNum,"64","Length of trajectory to track"); - } - CvMat Sample = cvMat(Dim,1,CV_MAT32F,NULL); - CvMat Temp = cvMat(Dim,1,CV_MAT32F,NULL); - CvMat LB = cvMat(Dim,1,CV_MAT32F,NULL); - CvMat UB = cvMat(Dim,1,CV_MAT32F,NULL); - cvmAlloc(&LB); - cvmAlloc(&UB); - cvmAlloc(&Sample); - cvmAlloc(&Temp); - ConDens = cvCreateConDensation(Dim, Dim,SamplesNum); - CvMat Dyn = cvMat(Dim,Dim,CV_MAT32F,ConDens->DynamMatr); - atsRandInit(&dynam,-1.0, 1.0, 1); - atsRandInit(&noisegen,-0.1, 0.1, 2); - cvmSetIdentity(&Dyn); - atsbRand32f(&dynam,Sample.data.fl,Dim); - int i; - for(i = 0; iState,Dim,EPSILON); - cvmFree(&Sample); - cvmFree(&Temp); - cvmFree(&LB); - cvmFree(&UB); - cvReleaseConDensation(&ConDens); - if(Error>=EPSILON)return TRS_FAIL; - return TRS_OK; -} /* fcaSobel8uC1R */ -void InitAConDens(void) -{ - trsReg( "Condensation Algorithm", TestName, TestClass, fcaConDens); - -} /* InitASobel */ - -/* End of file. */ - -#endif diff --git a/tests/cv/src/acontourmoments.cpp b/tests/cv/src/acontourmoments.cpp deleted file mode 100644 index 0f8771b..0000000 --- a/tests/cv/src/acontourmoments.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -/* End of file. */ - diff --git a/tests/cv/src/acontours.cpp b/tests/cv/src/acontours.cpp deleted file mode 100644 index 76eaa34..0000000 --- a/tests/cv/src/acontours.cpp +++ /dev/null @@ -1,405 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_FindContourTest : public CvTest -{ -public: - enum { NUM_IMG = 4 }; - - CV_FindContourTest(); - ~CV_FindContourTest(); - int write_default_params(CvFileStorage* fs); - void clear(); - -protected: - int read_params( CvFileStorage* fs ); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void run_func(); - - int min_blob_size, max_blob_size; - int blob_count, max_log_blob_count; - int retr_mode, approx_method; - - int min_log_img_size, max_log_img_size; - CvSize img_size; - int count, count2; - - IplImage* img[NUM_IMG]; - CvMemStorage* storage; - CvSeq *contours, *contours2, *chain; -}; - - -CV_FindContourTest::CV_FindContourTest() : - CvTest( "contour-find", "cvFindContours, cvDrawContours, cvApproxChains" ) -{ - int i; - - test_case_count = 300; - min_blob_size = 1; - max_blob_size = 50; - max_log_blob_count = 10; - - min_log_img_size = 3; - max_log_img_size = 10; - - for( i = 0; i < NUM_IMG; i++ ) - img[i] = 0; - - storage = 0; -} - - -CV_FindContourTest::~CV_FindContourTest() -{ - clear(); -} - - -void CV_FindContourTest::clear() -{ - int i; - - CvTest::clear(); - - for( i = 0; i < NUM_IMG; i++ ) - cvReleaseImage( &img[i] ); - - cvReleaseMemStorage( &storage ); -} - - -int CV_FindContourTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "min_blob_size", min_blob_size ); - write_param( fs, "max_blob_size", max_blob_size ); - write_param( fs, "max_log_blob_count", max_log_blob_count ); - write_param( fs, "min_log_img_size", min_log_img_size ); - write_param( fs, "max_log_img_size", max_log_img_size ); - } - return 0; -} - - -int CV_FindContourTest::read_params( CvFileStorage* fs ) -{ - int t; - int code = CvTest::read_params( fs ); - - if( code < 0 ) - return code; - - min_blob_size = cvReadInt( find_param( fs, "min_blob_size" ), min_blob_size ); - max_blob_size = cvReadInt( find_param( fs, "max_blob_size" ), max_blob_size ); - max_log_blob_count = cvReadInt( find_param( fs, "max_log_blob_count" ), max_log_blob_count ); - min_log_img_size = cvReadInt( find_param( fs, "min_log_img_size" ), min_log_img_size ); - max_log_img_size = cvReadInt( find_param( fs, "max_log_img_size" ), max_log_img_size ); - - min_blob_size = cvTsClipInt( min_blob_size, 1, 100 ); - max_blob_size = cvTsClipInt( max_blob_size, 1, 100 ); - - if( min_blob_size > max_blob_size ) - CV_SWAP( min_blob_size, max_blob_size, t ); - - max_log_blob_count = cvTsClipInt( max_log_blob_count, 1, 10 ); - - min_log_img_size = cvTsClipInt( min_log_img_size, 1, 10 ); - max_log_img_size = cvTsClipInt( max_log_img_size, 1, 10 ); - - if( min_log_img_size > max_log_img_size ) - CV_SWAP( min_log_img_size, max_log_img_size, t ); - - return 0; -} - - -static void -cvTsGenerateBlobImage( IplImage* img, int min_blob_size, int max_blob_size, - int blob_count, int min_brightness, int max_brightness, - CvRNG* rng ) -{ - int i; - CvSize size; - - assert( img->depth == IPL_DEPTH_8U && img->nChannels == 1 ); - - cvZero( img ); - - // keep the border clear - cvSetImageROI( img, cvRect(1,1,img->width-2,img->height-2) ); - size = cvGetSize( img ); - - for( i = 0; i < blob_count; i++ ) - { - CvPoint center; - CvSize axes; - int angle = cvTsRandInt(rng) % 180; - int brightness = cvTsRandInt(rng) % - (max_brightness - min_brightness) + min_brightness; - center.x = cvTsRandInt(rng) % size.width; - center.y = cvTsRandInt(rng) % size.height; - - axes.width = (cvTsRandInt(rng) % - (max_blob_size - min_blob_size) + min_blob_size + 1)/2; - axes.height = (cvTsRandInt(rng) % - (max_blob_size - min_blob_size) + min_blob_size + 1)/2; - - cvEllipse( img, center, axes, angle, 0, 360, cvScalar(brightness), CV_FILLED ); - } - - cvResetImageROI( img ); -} - - -static void -cvTsMarkContours( IplImage* img, int val ) -{ - int i, j; - int step = img->widthStep; - - assert( img->depth == IPL_DEPTH_8U && img->nChannels == 1 && (val&1) != 0); - - for( i = 1; i < img->height - 1; i++ ) - for( j = 1; j < img->width - 1; j++ ) - { - uchar* t = (uchar*)(img->imageData + img->widthStep*i + j); - if( *t == 1 && (t[-step] == 0 || t[-1] == 0 || t[1] == 0 || t[step] == 0)) - *t = (uchar)val; - } - - cvThreshold( img, img, val - 2, val, CV_THRESH_BINARY ); -} - - -int CV_FindContourTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - const int min_brightness = 0, max_brightness = 2; - int i, code = CvTest::prepare_test_case( test_case_idx ); - - if( code < 0 ) - return code; - - clear(); - - blob_count = cvRound(exp(cvTsRandReal(rng)*max_log_blob_count*CV_LOG2)); - - img_size.width = cvRound(exp((cvTsRandReal(rng)* - (max_log_img_size - min_log_img_size) + min_log_img_size)*CV_LOG2)); - img_size.height = cvRound(exp((cvTsRandReal(rng)* - (max_log_img_size - min_log_img_size) + min_log_img_size)*CV_LOG2)); - - approx_method = cvTsRandInt( rng ) % 4 + 1; - retr_mode = cvTsRandInt( rng ) % 4; - - storage = cvCreateMemStorage( 1 << 10 ); - - for( i = 0; i < NUM_IMG; i++ ) - img[i] = cvCreateImage( img_size, 8, 1 ); - - cvTsGenerateBlobImage( img[0], min_blob_size, max_blob_size, - blob_count, min_brightness, max_brightness, rng ); - - cvCopy( img[0], img[1] ); - cvCopy( img[0], img[2] ); - - cvTsMarkContours( img[1], 255 ); - - return 1; -} - - -void CV_FindContourTest::run_func() -{ - contours = contours2 = chain = 0; - count = cvFindContours( img[2], storage, &contours, sizeof(CvContour), retr_mode, approx_method ); - - cvZero( img[3] ); - - if( contours && retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - cvDrawContours( img[3], contours, cvScalar(255), cvScalar(255), INT_MAX, -1 ); - - cvCopy( img[0], img[2] ); - - count2 = cvFindContours( img[2], storage, &chain, sizeof(CvChain), retr_mode, CV_CHAIN_CODE ); - - if( chain ) - contours2 = cvApproxChains( chain, storage, approx_method, 0, 0, 1 ); - - cvZero( img[2] ); - - if( contours && retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - cvDrawContours( img[2], contours2, cvScalar(255), cvScalar(255), INT_MAX ); -} - - -// the whole testing is done here, run_func() is not utilized in this test -int CV_FindContourTest::validate_test_results( int /*test_case_idx*/ ) -{ - int i, code = CvTS::OK; - - cvCmpS( img[0], 0, img[0], CV_CMP_GT ); - - if( count != count2 ) - { - ts->printf( CvTS::LOG, "The number of contours retrieved with different " - "approximation methods is not the same\n" - "(%d contour(s) for method %d vs %d contour(s) for method %d)\n", - count, approx_method, count2, CV_CHAIN_CODE ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - - if( retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - { - code = cvTsCmpEps2( ts, img[0], img[3], 0, true, - "Comparing original image with the map of filled contours" ); - - if( code < 0 ) - goto _exit_; - - code = cvTsCmpEps2( ts, img[1], img[2], 0, true, - "Comparing contour outline vs manually produced edge map" ); - - if( code < 0 ) - goto _exit_; - } - - if( contours ) - { - CvTreeNodeIterator iterator1; - CvTreeNodeIterator iterator2; - int count3; - - for( i = 0; i < 2; i++ ) - { - CvTreeNodeIterator iterator; - cvInitTreeNodeIterator( &iterator, i == 0 ? contours : contours2, INT_MAX ); - - for( count3 = 0; cvNextTreeNode( &iterator ) != 0; count3++ ) - ; - - if( count3 != count ) - { - ts->printf( CvTS::LOG, - "The returned number of retrieved contours (using the approx_method = %d) does not match\n" - "to the actual number of contours in the tree/list (returned %d, actual %d)\n", - i == 0 ? approx_method : 0, count, count3 ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - - cvInitTreeNodeIterator( &iterator1, contours, INT_MAX ); - cvInitTreeNodeIterator( &iterator2, contours2, INT_MAX ); - - for( count3 = 0; count3 < count; count3++ ) - { - CvSeq* seq1 = (CvSeq*)cvNextTreeNode( &iterator1 ); - CvSeq* seq2 = (CvSeq*)cvNextTreeNode( &iterator2 ); - CvSeqReader reader1; - CvSeqReader reader2; - - if( !seq1 || !seq2 ) - { - ts->printf( CvTS::LOG, - "There are NULL pointers in the original contour tree or the " - "tree produced by cvApproxChains\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - cvStartReadSeq( seq1, &reader1 ); - cvStartReadSeq( seq2, &reader2 ); - - if( seq1->total != seq2->total ) - { - ts->printf( CvTS::LOG, - "The original contour #%d has %d points, while the corresponding contour has %d point\n", - count3, seq1->total, seq2->total ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - for( i = 0; i < seq1->total; i++ ) - { - CvPoint pt1; - CvPoint pt2; - - CV_READ_SEQ_ELEM( pt1, reader1 ); - CV_READ_SEQ_ELEM( pt2, reader2 ); - - if( pt1.x != pt2.x || pt1.y != pt2.y ) - { - ts->printf( CvTS::LOG, - "The point #%d in the contour #%d is different from the corresponding point " - "in the approximated chain ((%d,%d) vs (%d,%d)", count3, i, pt1.x, pt1.y, pt2.x, pt2.y ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - } - } - -_exit_: - if( code < 0 ) - { -#if 0 - cvNamedWindow( "test", 0 ); - cvShowImage( "test", img[0] ); - cvWaitKey(); -#endif - ts->set_failed_test_info( code ); - } - - return code; -} - - -CV_FindContourTest find_contour_test; - -/* End of file. */ diff --git a/tests/cv/src/acontoursmatch.cpp b/tests/cv/src/acontoursmatch.cpp deleted file mode 100644 index f6f21b1..0000000 --- a/tests/cv/src/acontoursmatch.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 -/*#include "conio.h"*/ - -static char cTestName[] = "Matching Contours"; -static char cTestClass[] = "Algorithm"; -static char cFuncName[] = "cvMatchContours"; - -static int aMatchContours(void) -{ - CvSeqBlock contour_blk1, contour_blk2; - CvContour contour_h1, contour_h2; - CvContoursMatchMethod method; - int nPoints1 = 20, nPoints2 = 20; - int xc,yc,a1 = 10, b1 = 20, a2 = 15, b2 =30, fi = 0; - int xmin,ymin,xmax,ymax; - int seq_type; - double error_test,rezult, eps_rez = 0.1; - double pi = 3.1415926; - int i; - int code = TRS_OK; - - int width=256,height=256; - CvPoint *cp1,*cp2; - -/* read tests params */ - - if (!trsiRead(&nPoints1,"20","Number of points first contour")) - return TRS_UNDEF; - if (!trsiRead(&nPoints2,"20","Number of points second contour")) - return TRS_UNDEF; - - if(nPoints1>0&&nPoints2>0) - { - if (!trsiRead(&a1,"10","first radius of the first elipse")) - return TRS_UNDEF; - if (!trsiRead(&b1,"20","second radius of the first elipse")) - return TRS_UNDEF; - if (!trsiRead(&a2,"15","first radius of the second elipse")) - return TRS_UNDEF; - if (!trsiRead(&b2,"30","second radius of the second elipse")) - return TRS_UNDEF; - if (!trsiRead(&fi,"0","second radius of the second elipse")) - return TRS_UNDEF; - - xc = (int)(width/2.); - yc = (int)(height/2.); - xmin = width; - ymin = height; - xmax = 0; - ymax = 0; - - cp1 = (CvPoint*) trsmAlloc(nPoints1*sizeof(CvPoint)); - cp2 = (CvPoint*) trsmAlloc(nPoints2*sizeof(CvPoint)); - - for(i=0;i cp1[i].x) xmin = cp1[i].x; - if(xmax< cp1[i].x) xmax = cp1[i].x; - if(ymin> cp1[i].y) ymin = cp1[i].y; - if(ymax< cp1[i].y) ymax = cp1[i].y; - } - - if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; - - for(i=0;i cp2[i].x) xmin = cp2[i].x; - if(xmax< cp2[i].x) xmax = cp2[i].x; - if(ymin> cp2[i].y) ymin = cp2[i].y; - if(ymax< cp2[i].y) ymax = cp2[i].y; - } - if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; - -/* contours initialazing */ - seq_type = CV_SEQ_POLYGON; - cvMakeSeqHeaderForArray( seq_type, sizeof(CvContour), sizeof(CvPoint), - (char*)cp1, nPoints1, (CvSeq*)&contour_h1, &contour_blk1); - - cvMakeSeqHeaderForArray( seq_type, sizeof(CvContour), sizeof(CvPoint), - (char*)cp2, nPoints2, (CvSeq*)&contour_h2, &contour_blk2); - -/* countours matchig */ - error_test = 0.; - - for (i=1;i<=3;i++) - { - method = (CvContoursMatchMethod)i; - rezult = cvMatchContours((CvSeq*)&contour_h1, (CvSeq*)&contour_h2, method); - - error_test+=rezult; - } - error_test = error_test/3.; - - if(error_test > eps_rez) code = TRS_FAIL; - else code = TRS_OK; - - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "contours matching error_test =%f \n", - error_test); - - trsFree (cp2); - trsFree (cp1); - } - - -/* _getch(); */ - return code; -} - -void InitAMatchContours( void ) -{ -/* Test Registartion */ - trsReg(cFuncName,cTestName,cTestClass,aMatchContours); - -} /* InitAMatchContours */ - -/* End of file. */ - -#endif - diff --git a/tests/cv/src/aconvhull.cpp b/tests/cv/src/aconvhull.cpp deleted file mode 100644 index 864a337..0000000 --- a/tests/cv/src/aconvhull.cpp +++ /dev/null @@ -1,1622 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -/*static int -cvTsPointConvexPolygon( CvPoint2D32f pt, CvPoint2D32f* v, int n ) -{ - CvPoint2D32f v0 = v[n-1]; - int i, sign = 0; - - for( i = 0; i < n; i++ ) - { - CvPoint2D32f v1 = v[i]; - float dx = pt.x - v0.x, dy = pt.y - v0.y; - float dx1 = v1.x - v0.x, dy1 = v1.y - v0.y; - double t = (double)dx*dy1 - (double)dx1*dy; - if( fabs(t) > DBL_EPSILON ) - { - if( t*sign < 0 ) - break; - if( sign == 0 ) - sign = t < 0 ? -1 : 1; - } - else if( fabs(dx) + fabs(dy) < DBL_EPSILON ) - return i+1; - v0 = v1; - } - - return i < n ? -1 : 0; -}*/ - -CV_INLINE double -cvTsDist( CvPoint2D32f a, CvPoint2D32f b ) -{ - double dx = a.x - b.x; - double dy = a.y - b.y; - return sqrt(dx*dx + dy*dy); -} - -CV_INLINE double -cvTsPtLineDist( CvPoint2D32f pt, CvPoint2D32f a, CvPoint2D32f b ) -{ - double d0 = cvTsDist( pt, a ), d1; - double dd = cvTsDist( a, b ); - if( dd < FLT_EPSILON ) - return d0; - d1 = cvTsDist( pt, b ); - dd = fabs((double)(pt.x - a.x)*(b.y - a.y) - (double)(pt.y - a.y)*(b.x - a.x))/dd; - d0 = MIN( d0, d1 ); - return MIN( d0, dd ); -} - -static double -cvTsPointPolygonTest( CvPoint2D32f pt, const CvPoint2D32f* vv, int n, int* _idx=0, int* _on_edge=0 ) -{ - int i; - CvPoint2D32f v = vv[n-1], v0; - double min_dist_num = FLT_MAX, min_dist_denom = 1; - int min_dist_idx = -1, min_on_edge = 0; - int counter = 0; - double result; - - for( i = 0; i < n; i++ ) - { - double dx, dy, dx1, dy1, dx2, dy2, dist_num, dist_denom = 1; - int on_edge = 0, idx = i; - - v0 = v; v = vv[i]; - dx = v.x - v0.x; dy = v.y - v0.y; - dx1 = pt.x - v0.x; dy1 = pt.y - v0.y; - dx2 = pt.x - v.x; dy2 = pt.y - v.y; - - if( dx2*dx + dy2*dy >= 0 ) - dist_num = dx2*dx2 + dy2*dy2; - else if( dx1*dx + dy1*dy <= 0 ) - { - dist_num = dx1*dx1 + dy1*dy1; - idx = i - 1; - if( idx < 0 ) idx = n-1; - } - else - { - dist_num = (dy1*dx - dx1*dy); - dist_num *= dist_num; - dist_denom = dx*dx + dy*dy; - on_edge = 1; - } - - if( dist_num*min_dist_denom < min_dist_num*dist_denom ) - { - min_dist_num = dist_num; - min_dist_denom = dist_denom; - min_dist_idx = idx; - min_on_edge = on_edge; - if( min_dist_num == 0 ) - break; - } - - if( (v0.y <= pt.y && v.y <= pt.y) || - (v0.y > pt.y && v.y > pt.y) || - (v0.x < pt.x && v.x < pt.x) ) - continue; - - dist_num = dy1*dx - dx1*dy; - if( dy < 0 ) - dist_num = -dist_num; - counter += dist_num > 0; - } - - result = sqrt(min_dist_num/min_dist_denom); - if( counter % 2 == 0 ) - result = -result; - - if( _idx ) - *_idx = min_dist_idx; - if( _on_edge ) - *_on_edge = min_on_edge; - - return result; -} - - -/****************************************************************************************\ -* Base class for shape descriptor tests * -\****************************************************************************************/ - -class CV_BaseShapeDescrTest : public CvTest -{ -public: - CV_BaseShapeDescrTest( const char* test_name, const char* test_funcs ); - virtual ~CV_BaseShapeDescrTest(); - void clear(); - int write_default_params(CvFileStorage* fs); - -protected: - int read_params( CvFileStorage* fs ); - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - virtual void generate_point_set( void* points ); - virtual void extract_points(); - - int min_log_size; - int max_log_size; - int dims; - bool enable_flt_points; - - CvMemStorage* storage; - CvSeq* points1; - CvMat* points2; - void* points; - void* result; - double low_high_range; - CvScalar low, high; - - bool test_cpp; -}; - - -CV_BaseShapeDescrTest::CV_BaseShapeDescrTest( const char* test_name, const char* test_funcs ): - CvTest( test_name, test_funcs ) -{ - points1 = 0; - points2 = 0; - points = 0; - storage = 0; - test_case_count = 500; - min_log_size = 0; - max_log_size = 10; - low = high = cvScalarAll(0); - low_high_range = 50; - dims = 2; - enable_flt_points = true; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - - test_cpp = false; -} - - -CV_BaseShapeDescrTest::~CV_BaseShapeDescrTest() -{ - clear(); -} - - -void CV_BaseShapeDescrTest::clear() -{ - CvTest::clear(); - cvReleaseMemStorage( &storage ); - cvReleaseMat( &points2 ); - points1 = 0; - points = 0; -} - - -int CV_BaseShapeDescrTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "min_log_size", min_log_size ); - write_param( fs, "max_log_size", max_log_size ); - } - return 0; -} - - -int CV_BaseShapeDescrTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "struct_count" ), test_case_count ); - min_log_size = cvReadInt( find_param( fs, "min_log_size" ), min_log_size ); - max_log_size = cvReadInt( find_param( fs, "max_log_size" ), max_log_size ); - - min_log_size = cvTsClipInt( min_log_size, 0, 8 ); - max_log_size = cvTsClipInt( max_log_size, 0, 10 ); - if( min_log_size > max_log_size ) - { - int t; - CV_SWAP( min_log_size, max_log_size, t ); - } - - return 0; -} - - -void CV_BaseShapeDescrTest::generate_point_set( void* points ) -{ - CvRNG* rng = ts->get_rng(); - int i, k, n, total, point_type; - CvSeqReader reader; - uchar* data = 0; - double a[4], b[4]; - - for( k = 0; k < 4; k++ ) - { - a[k] = high.val[k] - low.val[k]; - b[k] = low.val[k]; - } - memset( &reader, 0, sizeof(reader) ); - - if( CV_IS_SEQ(points) ) - { - CvSeq* ptseq = (CvSeq*)points; - total = ptseq->total; - point_type = CV_SEQ_ELTYPE(ptseq); - cvStartReadSeq( ptseq, &reader ); - } - else - { - CvMat* ptm = (CvMat*)points; - assert( CV_IS_MAT(ptm) && CV_IS_MAT_CONT(ptm->type) ); - total = ptm->rows + ptm->cols - 1; - point_type = CV_MAT_TYPE(ptm->type); - data = ptm->data.ptr; - } - - n = CV_MAT_CN(point_type); - point_type = CV_MAT_DEPTH(point_type); - - assert( (point_type == CV_32S || point_type == CV_32F) && n <= 4 ); - - for( i = 0; i < total; i++ ) - { - int* pi; - float* pf; - if( reader.ptr ) - { - pi = (int*)reader.ptr; - pf = (float*)reader.ptr; - CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader ); - } - else - { - pi = (int*)data + i*n; - pf = (float*)data + i*n; - } - if( point_type == CV_32S ) - for( k = 0; k < n; k++ ) - pi[k] = cvRound(cvTsRandReal(rng)*a[k] + b[k]); - else - for( k = 0; k < n; k++ ) - pf[k] = (float)(cvTsRandReal(rng)*a[k] + b[k]); - } -} - - -int CV_BaseShapeDescrTest::prepare_test_case( int test_case_idx ) -{ - int size; - int use_storage = 0; - int point_type; - int i; - CvRNG* rng = ts->get_rng(); - - CvTest::prepare_test_case( test_case_idx ); - - clear(); - size = cvRound( exp((cvTsRandReal(rng) * (max_log_size - min_log_size) + min_log_size)*CV_LOG2) ); - use_storage = cvTsRandInt(rng) % 2; - point_type = CV_MAKETYPE(cvTsRandInt(rng) % - (enable_flt_points ? 2 : 1) ? CV_32F : CV_32S, dims); - - if( use_storage ) - { - storage = cvCreateMemStorage( (cvTsRandInt(rng)%10 + 1)*1024 ); - points1 = cvCreateSeq( point_type, sizeof(CvSeq), CV_ELEM_SIZE(point_type), storage ); - cvSeqPushMulti( points1, 0, size ); - points = points1; - } - else - { - int rows = 1, cols = size; - if( cvTsRandInt(rng) % 2 ) - rows = size, cols = 1; - - points2 = cvCreateMat( rows, cols, point_type ); - points = points2; - } - - for( i = 0; i < 4; i++ ) - { - low.val[i] = (cvTsRandReal(rng)-0.5)*low_high_range*2; - high.val[i] = (cvTsRandReal(rng)-0.5)*low_high_range*2; - if( low.val[i] > high.val[i] ) - { - double t; - CV_SWAP( low.val[i], high.val[i], t ); - } - if( high.val[i] < low.val[i] + 1 ) - high.val[i] += 1; - } - - generate_point_set( points ); - - test_cpp = (cvTsRandInt(rng) & 16) == 0; - return 1; -} - - -void CV_BaseShapeDescrTest::extract_points() -{ - if( points1 ) - { - points2 = cvCreateMat( 1, points1->total, CV_SEQ_ELTYPE(points1) ); - cvCvtSeqToArray( points1, points2->data.ptr ); - } - - if( CV_MAT_DEPTH(points2->type) != CV_32F && enable_flt_points ) - { - CvMat tmp = cvMat( points2->rows, points2->cols, - (points2->type & ~CV_MAT_DEPTH_MASK) | CV_32F, points2->data.ptr ); - cvConvert( points2, &tmp ); - } -} - - -void CV_BaseShapeDescrTest::run_func(void) -{ -} - - -int CV_BaseShapeDescrTest::validate_test_results( int /*test_case_idx*/ ) -{ - extract_points(); - return 0; -} - - -CV_BaseShapeDescrTest shape_basetest( "shape", "" ); - - -/****************************************************************************************\ -* Convex Hull Test * -\****************************************************************************************/ - -class CV_ConvHullTest : public CV_BaseShapeDescrTest -{ -public: - CV_ConvHullTest(); - virtual ~CV_ConvHullTest(); - void clear(); - -protected: - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - - CvSeq* hull1; - CvMat* hull2; - void* hull_storage; - int orientation; - int return_points; -}; - - -CV_ConvHullTest::CV_ConvHullTest(): - CV_BaseShapeDescrTest( "shape-convhull", "cvConvexHull2" ) -{ - hull1 = 0; - hull2 = 0; - hull_storage = 0; - orientation = return_points = 0; -} - - -CV_ConvHullTest::~CV_ConvHullTest() -{ - clear(); -} - - -void CV_ConvHullTest::clear() -{ - CV_BaseShapeDescrTest::clear(); - cvReleaseMat( &hull2 ); - hull1 = 0; - hull_storage = 0; -} - - -int CV_ConvHullTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - int use_storage_for_hull = 0; - CvRNG* rng = ts->get_rng(); - - if( code <= 0 ) - return code; - - orientation = cvTsRandInt(rng) % 2 ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE; - return_points = cvTsRandInt(rng) % 2; - - use_storage_for_hull = (cvTsRandInt(rng) % 2) && !test_cpp; - if( use_storage_for_hull ) - { - if( !storage ) - storage = cvCreateMemStorage( (cvTsRandInt(rng)%10 + 1)*1024 ); - hull_storage = storage; - } - else - { - int rows, cols; - int sz = points1 ? points1->total : points2->cols + points2->rows - 1; - int point_type = points1 ? CV_SEQ_ELTYPE(points1) : CV_MAT_TYPE(points2->type); - - if( cvTsRandInt(rng) % 2 ) - rows = sz, cols = 1; - else - rows = 1, cols = sz; - - hull2 = cvCreateMat( rows, cols, return_points ? point_type : CV_32SC1 ); - hull_storage = hull2; - } - - return code; -} - - -void CV_ConvHullTest::run_func() -{ - if(!test_cpp) - hull1 = cvConvexHull2( points, hull_storage, orientation, return_points ); - else - { - cv::Mat _points = cv::cvarrToMat(points); - bool clockwise = orientation == CV_CLOCKWISE; - size_t n = 0; - if( !return_points ) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - else if(_points.type() == CV_32SC2) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - else if(_points.type() == CV_32FC2) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - if(hull2->rows > hull2->cols) - hull2->rows = (int)n; - else - hull2->cols = (int)n; - } -} - - -int CV_ConvHullTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - CvMat* hull = 0; - CvMat* mask = 0; - int i, point_count, hull_count; - CvPoint2D32f *p, *h; - CvSeq header, hheader, *ptseq, *hseq; - CvSeqBlock block, hblock; - - if( points1 ) - ptseq = points1; - else - ptseq = cvMakeSeqHeaderForArray( CV_MAT_TYPE(points2->type), - sizeof(CvSeq), CV_ELEM_SIZE(points2->type), points2->data.ptr, - points2->rows + points2->cols - 1, &header, &block ); - point_count = ptseq->total; - p = (CvPoint2D32f*)(points2->data.ptr); - - if( hull1 ) - hseq = hull1; - else - hseq = cvMakeSeqHeaderForArray( CV_MAT_TYPE(hull2->type), - sizeof(CvSeq), CV_ELEM_SIZE(hull2->type), hull2->data.ptr, - hull2->rows + hull2->cols - 1, &hheader, &hblock ); - hull_count = hseq->total; - hull = cvCreateMat( 1, hull_count, CV_32FC2 ); - mask = cvCreateMat( 1, hull_count, CV_8UC1 ); - cvZero( mask ); - h = (CvPoint2D32f*)(hull->data.ptr); - - // extract convex hull points - if( return_points ) - { - cvCvtSeqToArray( hseq, hull->data.ptr ); - if( CV_SEQ_ELTYPE(hseq) != CV_32FC2 ) - { - CvMat tmp = cvMat( hull->rows, hull->cols, CV_32SC2, hull->data.ptr ); - cvConvert( &tmp, hull ); - } - } - else - { - CvSeqReader reader; - cvStartReadSeq( hseq, &reader ); - - for( i = 0; i < hull_count; i++ ) - { - schar* ptr = reader.ptr; - int idx; - CV_NEXT_SEQ_ELEM( hseq->elem_size, reader ); - - if( hull1 ) - idx = cvSeqElemIdx( ptseq, *(uchar**)ptr ); - else - idx = *(int*)ptr; - - if( idx < 0 || idx >= point_count ) - { - ts->printf( CvTS::LOG, "Invalid convex hull point #%d\n", i ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - h[i] = p[idx]; - } - } - - // check that the convex hull is a convex polygon - if( hull_count >= 3 ) - { - CvPoint2D32f pt0 = h[hull_count-1]; - for( i = 0; i < hull_count; i++ ) - { - int j = i+1; - CvPoint2D32f pt1 = h[i], pt2 = h[j < hull_count ? j : 0]; - float dx0 = pt1.x - pt0.x, dy0 = pt1.y - pt0.y; - float dx1 = pt2.x - pt1.x, dy1 = pt2.y - pt1.y; - double t = (double)dx0*dy1 - (double)dx1*dy0; - if( (t < 0) ^ (orientation != CV_COUNTER_CLOCKWISE) ) - { - ts->printf( CvTS::LOG, "The convex hull is not convex or has a wrong orientation (vtx %d)\n", i ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - pt0 = pt1; - } - } - - // check that all the points are inside the hull or on the hull edge - // and at least hull_point points are at the hull vertices - for( i = 0; i < point_count; i++ ) - { - int idx = 0, on_edge = 0; - double result = cvTsPointPolygonTest( p[i], h, hull_count, &idx, &on_edge ); - - if( result < 0 ) - { - ts->printf( CvTS::LOG, "The point #%d is outside of the convex hull\n", i ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( result < FLT_EPSILON && !on_edge ) - mask->data.ptr[idx] = (uchar)1; - } - - if( cvNorm( mask, 0, CV_L1 ) != hull_count ) - { - ts->printf( CvTS::LOG, "Not every convex hull vertex coincides with some input point\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - cvReleaseMat( &hull ); - cvReleaseMat( &mask ); - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_ConvHullTest shape_convhull_test; - - -/****************************************************************************************\ -* MinAreaRect Test * -\****************************************************************************************/ - -class CV_MinAreaRectTest : public CV_BaseShapeDescrTest -{ -public: - CV_MinAreaRectTest(); - -protected: - void run_func(void); - int validate_test_results( int test_case_idx ); - - CvBox2D box; - CvPoint2D32f box_pt[4]; -}; - - -CV_MinAreaRectTest::CV_MinAreaRectTest(): - CV_BaseShapeDescrTest( "shape-minarearect", "cvMinAreaRect2, cvBoxPoints" ) -{ -} - - -void CV_MinAreaRectTest::run_func() -{ - if(!test_cpp) - { - box = cvMinAreaRect2( points, storage ); - cvBoxPoints( box, box_pt ); - } - else - { - cv::RotatedRect r = cv::minAreaRect(cv::cvarrToMat(points)); - box = (CvBox2D)r; - r.points((cv::Point2f*)box_pt); - } -} - - -int CV_MinAreaRectTest::validate_test_results( int test_case_idx ) -{ - double eps = 1e-1; - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, j, point_count = points2->rows + points2->cols - 1; - CvPoint2D32f *p = (CvPoint2D32f*)(points2->data.ptr); - int mask[] = {0,0,0,0}; - - // check that the bounding box is a rotated rectangle: - // 1. diagonals should be equal - // 2. they must intersect in their middle points - { - double d0 = cvTsDist( box_pt[0], box_pt[2] ); - double d1 = cvTsDist( box_pt[1], box_pt[3] ); - - double x0 = (box_pt[0].x + box_pt[2].x)*0.5; - double y0 = (box_pt[0].y + box_pt[2].y)*0.5; - double x1 = (box_pt[1].x + box_pt[3].x)*0.5; - double y1 = (box_pt[1].y + box_pt[3].y)*0.5; - - if( fabs(d0 - d1) + fabs(x0 - x1) + fabs(y0 - y1) > eps*MAX(d0,d1) ) - { - ts->printf( CvTS::LOG, "The bounding box is not a rectangle\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - -#if 0 - { - int n = 4; - double a = 8, c = 8, b = 100, d = 150; - CvPoint bp[4], *bpp = bp; - cvNamedWindow( "test", 1 ); - IplImage* img = cvCreateImage( cvSize(500,500), 8, 3 ); - cvZero(img); - for( i = 0; i < point_count; i++ ) - cvCircle(img,cvPoint(cvRound(p[i].x*a+b),cvRound(p[i].y*c+d)), 3, CV_RGB(0,255,0), -1 ); - for( i = 0; i < n; i++ ) - bp[i] = cvPoint(cvRound(box_pt[i].x*a+b),cvRound(box_pt[i].y*c+d)); - cvPolyLine( img, &bpp, &n, 1, 1, CV_RGB(255,255,0), 1, CV_AA, 0 ); - cvShowImage( "test", img ); - cvWaitKey(); - cvReleaseImage(&img); - } -#endif - - // check that the box includes all the points - // and there is at least one point at (or very close to) every box side - for( i = 0; i < point_count; i++ ) - { - int idx = 0, on_edge = 0; - double result = cvTsPointPolygonTest( p[i], box_pt, 4, &idx, &on_edge ); - if( result < -eps ) - { - ts->printf( CvTS::LOG, "The point #%d is outside of the box\n", i ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( result < eps ) - { - for( j = 0; j < 4; j++ ) - { - double d = cvTsPtLineDist( p[i], box_pt[(j-1)&3], box_pt[j] ); - if( d < eps ) - mask[j] = (uchar)1; - } - } - } - - if( mask[0] + mask[1] + mask[2] + mask[3] != 4 ) - { - ts->printf( CvTS::LOG, "Not every box side has a point nearby\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_MinAreaRectTest shape_minarearect_test; - - -/****************************************************************************************\ -* MinEnclosingCircle Test * -\****************************************************************************************/ - -class CV_MinCircleTest : public CV_BaseShapeDescrTest -{ -public: - CV_MinCircleTest(); - -protected: - void run_func(void); - int validate_test_results( int test_case_idx ); - - CvPoint2D32f center; - float radius; -}; - - -CV_MinCircleTest::CV_MinCircleTest(): - CV_BaseShapeDescrTest( "shape-mincircle", "cvMinEnclosingCircle" ) -{ -} - - -void CV_MinCircleTest::run_func() -{ - if(!test_cpp) - cvMinEnclosingCircle( points, ¢er, &radius ); - else - cv::minEnclosingCircle(cv::cvarrToMat(points), (cv::Point2f&)center, radius); -} - - -int CV_MinCircleTest::validate_test_results( int test_case_idx ) -{ - double eps = 1.03; - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, j = 0, point_count = points2->rows + points2->cols - 1; - CvPoint2D32f *p = (CvPoint2D32f*)(points2->data.ptr); - CvPoint2D32f v[3]; - -#if 0 - { - double a = 2, b = 200, d = 400; - cvNamedWindow( "test", 1 ); - IplImage* img = cvCreateImage( cvSize(500,500), 8, 3 ); - cvZero(img); - for( i = 0; i < point_count; i++ ) - cvCircle(img,cvPoint(cvRound(p[i].x*a+b),cvRound(p[i].y*a+d)), 3, CV_RGB(0,255,0), -1 ); - cvCircle( img, cvPoint(cvRound(center.x*a+b),cvRound(center.y*a+d)), - cvRound(radius*a), CV_RGB(255,255,0), 1 ); - cvShowImage( "test", img ); - cvWaitKey(); - cvReleaseImage(&img); - } -#endif - - // check that the circle contains all the points inside and - // remember at most 3 points that are close to the boundary - for( i = 0; i < point_count; i++ ) - { - double d = cvTsDist( p[i], center ); - if( d > radius ) - { - ts->printf( CvTS::LOG, "The point #%d is outside of the circle\n", i ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - if( radius - d < eps*radius && j < 3 ) - v[j++] = p[i]; - } - - if( point_count >= 2 && (j < 2 || (j == 2 && cvTsDist(v[0],v[1]) < (radius-1)*2/eps)) ) - { - ts->printf( CvTS::LOG, - "There should be at at least 3 points near the circle boundary or 2 points on the diameter\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_MinCircleTest shape_mincircle_test; - - -/****************************************************************************************\ -* Perimeter Test * -\****************************************************************************************/ - -class CV_PerimeterTest : public CV_BaseShapeDescrTest -{ -public: - CV_PerimeterTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvSlice slice; - int is_closed; - double result; -}; - - -CV_PerimeterTest::CV_PerimeterTest(): - CV_BaseShapeDescrTest( "shape-perimeter", "cvArcLength" ) -{ -} - - -int CV_PerimeterTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - CvRNG* rng = ts->get_rng(); - int total; - - if( code < 0 ) - return code; - - is_closed = cvTsRandInt(rng) % 2; - - if( points1 ) - { - points1->flags |= CV_SEQ_KIND_CURVE; - if( is_closed ) - points1->flags |= CV_SEQ_FLAG_CLOSED; - total = points1->total; - } - else - total = points2->cols + points2->rows - 1; - - if( (cvTsRandInt(rng) % 3) && !test_cpp ) - { - slice.start_index = cvTsRandInt(rng) % total; - slice.end_index = cvTsRandInt(rng) % total; - } - else - slice = CV_WHOLE_SEQ; - - return 1; -} - - -void CV_PerimeterTest::run_func() -{ - if(!test_cpp) - result = cvArcLength( points, slice, points1 ? -1 : is_closed ); - else - result = cv::arcLength(cv::cvarrToMat(points), - !points1 ? is_closed != 0 : (points1->flags & CV_SEQ_FLAG_CLOSED) != 0); -} - - -int CV_PerimeterTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, len = slice.end_index - slice.start_index, total = points2->cols + points2->rows - 1; - double result0 = 0; - CvPoint2D32f prev_pt, pt, *ptr; - - if( len < 0 ) - len += total; - - len = MIN( len, total ); - len -= !is_closed && len == total; - - ptr = (CvPoint2D32f*)points2->data.fl; - prev_pt = ptr[slice.start_index % total]; - - for( i = 1; i <= len; i++ ) - { - pt = ptr[(i + slice.start_index) % total]; - double dx = pt.x - prev_pt.x, dy = pt.y - prev_pt.y; - result0 += sqrt(dx*dx + dy*dy); - prev_pt = pt; - } - - if( cvIsNaN(result) || cvIsInf(result) ) - { - ts->printf( CvTS::LOG, "cvArcLength() returned invalid value (%g)\n", result ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - else if( fabs(result - result0) > FLT_EPSILON*100*result0 ) - { - ts->printf( CvTS::LOG, "The function returned %g, while the correct result is %g\n", result, result0 ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_PerimeterTest shape_perimeter_test; - - - -/****************************************************************************************\ -* FitEllipse Test * -\****************************************************************************************/ - -class CV_FitEllipseTest : public CV_BaseShapeDescrTest -{ -public: - CV_FitEllipseTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void generate_point_set( void* points ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvBox2D box0, box; - double min_ellipse_size, max_noise; -}; - - -CV_FitEllipseTest::CV_FitEllipseTest(): - CV_BaseShapeDescrTest( "shape-fit-ellipse", "cvFitEllipse" ) -{ - min_log_size = 5; // for robust ellipse fitting a dozen of points is needed at least - max_log_size = 10; - min_ellipse_size = 10; - max_noise = 0.05; -} - - -void CV_FitEllipseTest::generate_point_set( void* points ) -{ - CvRNG* rng = ts->get_rng(); - int i, total, point_type; - CvSeqReader reader; - uchar* data = 0; - double a, b; - - box0.center.x = (float)((low.val[0] + high.val[0])*0.5); - box0.center.y = (float)((low.val[1] + high.val[1])*0.5); - box0.size.width = (float)(MAX(high.val[0] - low.val[0], min_ellipse_size)*2); - box0.size.height = (float)(MAX(high.val[1] - low.val[1], min_ellipse_size)*2); - box0.angle = (float)(cvTsRandReal(rng)*180); - a = cos(box0.angle*CV_PI/180.); - b = sin(box0.angle*CV_PI/180.); - - if( box0.size.width > box0.size.height ) - { - float t; - CV_SWAP( box0.size.width, box0.size.height, t ); - } - memset( &reader, 0, sizeof(reader) ); - - if( CV_IS_SEQ(points) ) - { - CvSeq* ptseq = (CvSeq*)points; - total = ptseq->total; - point_type = CV_SEQ_ELTYPE(ptseq); - cvStartReadSeq( ptseq, &reader ); - } - else - { - CvMat* ptm = (CvMat*)points; - assert( CV_IS_MAT(ptm) && CV_IS_MAT_CONT(ptm->type) ); - total = ptm->rows + ptm->cols - 1; - point_type = CV_MAT_TYPE(ptm->type); - data = ptm->data.ptr; - } - - assert( point_type == CV_32SC2 || point_type == CV_32FC2 ); - - for( i = 0; i < total; i++ ) - { - CvPoint* pp; - CvPoint2D32f p; - double angle = cvTsRandReal(rng)*CV_PI*2; - double x = box0.size.height*0.5*(cos(angle) + (cvTsRandReal(rng)-0.5)*2*max_noise); - double y = box0.size.width*0.5*(sin(angle) + (cvTsRandReal(rng)-0.5)*2*max_noise); - p.x = (float)(box0.center.x + a*x + b*y); - p.y = (float)(box0.center.y - b*x + a*y); - - if( reader.ptr ) - { - pp = (CvPoint*)reader.ptr; - CV_NEXT_SEQ_ELEM( sizeof(*pp), reader ); - } - else - pp = ((CvPoint*)data) + i; - if( point_type == CV_32SC2 ) - { - pp->x = cvRound(p.x); - pp->y = cvRound(p.y); - } - else - *(CvPoint2D32f*)pp = p; - } -} - - -int CV_FitEllipseTest::prepare_test_case( int test_case_idx ) -{ - min_log_size = MAX(min_log_size,4); - max_log_size = MAX(min_log_size,max_log_size); - return CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); -} - - -void CV_FitEllipseTest::run_func() -{ - if(!test_cpp) - box = cvFitEllipse2( points ); - else - box = (CvBox2D)cv::fitEllipse(cv::cvarrToMat(points)); -} - - -int CV_FitEllipseTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - double diff_angle; - - if( cvIsNaN(box.center.x) || cvIsInf(box.center.x) || - cvIsNaN(box.center.y) || cvIsInf(box.center.y) || - cvIsNaN(box.size.width) || cvIsInf(box.size.width) || - cvIsNaN(box.size.height) || cvIsInf(box.size.height) || - cvIsNaN(box.angle) || cvIsInf(box.angle) ) - { - ts->printf( CvTS::LOG, "Some of the computed ellipse parameters are invalid (x=%g,y=%g,w=%g,h=%g,angle=%g)\n", - box.center.x, box.center.y, box.size.width, box.size.height, box.angle ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - box.angle = (float)(90-box.angle); - if( box.angle < 0 ) - box.angle += 360; - if( box.angle > 360 ) - box.angle -= 360; - - if( fabs(box.center.x - box0.center.x) > 3 || - fabs(box.center.y - box0.center.y) > 3 || - fabs(box.size.width - box0.size.width) > 0.1*fabs(box0.size.width) || - fabs(box.size.height - box0.size.height) > 0.1*fabs(box0.size.height) ) - { - ts->printf( CvTS::LOG, "The computed ellipse center and/or size are incorrect:\n\t" - "(x=%.1f,y=%.1f,w=%.1f,h=%.1f), while it should be (x=%.1f,y=%.1f,w=%.1f,h=%.1f)\n", - box.center.x, box.center.y, box.size.width, box.size.height, - box0.center.x, box0.center.y, box0.size.width, box0.size.height ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - diff_angle = fabs(box0.angle - box.angle); - diff_angle = MIN( diff_angle, fabs(diff_angle - 360)); - diff_angle = MIN( diff_angle, fabs(diff_angle - 180)); - - if( box0.size.height >= 1.3*box0.size.width && diff_angle > 30 ) - { - ts->printf( CvTS::LOG, "Incorrect ellipse angle (=%1.f, should be %1.f)\n", - box.angle, box0.angle ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - -#if 0 - cvNamedWindow( "test", 0 ); - IplImage* img = cvCreateImage( cvSize(cvRound(low_high_range*4), - cvRound(low_high_range*4)), 8, 3 ); - cvZero( img ); - - box.center.x += (float)low_high_range*2; - box.center.y += (float)low_high_range*2; - cvEllipseBox( img, box, CV_RGB(255,0,0), 3, 8 ); - - for( int i = 0; i < points2->rows + points2->cols - 1; i++ ) - { - CvPoint pt; - pt.x = cvRound(points2->data.fl[i*2] + low_high_range*2); - pt.y = cvRound(points2->data.fl[i*2+1] + low_high_range*2); - cvCircle( img, pt, 1, CV_RGB(255,255,255), -1, 8 ); - } - - cvShowImage( "test", img ); - cvReleaseImage( &img ); - cvWaitKey(0); -#endif - - if( code < 0 ) - { - ts->set_failed_test_info( code ); - } - return code; -} - - -CV_FitEllipseTest fit_ellipse_test; - - - -/****************************************************************************************\ -* FitLine Test * -\****************************************************************************************/ - -class CV_FitLineTest : public CV_BaseShapeDescrTest -{ -public: - CV_FitLineTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void generate_point_set( void* points ); - void run_func(void); - int validate_test_results( int test_case_idx ); - double max_noise; - float line[6], line0[6]; - int dist_type; - double reps, aeps; -}; - - -CV_FitLineTest::CV_FitLineTest(): - CV_BaseShapeDescrTest( "shape-fit-line", "cvFitLine" ) -{ - min_log_size = 5; // for robust ellipse fitting a dozen of points is needed at least - max_log_size = 10; - max_noise = 0.05; -} - - -void CV_FitLineTest::generate_point_set( void* points ) -{ - CvRNG* rng = ts->get_rng(); - int i, k, n, total, point_type; - CvSeqReader reader; - uchar* data = 0; - double s = 0; - - n = dims; - for( k = 0; k < n; k++ ) - { - line0[k+n] = (float)((low.val[k] + high.val[k])*0.5); - line0[k] = (float)(high.val[k] - low.val[k]); - if( cvTsRandInt(rng) % 2 ) - line0[k] = -line0[k]; - s += (double)line0[k]*line0[k]; - } - - s = 1./sqrt(s); - for( k = 0; k < n; k++ ) - line0[k] = (float)(line0[k]*s); - - memset( &reader, 0, sizeof(reader) ); - - if( CV_IS_SEQ(points) ) - { - CvSeq* ptseq = (CvSeq*)points; - total = ptseq->total; - point_type = CV_MAT_DEPTH(CV_SEQ_ELTYPE(ptseq)); - cvStartReadSeq( ptseq, &reader ); - } - else - { - CvMat* ptm = (CvMat*)points; - assert( CV_IS_MAT(ptm) && CV_IS_MAT_CONT(ptm->type) ); - total = ptm->rows + ptm->cols - 1; - point_type = CV_MAT_DEPTH(CV_MAT_TYPE(ptm->type)); - data = ptm->data.ptr; - } - - for( i = 0; i < total; i++ ) - { - int* pi; - float* pf; - float p[4], t; - if( reader.ptr ) - { - pi = (int*)reader.ptr; - pf = (float*)reader.ptr; - CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader ); - } - else - { - pi = (int*)data + i*n; - pf = (float*)data + i*n; - } - - t = (float)((cvTsRandReal(rng)-0.5)*low_high_range*2); - - for( k = 0; k < n; k++ ) - p[k] = (float)((cvTsRandReal(rng)-0.5)*max_noise*2 + t*line0[k] + line0[k+n]); - - if( point_type == CV_32S ) - for( k = 0; k < n; k++ ) - pi[k] = cvRound(p[k]); - else - for( k = 0; k < n; k++ ) - pf[k] = p[k]; - } -} - - -int CV_FitLineTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - dims = cvTsRandInt(rng) % 2 + 2; - min_log_size = MAX(min_log_size,5); - max_log_size = MAX(min_log_size,max_log_size); - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - dist_type = cvTsRandInt(rng) % 6 + 1; - dist_type += dist_type == CV_DIST_C; - reps = 0.1; aeps = 0.01; - return code; -} - - -void CV_FitLineTest::run_func() -{ - if(!test_cpp) - cvFitLine( points, dist_type, 0, reps, aeps, line ); - else if(dims == 2) - cv::fitLine(cv::cvarrToMat(points), (cv::Vec4f&)line[0], dist_type, 0, reps, aeps); - else - cv::fitLine(cv::cvarrToMat(points), (cv::Vec6f&)line[0], dist_type, 0, reps, aeps); -} - - -int CV_FitLineTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int k, max_k = 0; - double vec_diff = 0, t; - - for( k = 0; k < dims*2; k++ ) - { - if( cvIsNaN(line[k]) || cvIsInf(line[k]) ) - { - ts->printf( CvTS::LOG, "Some of the computed line parameters are invalid (line[%d]=%g)\n", - k, line[k] ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - - if( fabs(line0[1]) > fabs(line0[0]) ) - max_k = 1; - if( fabs(line0[dims-1]) > fabs(line0[max_k]) ) - max_k = dims-1; - if( line0[max_k] < 0 ) - for( k = 0; k < dims; k++ ) - line0[k] = -line0[k]; - if( line[max_k] < 0 ) - for( k = 0; k < dims; k++ ) - line[k] = -line[k]; - - for( k = 0; k < dims; k++ ) - { - double dt = line[k] - line0[k]; - vec_diff += dt*dt; - } - - if( sqrt(vec_diff) > 0.05 ) - { - if( dims == 2 ) - ts->printf( CvTS::LOG, - "The computed line vector (%.2f,%.2f) is different from the actual (%.2f,%.2f)\n", - line[0], line[1], line0[0], line0[1] ); - else - ts->printf( CvTS::LOG, - "The computed line vector (%.2f,%.2f,%.2f) is different from the actual (%.2f,%.2f,%.2f)\n", - line[0], line[1], line[2], line0[0], line0[1], line0[2] ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - t = (line[max_k+dims] - line0[max_k+dims])/line0[max_k]; - for( k = 0; k < dims; k++ ) - { - double p = line0[k+dims] + t*line0[k] - line[k+dims]; - vec_diff += p*p; - } - - if( sqrt(vec_diff) > 1*MAX(fabs(t),1) ) - { - if( dims == 2 ) - ts->printf( CvTS::LOG, - "The computed line point (%.2f,%.2f) is too far from the actual line\n", - line[2]+line0[2], line[3]+line0[3] ); - else - ts->printf( CvTS::LOG, - "The computed line point (%.2f,%.2f,%.2f) is too far from the actual line\n", - line[3]+line0[3], line[4]+line0[4], line[5]+line0[5] ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( code < 0 ) - { - ts->set_failed_test_info( code ); - } - return code; -} - - -CV_FitLineTest fit_line_test; - - -/****************************************************************************************\ -* ContourMoments Test * -\****************************************************************************************/ - - -static void -cvTsGenerateTousledBlob( CvPoint2D32f center, CvSize2D32f axes, - double max_r_scale, double angle, CvArr* points, CvRNG* rng ) -{ - int i, total, point_type; - uchar* data = 0; - CvSeqReader reader; - memset( &reader, 0, sizeof(reader) ); - - if( CV_IS_SEQ(points) ) - { - CvSeq* ptseq = (CvSeq*)points; - total = ptseq->total; - point_type = CV_SEQ_ELTYPE(ptseq); - cvStartReadSeq( ptseq, &reader ); - } - else - { - CvMat* ptm = (CvMat*)points; - assert( CV_IS_MAT(ptm) && CV_IS_MAT_CONT(ptm->type) ); - total = ptm->rows + ptm->cols - 1; - point_type = CV_MAT_TYPE(ptm->type); - data = ptm->data.ptr; - } - - assert( point_type == CV_32SC2 || point_type == CV_32FC2 ); - - for( i = 0; i < total; i++ ) - { - CvPoint* pp; - CvPoint2D32f p; - - double phi0 = 2*CV_PI*i/total; - double phi = CV_PI*angle/180.; - double t = cvTsRandReal(rng)*max_r_scale + (1 - max_r_scale); - double ta = axes.height*t; - double tb = axes.width*t; - double c0 = cos(phi0)*ta, s0 = sin(phi0)*tb; - double c = cos(phi), s = sin(phi); - p.x = (float)(c0*c - s0*s + center.x); - p.y = (float)(c0*s + s0*c + center.y); - - if( reader.ptr ) - { - pp = (CvPoint*)reader.ptr; - CV_NEXT_SEQ_ELEM( sizeof(*pp), reader ); - } - else - pp = ((CvPoint*)data) + i; - - if( point_type == CV_32SC2 ) - { - pp->x = cvRound(p.x); - pp->y = cvRound(p.y); - } - else - *(CvPoint2D32f*)pp = p; - } -} - - -class CV_ContourMomentsTest : public CV_BaseShapeDescrTest -{ -public: - CV_ContourMomentsTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void generate_point_set( void* points ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvMoments moments0, moments; - double area0, area; - CvSize2D32f axes; - CvPoint2D32f center; - int max_max_r_scale; - double max_r_scale, angle; - CvSize img_size; -}; - - -CV_ContourMomentsTest::CV_ContourMomentsTest(): - CV_BaseShapeDescrTest( "shape-moments", "cvMoments, cvContourArea" ) -{ - min_log_size = 3; - max_log_size = 8; - max_max_r_scale = 15; - low_high_range = 200; - enable_flt_points = false; -} - - -void CV_ContourMomentsTest::generate_point_set( void* points ) -{ - CvRNG* rng = ts->get_rng(); - float max_sz; - - axes.width = (float)((cvTsRandReal(rng)*0.9 + 0.1)*low_high_range); - axes.height = (float)((cvTsRandReal(rng)*0.9 + 0.1)*low_high_range); - max_sz = MAX(axes.width, axes.height); - - img_size.width = img_size.height = cvRound(low_high_range*2.2); - - center.x = (float)(img_size.width*0.5 + (cvTsRandReal(rng)-0.5)*(img_size.width - max_sz*2)*0.8); - center.y = (float)(img_size.height*0.5 + (cvTsRandReal(rng)-0.5)*(img_size.height - max_sz*2)*0.8); - - assert( 0 < center.x - max_sz && center.x + max_sz < img_size.width && - 0 < center.y - max_sz && center.y + max_sz < img_size.height ); - - max_r_scale = cvTsRandReal(rng)*max_max_r_scale*0.01; - angle = cvTsRandReal(rng)*360; - - cvTsGenerateTousledBlob( center, axes, max_r_scale, angle, points, rng ); - - if( points1 ) - points1->flags = CV_SEQ_MAGIC_VAL + CV_SEQ_POLYGON; -} - - -int CV_ContourMomentsTest::prepare_test_case( int test_case_idx ) -{ - min_log_size = MAX(min_log_size,3); - max_log_size = MIN(max_log_size,8); - max_log_size = MAX(min_log_size,max_log_size); - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - return code; -} - - -void CV_ContourMomentsTest::run_func() -{ - if(!test_cpp) - { - cvMoments( points, &moments ); - area = cvContourArea( points ); - } - else - { - moments = (CvMoments)cv::moments(cv::cvarrToMat(points)); - area = cv::contourArea(cv::cvarrToMat(points)); - } -} - - -int CV_ContourMomentsTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, n = (int)(sizeof(moments)/sizeof(moments.inv_sqrt_m00)); - CvMat* img = cvCreateMat( img_size.height, img_size.width, CV_8UC1 ); - CvPoint* pt = (CvPoint*)points2->data.i; - int count = points2->cols + points2->rows - 1; - double max_v0 = 0; - - cvZero(img); - cvFillPoly( img, &pt, &count, 1, cvScalarAll(1)); - cvMoments( img, &moments0 ); - - for( i = 0; i < n; i++ ) - { - double t = fabs((&moments0.m00)[i]); - max_v0 = MAX(max_v0, t); - } - - for( i = 0; i <= n; i++ ) - { - double v = i < n ? (&moments.m00)[i] : area; - double v0 = i < n ? (&moments0.m00)[i] : moments0.m00; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( CvTS::LOG, - "The contour %s is invalid (=%g)\n", i < n ? "moment" : "area", v ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - - if( fabs(v - v0) > 0.1*max_v0 ) - { - ts->printf( CvTS::LOG, - "The computed contour %s is %g, while it should be %g\n", - i < n ? "moment" : "area", v, v0 ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - } - } - - if( code < 0 ) - { -#if 0 - cvCmpS( img, 0, img, CV_CMP_GT ); - cvNamedWindow( "test", 1 ); - cvShowImage( "test", img ); - cvWaitKey(); -#endif - ts->set_failed_test_info( code ); - } - - cvReleaseMat( &img ); - return code; -} - - -CV_ContourMomentsTest contour_moments_test; - - -/* End of file. */ - diff --git a/tests/cv/src/acornerssubpix.cpp b/tests/cv/src/acornerssubpix.cpp deleted file mode 100644 index 7267968..0000000 --- a/tests/cv/src/acornerssubpix.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// - // - // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. - // - // By downloading, copying, installing or using the software you agree to this license. - // If you do not agree to this license, do not download, install, - // copy or use the software. - // - // - // Intel License Agreement - // For Open Source Computer Vision Library - // - // Copyright (C) 2000, Intel Corporation, all rights reserved. - // Third party copyrights are property of their respective owners. - // - // Redistribution and use in source and binary forms, with or without modification, - // are permitted provided that the following conditions are met: - // - // * Redistribution's of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistribution's in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * The name of Intel Corporation may not be used to endorse or promote products - // derived from this software without specific prior written permission. - // - // This software is provided by the copyright holders and contributors "as is" and - // any express or implied warranties, including, but not limited to, the implied - // warranties of merchantability and fitness for a particular purpose are disclaimed. - // In no event shall the Intel Corporation or contributors be liable for any direct, - // indirect, incidental, special, exemplary, or consequential damages - // (including, but not limited to, procurement of substitute goods or services; - // loss of use, data, or profits; or business interruption) however caused - // and on any theory of liability, whether in contract, strict liability, - // or tort (including negligence or otherwise) arising in any way out of - // the use of this software, even if advised of the possibility of such damage. - // - //M*/ - -#include - -#include "cvtest.h" -#include "cvchessboardgenerator.h" - -using namespace cv; - -class CV_ChessboardSubpixelTest : public CvTest -{ -public: - CV_ChessboardSubpixelTest(); - -protected: - Mat intrinsic_matrix_; - Mat distortion_coeffs_; - Size image_size_; - - void run(int); - void generateIntrinsicParams(); -}; - - -int calcDistance(const vector& set1, const vector& set2, double& mean_dist) -{ - if(set1.size() != set2.size()) - { - return 0; - } - - std::vector indices; - double sum_dist = 0.0; - for(size_t i = 0; i < set1.size(); i++) - { - double min_dist = std::numeric_limits::max(); - int min_idx = -1; - - for(int j = 0; j < (int)set2.size(); j++) - { - double dist = norm(set1[i] - set2[j]); - if(dist < min_dist) - { - min_idx = j; - min_dist = dist; - } - } - - // check validity of min_idx - if(min_idx == -1) - { - return 0; - } - std::vector::iterator it = std::find(indices.begin(), indices.end(), min_idx); - if(it != indices.end()) - { - // there are two points in set1 corresponding to the same point in set2 - return 0; - } - indices.push_back(min_idx); - -// printf("dist %d = %f\n", (int)i, min_dist); - - sum_dist += min_dist*min_dist; - } - - mean_dist = sqrt(sum_dist/set1.size()); -// printf("sum_dist = %f, set1.size() = %d, mean_dist = %f\n", sum_dist, (int)set1.size(), mean_dist); - - return 1; -} - -CV_ChessboardSubpixelTest::CV_ChessboardSubpixelTest(): - CvTest( "chessboard-subpixel", "cvFindCornerSubPix" ), - intrinsic_matrix_(Size(3, 3), CV_64FC1), distortion_coeffs_(Size(1, 4), CV_64FC1), - image_size_(640, 480) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE | CvTS::TIMING_MODE; -} - -/* ///////////////////// chess_corner_test ///////////////////////// */ -void CV_ChessboardSubpixelTest::run( int ) -{ - int code = CvTS::OK; - int progress = 0; - - CvRNG* rng = ts->get_rng(); - - const int runs_count = 20; - const int max_pattern_size = 8; - const int min_pattern_size = 5; - Mat bg(image_size_, CV_8UC1); - bg = Scalar(0); - - double sum_dist = 0.0; - int count = 0; - for(int i = 0; i < runs_count; i++) - { - const int pattern_width = min_pattern_size + cvRandInt(rng) % (max_pattern_size - min_pattern_size); - const int pattern_height = min_pattern_size + cvRandInt(rng) % (max_pattern_size - min_pattern_size); - Size pattern_size; - if(pattern_width > pattern_height) - { - pattern_size = Size(pattern_height, pattern_width); - } - else - { - pattern_size = Size(pattern_width, pattern_height); - } - ChessBoardGenerator gen_chessboard(Size(pattern_size.width + 1, pattern_size.height + 1)); - - // generates intrinsic camera and distortion matrices - generateIntrinsicParams(); - - vector corners; - Mat chessboard_image = gen_chessboard(bg, intrinsic_matrix_, distortion_coeffs_, corners); - - vector test_corners; - bool result = findChessboardCorners(chessboard_image, pattern_size, test_corners, 15); - if(!result) - { -#if 0 - ts->printf(CvTS::LOG, "Warning: chessboard was not detected! Writing image to test.jpg\n"); - ts->printf(CvTS::LOG, "Size = %d, %d\n", pattern_size.width, pattern_size.height); - ts->printf(CvTS::LOG, "Intrinsic params: fx = %f, fy = %f, cx = %f, cy = %f\n", - intrinsic_matrix_.at(0, 0), intrinsic_matrix_.at(1, 1), - intrinsic_matrix_.at(0, 2), intrinsic_matrix_.at(1, 2)); - ts->printf(CvTS::LOG, "Distortion matrix: %f, %f, %f, %f, %f\n", - distortion_coeffs_.at(0, 0), distortion_coeffs_.at(0, 1), - distortion_coeffs_.at(0, 2), distortion_coeffs_.at(0, 3), - distortion_coeffs_.at(0, 4)); - - imwrite("test.jpg", chessboard_image); -#endif - continue; - } - - double dist1 = 0.0; - int ret = calcDistance(corners, test_corners, dist1); - if(ret == 0) - { - ts->printf(CvTS::LOG, "findChessboardCorners returns invalid corner coordinates!\n"); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - - IplImage chessboard_image_header = chessboard_image; - cvFindCornerSubPix(&chessboard_image_header, (CvPoint2D32f*)&test_corners[0], - (int)test_corners.size(), cvSize(3, 3), cvSize(1, 1), cvTermCriteria(CV_TERMCRIT_EPS|CV_TERMCRIT_ITER,300,0.1)); - find4QuadCornerSubpix(chessboard_image, test_corners, Size(5, 5)); - - double dist2 = 0.0; - ret = calcDistance(corners, test_corners, dist2); - if(ret == 0) - { - ts->printf(CvTS::LOG, "findCornerSubpix returns invalid corner coordinates!\n"); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - - ts->printf(CvTS::LOG, "Error after findChessboardCorners: %f, after findCornerSubPix: %f\n", - dist1, dist2); - sum_dist += dist2; - count++; - - const double max_reduce_factor = 0.8; - if(dist1 < dist2*max_reduce_factor) - { - ts->printf(CvTS::LOG, "findCornerSubPix increases average error!\n"); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - - progress = update_progress( progress, i-1, runs_count, 0 ); - } - sum_dist /= count; - ts->printf(CvTS::LOG, "Average error after findCornerSubpix: %f\n", sum_dist); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -void CV_ChessboardSubpixelTest::generateIntrinsicParams() -{ - CvRNG* rng = ts->get_rng(); - const double max_focus_length = 1000.0; - const double max_focus_diff = 5.0; - - double fx = cvRandReal(rng)*max_focus_length; - double fy = fx + cvRandReal(rng)*max_focus_diff; - double cx = image_size_.width/2; - double cy = image_size_.height/2; - - double k1 = 0.5*cvRandReal(rng); - double k2 = 0.05*cvRandReal(rng); - double p1 = 0.05*cvRandReal(rng); - double p2 = 0.05*cvRandReal(rng); - double k3 = 0.0; - - intrinsic_matrix_ = (Mat_(3, 3) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0); - distortion_coeffs_ = (Mat_(1, 5) << k1, k2, p1, p2, k3); -} - -CV_ChessboardSubpixelTest chessboard_subpixel_test; - -/* End of file. */ diff --git a/tests/cv/src/acreatecontourtree.cpp b/tests/cv/src/acreatecontourtree.cpp deleted file mode 100644 index 65a6a64..0000000 --- a/tests/cv/src/acreatecontourtree.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -static char cTestName[] = "Binary tree create"; -static char cTestClass[] = "Algorithm"; -static char cFuncName[] = "cvCreateContourTree"; - -static int aCreateContourTree(void) -{ - CvSeqBlock contour_blk1; - CvContour contour_h1; /* input contour */ - CvSeq *contour_h2; /* destination contour */ - CvContourTree *tree; /* created binary tree */ - CvMemStorage *storage; /* storage for contour and tree writing */ - CvTermCriteria criteria; /* criteria for the contour restoring */ -/* CvSeqReader reader; // points reader of contour */ -/* ippiTrianAttr vertex;*/ - - int block_size = 10000; - int nPoints1 = 20; - int xc,yc,a1 = 10, b1 = 20, fi = 0; - int xmin,ymin,xmax,ymax; - double error_test; - double pi = 3.1415926, eps_rez = 0.05; - double threshold = 1.e-7; - double rezult,error; - int i, code = TRS_OK; - int type_seq = 0; - int width=256,height=256; - CvPoint *cp1; - CvPoint *cp2; - -/* read tests params */ - - if (!trsiRead(&nPoints1,"20","Number of points first contour")) - return TRS_UNDEF; - - if(nPoints1>0) - { - if (!trsiRead(&a1,"10","first radius of the first elipse")) - return TRS_UNDEF; - if (!trsiRead(&b1,"20","second radius of the first elipse")) - return TRS_UNDEF; - - if (!trsiRead(&fi,"0","second radius of the second elipse")) - return TRS_UNDEF; - - xc = (int)(width/2.); - yc = (int)(height/2.); - xmin = width; - ymin = height; - xmax = 0; - ymax = 0; - - cp1 = (CvPoint*) trsmAlloc(nPoints1*sizeof(CvPoint)); - cp2 = (CvPoint*) trsmAlloc(nPoints1*sizeof(CvPoint)); - - for(i=0;i cp1[i].x) xmin = cp1[i].x; - if(xmax< cp1[i].x) xmax = cp1[i].x; - if(ymin> cp1[i].y) ymin = cp1[i].y; - if(ymax< cp1[i].y) ymax = cp1[i].y; - } - - if(xmax>width||xmin<0||ymax>height||ymin<0) - return TRS_FAIL; - - - storage = cvCreateMemStorage( block_size ); -/* contours initialazing */ - - type_seq = CV_SEQ_POLYGON; - cvMakeSeqHeaderForArray(type_seq, sizeof(CvContour), sizeof(CvPoint), - (char*)cp1, nPoints1, (CvSeq*)&contour_h1, &contour_blk1); - -/* create countour's tree */ - error_test = 0.; - - tree = cvCreateContourTree ((CvSeq*)&contour_h1, storage, threshold); - - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "Contour's binary tree is created \n"); - - error = 0; - criteria.type = CV_TERMCRIT_ITER; - criteria.max_iter = 100; - contour_h2 = cvContourFromContourTree (tree, storage, criteria); - rezult = cvMatchContours ((CvSeq*)&contour_h1, contour_h2,CV_CONTOURS_MATCH_I1); - - error+=rezult; - - criteria.type = CV_TERMCRIT_EPS; - criteria.epsilon = (float)0.00001; - contour_h2 = cvContourFromContourTree (tree, storage, criteria); - rezult = cvMatchContours ((CvSeq*)&contour_h1, contour_h2, CV_CONTOURS_MATCH_I1); - error+=rezult; - - criteria.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; - criteria.epsilon = (float)0.00001; - criteria.max_iter = 1; - contour_h2 = cvContourFromContourTree (tree, storage, criteria); - rezult = cvMatchContours ((CvSeq*)&contour_h1, contour_h2, CV_CONTOURS_MATCH_I1); - error+=rezult; - - criteria.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; - criteria.epsilon = 1000.; - criteria.max_iter = 100; - contour_h2 = cvContourFromContourTree (tree, storage, criteria); - rezult = cvMatchContours ((CvSeq*)&contour_h1, contour_h2, CV_CONTOURS_MATCH_I1); - error+=rezult; - - if(error > eps_rez ) - code = TRS_FAIL; - else - code = TRS_OK; - - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "contour from contour tree is restored rezult= %f \n",rezult); - - cvCvtSeqToArray(contour_h2, (char*)cp2 ); - - cvReleaseMemStorage ( &storage ); - - trsFree (cp2); - trsFree (cp1); - - } - - -/* _getch(); */ - return code; -} - -void InitACreateContourTree( void ) -{ -/* Test Registartion */ - trsReg(cFuncName,cTestName,cTestClass,aCreateContourTree); - -} /* InitACreateContourTree */ - -/* End of file. */ - -#endif diff --git a/tests/cv/src/adetectordescriptor_evaluation.cpp b/tests/cv/src/adetectordescriptor_evaluation.cpp deleted file mode 100644 index fb6f2c4..0000000 --- a/tests/cv/src/adetectordescriptor_evaluation.cpp +++ /dev/null @@ -1,1186 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include - -using namespace std; -using namespace cv; - -/****************************************************************************************\ -* Functions to evaluate affine covariant detectors and descriptors. * -\****************************************************************************************/ - -static inline Point2f applyHomography( const Mat_& H, const Point2f& pt ) -{ - double z = H(2,0)*pt.x + H(2,1)*pt.y + H(2,2); - if( z ) - { - double w = 1./z; - return Point2f( (float)((H(0,0)*pt.x + H(0,1)*pt.y + H(0,2))*w), - (float)((H(1,0)*pt.x + H(1,1)*pt.y + H(1,2))*w) ); - } - return Point2f( numeric_limits::max(), numeric_limits::max() ); -} - -static inline void linearizeHomographyAt( const Mat_& H, const Point2f& pt, Mat_& A ) -{ - A.create(2,2); - double p1 = H(0,0)*pt.x + H(0,1)*pt.y + H(0,2), - p2 = H(1,0)*pt.x + H(1,1)*pt.y + H(1,2), - p3 = H(2,0)*pt.x + H(2,1)*pt.y + H(2,2), - p3_2 = p3*p3; - if( p3 ) - { - A(0,0) = H(0,0)/p3 - p1*H(2,0)/p3_2; // fxdx - A(0,1) = H(0,1)/p3 - p1*H(2,1)/p3_2; // fxdy - - A(1,0) = H(1,0)/p3 - p2*H(2,0)/p3_2; // fydx - A(1,1) = H(1,1)/p3 - p2*H(2,1)/p3_2; // fydx - } - else - A.setTo(Scalar::all(numeric_limits::max())); -} - -static void calcKeyPointProjections( const vector& src, const Mat_& H, vector& dst ) -{ - if( !src.empty() ) - { - assert( !H.empty() && H.cols == 3 && H.rows == 3); - dst.resize(src.size()); - vector::const_iterator srcIt = src.begin(); - vector::iterator dstIt = dst.begin(); - for( ; srcIt != src.end(); ++srcIt, ++dstIt ) - { - Point2f dstPt = applyHomography(H, srcIt->pt); - - float srcSize2 = srcIt->size * srcIt->size; - Mat_ M(2, 2); - M(0,0) = M(1,1) = 1./srcSize2; - M(1,0) = M(0,1) = 0; - Mat_ invM; invert(M, invM); - Mat_ Aff; linearizeHomographyAt(H, srcIt->pt, Aff); - Mat_ dstM; invert(Aff*invM*Aff.t(), dstM); - Mat_ eval; eigen( dstM, eval ); - assert( eval(0,0) && eval(1,0) ); - float dstSize = (float)pow(1./(eval(0,0)*eval(1,0)), 0.25); - - // TODO: check angle projection - float srcAngleRad = (float)(srcIt->angle*CV_PI/180); - Point2f vec1(cos(srcAngleRad), sin(srcAngleRad)), vec2; - vec2.x = (float)(Aff(0,0)*vec1.x + Aff(0,1)*vec1.y); - vec2.y = (float)(Aff(1,0)*vec1.x + Aff(0,1)*vec1.y); - float dstAngleGrad = fastAtan2(vec2.y, vec2.x); - - *dstIt = KeyPoint( dstPt, dstSize, dstAngleGrad, srcIt->response, srcIt->octave, srcIt->class_id ); - } - } -} - -static void filterKeyPointsByImageSize( vector& keypoints, const Size& imgSize ) -{ - if( !keypoints.empty() ) - { - vector filtered; - filtered.reserve(keypoints.size()); - Rect r(0, 0, imgSize.width, imgSize.height); - vector::const_iterator it = keypoints.begin(); - for( int i = 0; it != keypoints.end(); ++it, i++ ) - if( r.contains(it->pt) ) - filtered.push_back(*it); - keypoints.assign(filtered.begin(), filtered.end()); - } -} - -/****************************************************************************************\ -* Detectors evaluation * -\****************************************************************************************/ -const int DATASETS_COUNT = 8; -const int TEST_CASE_COUNT = 5; - -const string IMAGE_DATASETS_DIR = "detectors_descriptors_evaluation/images_datasets/"; -const string DETECTORS_DIR = "detectors_descriptors_evaluation/detectors/"; -const string DESCRIPTORS_DIR = "detectors_descriptors_evaluation/descriptors/"; -const string KEYPOINTS_DIR = "detectors_descriptors_evaluation/keypoints_datasets/"; - -const string PARAMS_POSTFIX = "_params.xml"; -const string RES_POSTFIX = "_res.xml"; - -const string REPEAT = "repeatability"; -const string CORRESP_COUNT = "correspondence_count"; - -string DATASET_NAMES[DATASETS_COUNT] = { "bark", "bikes", "boat", "graf", "leuven", "trees", "ubc", "wall"}; - -string DEFAULT_PARAMS = "default"; - -string IS_ACTIVE_PARAMS = "isActiveParams"; -string IS_SAVE_KEYPOINTS = "isSaveKeypoints"; - - -class BaseQualityTest : public CvTest -{ -public: - BaseQualityTest( const char* _algName, const char* _testName, const char* _testFuncs ) : - CvTest( _testName, _testFuncs ), algName(_algName) - { - //TODO: change this - isWriteGraphicsData = true; - } - -protected: - virtual string getRunParamsFilename() const = 0; - virtual string getResultsFilename() const = 0; - virtual string getPlotPath() const = 0; - - virtual void validQualityClear( int datasetIdx ) = 0; - virtual void calcQualityClear( int datasetIdx ) = 0; - virtual void validQualityCreate( int datasetIdx ) = 0; - virtual bool isValidQualityEmpty( int datasetIdx ) const = 0; - virtual bool isCalcQualityEmpty( int datasetIdx ) const = 0; - - void readAllDatasetsRunParams(); - virtual void readDatasetRunParams( FileNode& fn, int datasetIdx ) = 0; - void writeAllDatasetsRunParams() const; - virtual void writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const = 0; - void setDefaultAllDatasetsRunParams(); - virtual void setDefaultDatasetRunParams( int datasetIdx ) = 0; - virtual void readDefaultRunParams( FileNode& /*fn*/ ) {} - virtual void writeDefaultRunParams( FileStorage& /*fs*/ ) const {} - - virtual void readResults(); - virtual void readResults( FileNode& fn, int datasetIdx, int caseIdx ) = 0; - void writeResults() const; - virtual void writeResults( FileStorage& fs, int datasetIdx, int caseIdx ) const = 0; - - bool readDataset( const string& datasetName, vector& Hs, vector& imgs ); - - virtual void readAlgorithm( ) {}; - virtual void processRunParamsFile () {}; - virtual void runDatasetTest( const vector& /*imgs*/, const vector& /*Hs*/, int /*di*/, int& /*progress*/ ) {} - void run( int ); - - virtual void processResults( int datasetIdx ); - virtual int processResults( int datasetIdx, int caseIdx ) = 0; - virtual void processResults(); - virtual void writePlotData( int /*datasetIdx*/ ) const {} - virtual void writeAveragePlotData() const {}; - - string algName; - bool isWriteParams, isWriteResults, isWriteGraphicsData; -}; - -void BaseQualityTest::readAllDatasetsRunParams() -{ - string filename = getRunParamsFilename(); - FileStorage fs( filename, FileStorage::READ ); - if( !fs.isOpened() ) - { - isWriteParams = true; - setDefaultAllDatasetsRunParams(); - ts->printf(CvTS::LOG, "all runParams are default\n"); - } - else - { - isWriteParams = false; - FileNode topfn = fs.getFirstTopLevelNode(); - - FileNode fn = topfn[DEFAULT_PARAMS]; - readDefaultRunParams(fn); - - for( int i = 0; i < DATASETS_COUNT; i++ ) - { - FileNode fn = topfn[DATASET_NAMES[i]]; - if( fn.empty() ) - { - ts->printf( CvTS::LOG, "%d-runParams is default\n", i); - setDefaultDatasetRunParams(i); - } - else - readDatasetRunParams(fn, i); - } - } -} - -void BaseQualityTest::writeAllDatasetsRunParams() const -{ - string filename = getRunParamsFilename(); - FileStorage fs( filename, FileStorage::WRITE ); - if( fs.isOpened() ) - { - fs << "run_params" << "{"; // top file node - fs << DEFAULT_PARAMS << "{"; - writeDefaultRunParams(fs); - fs << "}"; - for( int i = 0; i < DATASETS_COUNT; i++ ) - { - fs << DATASET_NAMES[i] << "{"; - writeDatasetRunParams(fs, i); - fs << "}"; - } - fs << "}"; - } - else - ts->printf(CvTS::LOG, "file %s for writing run params can not be opened\n", filename.c_str() ); -} - -void BaseQualityTest::setDefaultAllDatasetsRunParams() -{ - for( int i = 0; i < DATASETS_COUNT; i++ ) - setDefaultDatasetRunParams(i); -} - -bool BaseQualityTest::readDataset( const string& datasetName, vector& Hs, vector& imgs ) -{ - Hs.resize( TEST_CASE_COUNT ); - imgs.resize( TEST_CASE_COUNT+1 ); - string dirname = string(ts->get_data_path()) + IMAGE_DATASETS_DIR + datasetName + "/"; - - for( int i = 0; i < (int)Hs.size(); i++ ) - { - stringstream filename; filename << "H1to" << i+2 << "p.xml"; - FileStorage fs( dirname + filename.str(), FileStorage::READ ); - if( !fs.isOpened() ) - return false; - fs.getFirstTopLevelNode() >> Hs[i]; - } - - for( int i = 0; i < (int)imgs.size(); i++ ) - { - stringstream filename; filename << "img" << i+1 << ".png"; - imgs[i] = imread( dirname + filename.str(), 0 ); - if( imgs[i].empty() ) - return false; - } - return true; -} - -void BaseQualityTest::readResults() -{ - string filename = getResultsFilename(); - FileStorage fs( filename, FileStorage::READ ); - if( fs.isOpened() ) - { - isWriteResults = false; - FileNode topfn = fs.getFirstTopLevelNode(); - for( int di = 0; di < DATASETS_COUNT; di++ ) - { - FileNode datafn = topfn[DATASET_NAMES[di]]; - if( datafn.empty() ) - { - validQualityClear(di); - ts->printf( CvTS::LOG, "results for %s dataset were not read\n", - DATASET_NAMES[di].c_str() ); - } - else - { - validQualityCreate(di); - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - stringstream ss; ss << "case" << ci; - FileNode casefn = datafn[ss.str()]; - CV_Assert( !casefn.empty() ); - readResults( casefn , di, ci ); - } - } - } - } - else - isWriteResults = true; -} - -void BaseQualityTest::writeResults() const -{ - string filename = getResultsFilename();; - FileStorage fs( filename, FileStorage::WRITE ); - if( fs.isOpened() ) - { - fs << "results" << "{"; - for( int di = 0; di < DATASETS_COUNT; di++ ) - { - if( isCalcQualityEmpty(di) ) - { - ts->printf(CvTS::LOG, "results on %s dataset were not write because of empty\n", - DATASET_NAMES[di].c_str()); - } - else - { - fs << DATASET_NAMES[di] << "{"; - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - stringstream ss; ss << "case" << ci; - fs << ss.str() << "{"; - writeResults( fs, di, ci ); - fs << "}"; //ss.str() - } - fs << "}"; //DATASET_NAMES[di] - } - } - fs << "}"; //results - } - else - ts->printf(CvTS::LOG, "results were not written because file %s can not be opened\n", filename.c_str() ); -} - -void BaseQualityTest::processResults( int datasetIdx ) -{ - if( isWriteGraphicsData ) - writePlotData( datasetIdx ); -} - -void BaseQualityTest::processResults() -{ - if( isWriteParams ) - writeAllDatasetsRunParams(); - - if( isWriteGraphicsData ) - writeAveragePlotData(); - - int res = CvTS::OK; - if( isWriteResults ) - writeResults(); - else - { - for( int di = 0; di < DATASETS_COUNT; di++ ) - { - if( isValidQualityEmpty(di) || isCalcQualityEmpty(di) ) - continue; - - ts->printf(CvTS::LOG, "\nDataset: %s\n", DATASET_NAMES[di].c_str() ); - - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - ts->printf(CvTS::LOG, "case%d\n", ci); - int currRes = processResults( di, ci ); - res = currRes == CvTS::OK ? res : currRes; - } - } - } - - if( res != CvTS::OK ) - ts->printf(CvTS::LOG, "BAD ACCURACY\n"); - ts->set_failed_test_info( res ); -} - -void BaseQualityTest::run ( int ) -{ - readAlgorithm (); - processRunParamsFile (); - readResults(); - - int notReadDatasets = 0; - int progress = 0; - - FileStorage runParamsFS( getRunParamsFilename(), FileStorage::READ ); - isWriteParams = (! runParamsFS.isOpened()); - FileNode topfn = runParamsFS.getFirstTopLevelNode(); - FileNode defaultParams = topfn[DEFAULT_PARAMS]; - readDefaultRunParams (defaultParams); - - for(int di = 0; di < DATASETS_COUNT; di++ ) - { - vector imgs, Hs; - if( !readDataset( DATASET_NAMES[di], Hs, imgs ) ) - { - calcQualityClear (di); - ts->printf( CvTS::LOG, "images or homography matrices of dataset named %s can not be read\n", - DATASET_NAMES[di].c_str()); - notReadDatasets++; - continue; - } - - FileNode fn = topfn[DATASET_NAMES[di]]; - readDatasetRunParams(fn, di); - - runDatasetTest (imgs, Hs, di, progress); - processResults( di ); - } - if( notReadDatasets == DATASETS_COUNT ) - { - ts->printf(CvTS::LOG, "All datasets were not be read\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - } - else - processResults(); - runParamsFS.release(); -} - - - -class DetectorQualityTest : public BaseQualityTest -{ -public: - DetectorQualityTest( const char* _detectorName, const char* _testName ) : - BaseQualityTest( _detectorName, _testName, "quality-of-detector" ) - { - validQuality.resize(DATASETS_COUNT); - calcQuality.resize(DATASETS_COUNT); - isSaveKeypoints.resize(DATASETS_COUNT); - isActiveParams.resize(DATASETS_COUNT); - - isSaveKeypointsDefault = false; - isActiveParamsDefault = false; - } - -protected: - using BaseQualityTest::readResults; - using BaseQualityTest::writeResults; - using BaseQualityTest::processResults; - - virtual string getRunParamsFilename() const; - virtual string getResultsFilename() const; - virtual string getPlotPath() const; - - virtual void validQualityClear( int datasetIdx ); - virtual void calcQualityClear( int datasetIdx ); - virtual void validQualityCreate( int datasetIdx ); - virtual bool isValidQualityEmpty( int datasetIdx ) const; - virtual bool isCalcQualityEmpty( int datasetIdx ) const; - - virtual void readResults( FileNode& fn, int datasetIdx, int caseIdx ); - virtual void writeResults( FileStorage& fs, int datasetIdx, int caseIdx ) const; - - virtual void readDatasetRunParams( FileNode& fn, int datasetIdx ); - virtual void writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const; - virtual void setDefaultDatasetRunParams( int datasetIdx ); - virtual void readDefaultRunParams( FileNode &fn ); - virtual void writeDefaultRunParams( FileStorage &fs ) const; - - virtual void writePlotData( int di ) const; - virtual void writeAveragePlotData() const; - - void openToWriteKeypointsFile( FileStorage& fs, int datasetIdx ); - - virtual void readAlgorithm( ); - virtual void processRunParamsFile () {}; - virtual void runDatasetTest( const vector &imgs, const vector &Hs, int di, int &progress ); - virtual int processResults( int datasetIdx, int caseIdx ); - - Ptr specificDetector; - Ptr defaultDetector; - - struct Quality - { - float repeatability; - int correspondenceCount; - }; - vector > validQuality; - vector > calcQuality; - - vector isSaveKeypoints; - vector isActiveParams; - - bool isSaveKeypointsDefault; - bool isActiveParamsDefault; -}; - -string DetectorQualityTest::getRunParamsFilename() const -{ - return string(ts->get_data_path()) + DETECTORS_DIR + algName + PARAMS_POSTFIX; -} - -string DetectorQualityTest::getResultsFilename() const -{ - return string(ts->get_data_path()) + DETECTORS_DIR + algName + RES_POSTFIX; -} - -string DetectorQualityTest::getPlotPath() const -{ - return string(ts->get_data_path()) + DETECTORS_DIR + "plots/"; -} - -void DetectorQualityTest::validQualityClear( int datasetIdx ) -{ - validQuality[datasetIdx].clear(); -} - -void DetectorQualityTest::calcQualityClear( int datasetIdx ) -{ - calcQuality[datasetIdx].clear(); -} - -void DetectorQualityTest::validQualityCreate( int datasetIdx ) -{ - validQuality[datasetIdx].resize(TEST_CASE_COUNT); -} - -bool DetectorQualityTest::isValidQualityEmpty( int datasetIdx ) const -{ - return validQuality[datasetIdx].empty(); -} - -bool DetectorQualityTest::isCalcQualityEmpty( int datasetIdx ) const -{ - return calcQuality[datasetIdx].empty(); -} - -void DetectorQualityTest::readResults( FileNode& fn, int datasetIdx, int caseIdx ) -{ - validQuality[datasetIdx][caseIdx].repeatability = fn[REPEAT]; - validQuality[datasetIdx][caseIdx].correspondenceCount = fn[CORRESP_COUNT]; -} - -void DetectorQualityTest::writeResults( FileStorage& fs, int datasetIdx, int caseIdx ) const -{ - fs << REPEAT << calcQuality[datasetIdx][caseIdx].repeatability; - fs << CORRESP_COUNT << calcQuality[datasetIdx][caseIdx].correspondenceCount; -} - -void DetectorQualityTest::readDefaultRunParams (FileNode &fn) -{ - if (! fn.empty() ) - { - isSaveKeypointsDefault = (int)fn[IS_SAVE_KEYPOINTS] != 0; - defaultDetector->read (fn); - } -} - -void DetectorQualityTest::writeDefaultRunParams (FileStorage &fs) const -{ - fs << IS_SAVE_KEYPOINTS << isSaveKeypointsDefault; - defaultDetector->write (fs); -} - -void DetectorQualityTest::readDatasetRunParams( FileNode& fn, int datasetIdx ) -{ - isActiveParams[datasetIdx] = (int)fn[IS_ACTIVE_PARAMS] != 0; - if (isActiveParams[datasetIdx]) - { - isSaveKeypoints[datasetIdx] = (int)fn[IS_SAVE_KEYPOINTS] != 0; - specificDetector->read (fn); - } - else - { - setDefaultDatasetRunParams(datasetIdx); - } -} - -void DetectorQualityTest::writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const -{ - fs << IS_ACTIVE_PARAMS << isActiveParams[datasetIdx]; - fs << IS_SAVE_KEYPOINTS << isSaveKeypoints[datasetIdx]; - defaultDetector->write (fs); -} - -void DetectorQualityTest::setDefaultDatasetRunParams( int datasetIdx ) -{ - isSaveKeypoints[datasetIdx] = isSaveKeypointsDefault; - isActiveParams[datasetIdx] = isActiveParamsDefault; -} - -void DetectorQualityTest::writePlotData(int di ) const -{ - int imgXVals[] = { 2, 3, 4, 5, 6 }; // if scale, blur or light changes - int viewpointXVals[] = { 20, 30, 40, 50, 60 }; // if viewpoint changes - int jpegXVals[] = { 60, 80, 90, 95, 98 }; // if jpeg compression - - int* xVals = 0; - if( !DATASET_NAMES[di].compare("ubc") ) - { - xVals = jpegXVals; - } - else if( !DATASET_NAMES[di].compare("graf") || !DATASET_NAMES[di].compare("wall") ) - { - xVals = viewpointXVals; - } - else - xVals = imgXVals; - - stringstream rFilename, cFilename; - rFilename << getPlotPath() << algName << "_" << DATASET_NAMES[di] << "_repeatability.csv"; - cFilename << getPlotPath() << algName << "_" << DATASET_NAMES[di] << "_correspondenceCount.csv"; - ofstream rfile(rFilename.str().c_str()), cfile(cFilename.str().c_str()); - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - rfile << xVals[ci] << ", " << calcQuality[di][ci].repeatability << endl; - cfile << xVals[ci] << ", " << calcQuality[di][ci].correspondenceCount << endl; - } -} - -void DetectorQualityTest::writeAveragePlotData() const -{ - stringstream rFilename, cFilename; - rFilename << getPlotPath() << algName << "_average_repeatability.csv"; - cFilename << getPlotPath() << algName << "_average_correspondenceCount.csv"; - ofstream rfile(rFilename.str().c_str()), cfile(cFilename.str().c_str()); - float avRep = 0, avCorCount = 0; - for( int di = 0; di < DATASETS_COUNT; di++ ) - { - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - avRep += calcQuality[di][ci].repeatability; - avCorCount += calcQuality[di][ci].correspondenceCount; - } - } - avRep /= DATASETS_COUNT*TEST_CASE_COUNT; - avCorCount /= DATASETS_COUNT*TEST_CASE_COUNT; - rfile << algName << ", " << avRep << endl; - cfile << algName << ", " << cvRound(avCorCount) << endl; -} - -void DetectorQualityTest::openToWriteKeypointsFile( FileStorage& fs, int datasetIdx ) -{ - string filename = string(ts->get_data_path()) + KEYPOINTS_DIR + algName + "_"+ - DATASET_NAMES[datasetIdx] + ".xml.gz" ; - - fs.open(filename, FileStorage::WRITE); - if( !fs.isOpened() ) - ts->printf( CvTS::LOG, "keypoints can not be written in file %s because this file can not be opened\n", - filename.c_str()); -} - -inline void writeKeypoints( FileStorage& fs, const vector& keypoints, int imgIdx ) -{ - if( fs.isOpened() ) - { - stringstream imgName; imgName << "img" << imgIdx; - write( fs, imgName.str(), keypoints ); - } -} - -inline void readKeypoints( FileStorage& fs, vector& keypoints, int imgIdx ) -{ - assert( fs.isOpened() ); - stringstream imgName; imgName << "img" << imgIdx; - read( fs[imgName.str()], keypoints); -} - -void DetectorQualityTest::readAlgorithm () -{ - defaultDetector = FeatureDetector::create( algName ); - specificDetector = FeatureDetector::create( algName ); - if( defaultDetector == 0 ) - { - ts->printf(CvTS::LOG, "Algorithm can not be read\n"); - ts->set_failed_test_info( CvTS::FAIL_GENERIC); - } -} - -void DetectorQualityTest::runDatasetTest (const vector &imgs, const vector &Hs, int di, int &progress) -{ - Ptr detector = isActiveParams[di] ? specificDetector : defaultDetector; - FileStorage keypontsFS; - if( isSaveKeypoints[di] ) - openToWriteKeypointsFile( keypontsFS, di ); - - calcQuality[di].resize(TEST_CASE_COUNT); - - vector keypoints1; - detector->detect( imgs[0], keypoints1 ); - writeKeypoints( keypontsFS, keypoints1, 0); - int progressCount = DATASETS_COUNT*TEST_CASE_COUNT; - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - progress = update_progress( progress, di*TEST_CASE_COUNT + ci, progressCount, 0 ); - vector keypoints2; - float rep; - evaluateFeatureDetector( imgs[0], imgs[ci+1], Hs[ci], &keypoints1, &keypoints2, - rep, calcQuality[di][ci].correspondenceCount, - detector ); - calcQuality[di][ci].repeatability = rep == -1 ? rep : 100.f*rep; - writeKeypoints( keypontsFS, keypoints2, ci+1); - } -} - -void testLog( CvTS* ts, bool isBadAccuracy ) -{ - if( isBadAccuracy ) - ts->printf(CvTS::LOG, " bad accuracy\n"); - else - ts->printf(CvTS::LOG, "\n"); -} - -int DetectorQualityTest::processResults( int datasetIdx, int caseIdx ) -{ - int res = CvTS::OK; - bool isBadAccuracy; - - Quality valid = validQuality[datasetIdx][caseIdx], calc = calcQuality[datasetIdx][caseIdx]; - - const int countEps = 1 + cvRound( 0.005f*(float)valid.correspondenceCount ); - const float rltvEps = 0.5f; - - ts->printf(CvTS::LOG, "%s: calc=%f, valid=%f", REPEAT.c_str(), calc.repeatability, valid.repeatability ); - isBadAccuracy = (valid.repeatability - calc.repeatability) > rltvEps; - testLog( ts, isBadAccuracy ); - res = isBadAccuracy ? CvTS::FAIL_BAD_ACCURACY : res; - - ts->printf(CvTS::LOG, "%s: calc=%d, valid=%d", CORRESP_COUNT.c_str(), calc.correspondenceCount, valid.correspondenceCount ); - isBadAccuracy = (valid.correspondenceCount - calc.correspondenceCount) > countEps; - testLog( ts, isBadAccuracy ); - res = isBadAccuracy ? CvTS::FAIL_BAD_ACCURACY : res; - return res; -} - -/****************************************************************************************\ -* Descriptors evaluation * -\****************************************************************************************/ - -const string RECALL = "recall"; -const string PRECISION = "precision"; - -const string KEYPOINTS_FILENAME = "keypointsFilename"; -const string PROJECT_KEYPOINTS_FROM_1IMAGE = "projectKeypointsFrom1Image"; -const string MATCH_FILTER = "matchFilter"; -const string RUN_PARAMS_IS_IDENTICAL = "runParamsIsIdentical"; - -const string ONE_WAY_TRAIN_DIR = "detectors_descriptors_evaluation/one_way_train_images/"; -const string ONE_WAY_IMAGES_LIST = "one_way_train_images.txt"; - -class DescriptorQualityTest : public BaseQualityTest -{ -public: - enum{ NO_MATCH_FILTER = 0 }; - DescriptorQualityTest( const char* _descriptorName, const char* _testName, const char* _matcherName = 0 ) : - BaseQualityTest( _descriptorName, _testName, "quality-of-descriptor" ) - { - validQuality.resize(DATASETS_COUNT); - calcQuality.resize(DATASETS_COUNT); - calcDatasetQuality.resize(DATASETS_COUNT); - commRunParams.resize(DATASETS_COUNT); - - commRunParamsDefault.projectKeypointsFrom1Image = true; - commRunParamsDefault.matchFilter = NO_MATCH_FILTER; - commRunParamsDefault.isActiveParams = false; - - if( _matcherName ) - matcherName = _matcherName; - } - -protected: - using BaseQualityTest::readResults; - using BaseQualityTest::writeResults; - using BaseQualityTest::processResults; - - virtual string getRunParamsFilename() const; - virtual string getResultsFilename() const; - virtual string getPlotPath() const; - - virtual void validQualityClear( int datasetIdx ); - virtual void calcQualityClear( int datasetIdx ); - virtual void validQualityCreate( int datasetIdx ); - virtual bool isValidQualityEmpty( int datasetIdx ) const; - virtual bool isCalcQualityEmpty( int datasetIdx ) const; - - virtual void readResults( FileNode& fn, int datasetIdx, int caseIdx ); - virtual void writeResults( FileStorage& fs, int datasetIdx, int caseIdx ) const; - - virtual void readDatasetRunParams( FileNode& fn, int datasetIdx ); // - virtual void writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const; - virtual void setDefaultDatasetRunParams( int datasetIdx ); - virtual void readDefaultRunParams( FileNode &fn ); - virtual void writeDefaultRunParams( FileStorage &fs ) const; - - virtual void readAlgorithm( ); - virtual void processRunParamsFile () {}; - virtual void runDatasetTest( const vector &imgs, const vector &Hs, int di, int &progress ); - - virtual int processResults( int datasetIdx, int caseIdx ); - - virtual void writePlotData( int di ) const; - void calculatePlotData( vector > &allMatches, vector > &allCorrectMatchesMask, int di ); - - struct Quality - { - float recall; - float precision; - }; - vector > validQuality; - vector > calcQuality; - vector > calcDatasetQuality; - - struct CommonRunParams - { - string keypontsFilename; - bool projectKeypointsFrom1Image; - int matchFilter; // not used now - bool isActiveParams; - }; - vector commRunParams; - - Ptr specificDescMatcher; - Ptr defaultDescMatcher; - - CommonRunParams commRunParamsDefault; - string matcherName; -}; - -string DescriptorQualityTest::getRunParamsFilename() const -{ - return string(ts->get_data_path()) + DESCRIPTORS_DIR + algName + PARAMS_POSTFIX; -} - -string DescriptorQualityTest::getResultsFilename() const -{ - return string(ts->get_data_path()) + DESCRIPTORS_DIR + algName + RES_POSTFIX; -} - -string DescriptorQualityTest::getPlotPath() const -{ - return string(ts->get_data_path()) + DESCRIPTORS_DIR + "plots/"; -} - -void DescriptorQualityTest::validQualityClear( int datasetIdx ) -{ - validQuality[datasetIdx].clear(); -} - -void DescriptorQualityTest::calcQualityClear( int datasetIdx ) -{ - calcQuality[datasetIdx].clear(); -} - -void DescriptorQualityTest::validQualityCreate( int datasetIdx ) -{ - validQuality[datasetIdx].resize(TEST_CASE_COUNT); -} - -bool DescriptorQualityTest::isValidQualityEmpty( int datasetIdx ) const -{ - return validQuality[datasetIdx].empty(); -} - -bool DescriptorQualityTest::isCalcQualityEmpty( int datasetIdx ) const -{ - return calcQuality[datasetIdx].empty(); -} - -void DescriptorQualityTest::readResults( FileNode& fn, int datasetIdx, int caseIdx ) -{ - validQuality[datasetIdx][caseIdx].recall = fn[RECALL]; - validQuality[datasetIdx][caseIdx].precision = fn[PRECISION]; -} - -void DescriptorQualityTest::writeResults( FileStorage& fs, int datasetIdx, int caseIdx ) const -{ - fs << RECALL << calcQuality[datasetIdx][caseIdx].recall; - fs << PRECISION << calcQuality[datasetIdx][caseIdx].precision; -} - -void DescriptorQualityTest::readDefaultRunParams (FileNode &fn) -{ - if (! fn.empty() ) - { - commRunParamsDefault.projectKeypointsFrom1Image = (int)fn[PROJECT_KEYPOINTS_FROM_1IMAGE] != 0; - commRunParamsDefault.matchFilter = (int)fn[MATCH_FILTER]; - defaultDescMatcher->read (fn); - } -} - -void DescriptorQualityTest::writeDefaultRunParams (FileStorage &fs) const -{ - fs << PROJECT_KEYPOINTS_FROM_1IMAGE << commRunParamsDefault.projectKeypointsFrom1Image; - fs << MATCH_FILTER << commRunParamsDefault.matchFilter; - defaultDescMatcher->write (fs); -} - -void DescriptorQualityTest::readDatasetRunParams( FileNode& fn, int datasetIdx ) -{ - commRunParams[datasetIdx].isActiveParams = (int)fn[IS_ACTIVE_PARAMS] != 0; - if (commRunParams[datasetIdx].isActiveParams) - { - commRunParams[datasetIdx].keypontsFilename = (string)fn[KEYPOINTS_FILENAME]; - commRunParams[datasetIdx].projectKeypointsFrom1Image = (int)fn[PROJECT_KEYPOINTS_FROM_1IMAGE] != 0; - commRunParams[datasetIdx].matchFilter = (int)fn[MATCH_FILTER]; - specificDescMatcher->read (fn); - } - else - { - setDefaultDatasetRunParams(datasetIdx); - } -} - -void DescriptorQualityTest::writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const -{ - fs << IS_ACTIVE_PARAMS << commRunParams[datasetIdx].isActiveParams; - fs << KEYPOINTS_FILENAME << commRunParams[datasetIdx].keypontsFilename; - fs << PROJECT_KEYPOINTS_FROM_1IMAGE << commRunParams[datasetIdx].projectKeypointsFrom1Image; - fs << MATCH_FILTER << commRunParams[datasetIdx].matchFilter; - - defaultDescMatcher->write (fs); -} - -void DescriptorQualityTest::setDefaultDatasetRunParams( int datasetIdx ) -{ - commRunParams[datasetIdx] = commRunParamsDefault; - commRunParams[datasetIdx].keypontsFilename = "SURF_" + DATASET_NAMES[datasetIdx] + ".xml.gz"; -} - -void DescriptorQualityTest::writePlotData( int di ) const -{ - stringstream filename; - filename << getPlotPath() << algName << "_" << DATASET_NAMES[di] << ".csv"; - FILE *file = fopen (filename.str().c_str(), "w"); - size_t size = calcDatasetQuality[di].size(); - for (size_t i=0;i extractor = DescriptorExtractor::create( algName ); - Ptr matcher = DescriptorMatcher::create( matcherName ); - defaultDescMatcher = new VectorDescriptorMatch( extractor, matcher ); - specificDescMatcher = new VectorDescriptorMatch( extractor, matcher ); - - if( extractor == 0 || matcher == 0 ) - { - ts->printf(CvTS::LOG, "Algorithm can not be read\n"); - ts->set_failed_test_info( CvTS::FAIL_GENERIC); - } - } -} - -void DescriptorQualityTest::calculatePlotData( vector > &allMatches, vector > &allCorrectMatchesMask, int di ) -{ - vector recallPrecisionCurve; - computeRecallPrecisionCurve( allMatches, allCorrectMatchesMask, recallPrecisionCurve ); - - calcDatasetQuality[di].clear(); - const float resultPrecision = 0.5; - bool isResultCalculated = false; - const double eps = 1e-2; - - Quality initQuality; - initQuality.recall = 0; - initQuality.precision = 0; - calcDatasetQuality[di].push_back( initQuality ); - - for( size_t i=0;i &imgs, const vector &Hs, int di, int &progress) -{ - FileStorage keypontsFS( string(ts->get_data_path()) + KEYPOINTS_DIR + commRunParams[di].keypontsFilename, - FileStorage::READ ); - if( !keypontsFS.isOpened()) - { - calcQuality[di].clear(); - ts->printf( CvTS::LOG, "keypoints from file %s can not be read\n", commRunParams[di].keypontsFilename.c_str() ); - return; - } - - Ptr descMatch = commRunParams[di].isActiveParams ? specificDescMatcher : defaultDescMatcher; - calcQuality[di].resize(TEST_CASE_COUNT); - - vector keypoints1; - readKeypoints( keypontsFS, keypoints1, 0); - - int progressCount = DATASETS_COUNT*TEST_CASE_COUNT; - - vector > allMatches1to2; - vector > allCorrectMatchesMask; - for( int ci = 0; ci < TEST_CASE_COUNT; ci++ ) - { - progress = update_progress( progress, di*TEST_CASE_COUNT + ci, progressCount, 0 ); - - vector keypoints2; - if( commRunParams[di].projectKeypointsFrom1Image ) - { - // TODO need to test function calcKeyPointProjections - calcKeyPointProjections( keypoints1, Hs[ci], keypoints2 ); - filterKeyPointsByImageSize( keypoints2, imgs[ci+1].size() ); - } - else - readKeypoints( keypontsFS, keypoints2, ci+1 ); - // TODO if( commRunParams[di].matchFilter ) - - vector > matches1to2; - vector > correctMatchesMask; - vector recallPrecisionCurve; // not used because we need recallPrecisionCurve for - // all images in dataset - evaluateGenericDescriptorMatcher( imgs[0], imgs[ci+1], Hs[ci], keypoints1, keypoints2, - &matches1to2, &correctMatchesMask, recallPrecisionCurve, - descMatch ); - allMatches1to2.insert( allMatches1to2.end(), matches1to2.begin(), matches1to2.end() ); - allCorrectMatchesMask.insert( allCorrectMatchesMask.end(), correctMatchesMask.begin(), correctMatchesMask.end() ); - } - - calculatePlotData( allMatches1to2, allCorrectMatchesMask, di ); -} - -int DescriptorQualityTest::processResults( int datasetIdx, int caseIdx ) -{ - const float rltvEps = 0.001f; - - int res = CvTS::OK; - bool isBadAccuracy; - - Quality valid = validQuality[datasetIdx][caseIdx], calc = calcQuality[datasetIdx][caseIdx]; - - ts->printf(CvTS::LOG, "%s: calc=%f, valid=%f", RECALL.c_str(), calc.recall, valid.recall ); - isBadAccuracy = (valid.recall - calc.recall) > rltvEps; - testLog( ts, isBadAccuracy ); - res = isBadAccuracy ? CvTS::FAIL_BAD_ACCURACY : res; - - ts->printf(CvTS::LOG, "%s: calc=%f, valid=%f", PRECISION.c_str(), calc.precision, valid.precision ); - isBadAccuracy = (valid.precision - calc.precision) > rltvEps; - testLog( ts, isBadAccuracy ); - res = isBadAccuracy ? CvTS::FAIL_BAD_ACCURACY : res; - - return res; -} - -//--------------------------------- Calonder descriptor test -------------------------------------------- -class CalonderDescriptorQualityTest : public DescriptorQualityTest -{ -public: - CalonderDescriptorQualityTest() : - DescriptorQualityTest( "Calonder", "quality-descriptor-calonder") {} - virtual void readAlgorithm( ) - { - string classifierFile = string(ts->get_data_path()) + "/features2d/calonder_classifier.rtc"; - defaultDescMatcher = new VectorDescriptorMatch( new CalonderDescriptorExtractor( classifierFile ), - new BruteForceMatcher > ); - specificDescMatcher = defaultDescMatcher; - } -}; - -//--------------------------------- One Way descriptor test -------------------------------------------- -class OneWayDescriptorQualityTest : public DescriptorQualityTest -{ -public: - OneWayDescriptorQualityTest() : - DescriptorQualityTest("ONEWAY", "quality-descriptor-one-way") - { - } -protected: - virtual void processRunParamsFile (); - virtual void writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const; -}; - -void OneWayDescriptorQualityTest::processRunParamsFile () -{ - string filename = getRunParamsFilename(); - FileStorage fs = FileStorage (filename, FileStorage::READ); - FileNode fn = fs.getFirstTopLevelNode(); - fn = fn[DEFAULT_PARAMS]; - - string pcaFilename = string(ts->get_data_path()) + (string)fn["pcaFilename"]; - string trainPath = string(ts->get_data_path()) + (string)fn["trainPath"]; - string trainImagesList = (string)fn["trainImagesList"]; - int patch_width = fn["patchWidth"]; - int patch_height = fn["patchHeight"]; - Size patchSize = cvSize (patch_width, patch_height); - int poseCount = fn["poseCount"]; - - if (trainImagesList.length () == 0 ) - return; - - fs.release (); - - readAllDatasetsRunParams(); - - OneWayDescriptorBase *base = new OneWayDescriptorBase(patchSize, poseCount, pcaFilename, - trainPath, trainImagesList); - - OneWayDescriptorMatch *match = new OneWayDescriptorMatch (); - match->initialize( OneWayDescriptorMatch::Params (), base ); - defaultDescMatcher = match; - writeAllDatasetsRunParams(); -} - -void OneWayDescriptorQualityTest::writeDatasetRunParams( FileStorage& fs, int datasetIdx ) const -{ - fs << IS_ACTIVE_PARAMS << commRunParams[datasetIdx].isActiveParams; - fs << KEYPOINTS_FILENAME << commRunParams[datasetIdx].keypontsFilename; - fs << PROJECT_KEYPOINTS_FROM_1IMAGE << commRunParams[datasetIdx].projectKeypointsFrom1Image; - fs << MATCH_FILTER << commRunParams[datasetIdx].matchFilter; -} - -// Detectors -//DetectorQualityTest fastDetectorQuality = DetectorQualityTest( "FAST", "quality-detector-fast" ); -//DetectorQualityTest gfttDetectorQuality = DetectorQualityTest( "GFTT", "quality-detector-gftt" ); -//DetectorQualityTest harrisDetectorQuality = DetectorQualityTest( "HARRIS", "quality-detector-harris" ); -//DetectorQualityTest mserDetectorQuality = DetectorQualityTest( "MSER", "quality-detector-mser" ); -//DetectorQualityTest starDetectorQuality = DetectorQualityTest( "STAR", "quality-detector-star" ); -//DetectorQualityTest siftDetectorQuality = DetectorQualityTest( "SIFT", "quality-detector-sift" ); -//DetectorQualityTest surfDetectorQuality = DetectorQualityTest( "SURF", "quality-detector-surf" ); - -// Descriptors -//DescriptorQualityTest siftDescriptorQuality = DescriptorQualityTest( "SIFT", "quality-descriptor-sift", "BruteForce" ); -//DescriptorQualityTest surfDescriptorQuality = DescriptorQualityTest( "SURF", "quality-descriptor-surf", "BruteForce" ); -//DescriptorQualityTest fernDescriptorQualityTest( "FERN", "quality-descriptor-fern"); -//CalonderDescriptorQualityTest calonderDescriptorQualityTest; - - - -// Don't run it because of bug in OneWayDescriptorBase many to many matching. TODO: fix this bug. -//OneWayDescriptorQualityTest oneWayDescriptorQuality; - -// Don't run them (will validate and save results as "quality-descriptor-sift" and "quality-descriptor-surf" test data). -// TODO: differ result filenames. -//DescriptorQualityTest siftL1DescriptorQuality = DescriptorQualityTest( "SIFT", "quality-descriptor-sift-L1", "BruteForce-L1" ); -//DescriptorQualityTest surfL1DescriptorQuality = DescriptorQualityTest( "SURF", "quality-descriptor-surf-L1", "BruteForce-L1" ); -//DescriptorQualityTest oppSiftL1DescriptorQuality = DescriptorQualityTest( "SIFT", "quality-descriptor-opponent-sift-L1", "BruteForce-L1" ); -//DescriptorQualityTest oppSurfL1DescriptorQuality = DescriptorQualityTest( "SURF", "quality-descriptor-opponent-surf-L1", "BruteForce-L1" ); - diff --git a/tests/cv/src/adistancetransform.cpp b/tests/cv/src/adistancetransform.cpp deleted file mode 100644 index e52ad17..0000000 --- a/tests/cv/src/adistancetransform.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const char* distrans_param_names[] = { "size", "dist_type", "labels", 0 }; -static const CvSize distrans_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize distrans_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; -static const char* distrans_types[] = { "c_3x3", "l1_3x3", "l2_3x3", "l2_5x5", 0 }; -static const int distrans_labels[] = { 0, 1, -1 }; - -class CV_DisTransTest : public CvArrTest -{ -public: - CV_DisTransTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - int prepare_test_case( int test_case_idx ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int mask_size; - int dist_type; - int fill_labels; - float mask[3]; -}; - - -CV_DisTransTest::CV_DisTransTest() - : CvArrTest( "distrans", "cvDistTransform", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - optional_mask = false; - element_wise_relative_error = true; - - default_timing_param_names = distrans_param_names; - depth_list = 0; - size_list = distrans_sizes; - whole_size_list = distrans_whole_sizes; - cn_list = 0; -} - - -void CV_DisTransTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - types[INPUT][0] = CV_8UC1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_32FC1; - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_32SC1; - - if( cvTsRandInt(rng) & 1 ) - { - mask_size = 3; - dist_type = cvTsRandInt(rng) % 4; - dist_type = dist_type == 0 ? CV_DIST_C : dist_type == 1 ? CV_DIST_L1 : - dist_type == 2 ? CV_DIST_L2 : CV_DIST_USER; - } - else - { - mask_size = 5; - dist_type = cvTsRandInt(rng) % 10; - dist_type = dist_type == 0 ? CV_DIST_C : dist_type == 1 ? CV_DIST_L1 : - dist_type < 6 ? CV_DIST_L2 : CV_DIST_USER; - } - - // for now, check only the "labeled" distance transform mode - fill_labels = 0; - - if( !fill_labels ) - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = cvSize(0,0); - - if( dist_type == CV_DIST_USER ) - { - mask[0] = (float)(1.1 - cvTsRandReal(rng)*0.2); - mask[1] = (float)(1.9 - cvTsRandReal(rng)*0.8); - mask[2] = (float)(3. - cvTsRandReal(rng)); - } -} - - -double CV_DisTransTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - CvSize sz = cvGetMatSize(&test_mat[INPUT][0]); - return dist_type == CV_DIST_C || dist_type == CV_DIST_L1 ? 0 : 0.01*MAX(sz.width, sz.height); -} - - -void CV_DisTransTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT && CV_MAT_DEPTH(type) == CV_8U ) - { - *low = cvScalarAll(0); - *high = cvScalarAll(10); - } -} - -int CV_DisTransTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - // the function's response to an "all-nonzeros" image is not determined, - // so put at least one zero point - CvMat* mat = &test_mat[INPUT][0]; - CvRNG* rng = ts->get_rng(); - int i = cvTsRandInt(rng) % mat->rows; - int j = cvTsRandInt(rng) % mat->cols; - mat->data.ptr[mat->step*i + j] = 0; - } - - return code; -} - - -void CV_DisTransTest::run_func() -{ - cvDistTransform( test_array[INPUT][0], test_array[OUTPUT][0], dist_type, mask_size, - dist_type == CV_DIST_USER ? mask : 0, test_array[OUTPUT][1] ); -} - - -static void -cvTsDistTransform( const CvMat* _src, CvMat* _dst, int dist_type, - int mask_size, float* _mask, CvMat* /*_labels*/ ) -{ - int i, j, k; - int width = _src->cols, height = _src->rows; - const float init_val = 1e6; - float mask[3]; - CvMat* temp; - int ofs[16]; - float delta[16]; - int tstep, count; - - assert( mask_size == 3 || mask_size == 5 ); - - if( dist_type == CV_DIST_USER ) - memcpy( mask, _mask, sizeof(mask) ); - else if( dist_type == CV_DIST_C ) - { - mask_size = 3; - mask[0] = mask[1] = 1.f; - } - else if( dist_type == CV_DIST_L1 ) - { - mask_size = 3; - mask[0] = 1.f; - mask[1] = 2.f; - } - else if( mask_size == 3 ) - { - mask[0] = 0.955f; - mask[1] = 1.3693f; - } - else - { - mask[0] = 1.0f; - mask[1] = 1.4f; - mask[2] = 2.1969f; - } - - temp = cvCreateMat( height + mask_size-1, width + mask_size-1, CV_32F ); - tstep = temp->step / sizeof(float); - - if( mask_size == 3 ) - { - count = 4; - ofs[0] = -1; delta[0] = mask[0]; - ofs[1] = -tstep-1; delta[1] = mask[1]; - ofs[2] = -tstep; delta[2] = mask[0]; - ofs[3] = -tstep+1; delta[3] = mask[1]; - } - else - { - count = 8; - ofs[0] = -1; delta[0] = mask[0]; - ofs[1] = -tstep-2; delta[1] = mask[2]; - ofs[2] = -tstep-1; delta[2] = mask[1]; - ofs[3] = -tstep; delta[3] = mask[0]; - ofs[4] = -tstep+1; delta[4] = mask[1]; - ofs[5] = -tstep+2; delta[5] = mask[2]; - ofs[6] = -tstep*2-1; delta[6] = mask[2]; - ofs[7] = -tstep*2+1; delta[7] = mask[2]; - } - - for( i = 0; i < mask_size/2; i++ ) - { - float* t0 = (float*)(temp->data.ptr + i*temp->step); - float* t1 = (float*)(temp->data.ptr + (temp->rows - i - 1)*temp->step); - - for( j = 0; j < width + mask_size - 1; j++ ) - t0[j] = t1[j] = init_val; - } - - for( i = 0; i < height; i++ ) - { - uchar* s = _src->data.ptr + i*_src->step; - float* tmp = (float*)(temp->data.ptr + temp->step*(i + (mask_size/2))) + (mask_size/2); - - for( j = 0; j < mask_size/2; j++ ) - tmp[-j-1] = tmp[j + width] = init_val; - - for( j = 0; j < width; j++ ) - { - if( s[j] == 0 ) - tmp[j] = 0; - else - { - float min_dist = init_val; - for( k = 0; k < count; k++ ) - { - float t = tmp[j+ofs[k]] + delta[k]; - if( min_dist > t ) - min_dist = t; - } - tmp[j] = min_dist; - } - } - } - - for( i = height - 1; i >= 0; i-- ) - { - float* d = (float*)(_dst->data.ptr + i*_dst->step); - float* tmp = (float*)(temp->data.ptr + temp->step*(i + (mask_size/2))) + (mask_size/2); - - for( j = width - 1; j >= 0; j-- ) - { - float min_dist = tmp[j]; - if( min_dist > mask[0] ) - { - for( k = 0; k < count; k++ ) - { - float t = tmp[j-ofs[k]] + delta[k]; - if( min_dist > t ) - min_dist = t; - } - tmp[j] = min_dist; - } - d[j] = min_dist; - } - } - - cvReleaseMat( &temp ); -} - - -void CV_DisTransTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsDistTransform( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - dist_type, mask_size, mask, 0 ); -} - - -int CV_DisTransTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_string_list( fs, "dist_type", distrans_types ); - write_int_list( fs, "labels", distrans_labels, -1, -1 ); - } - - return code; -} - - -void CV_DisTransTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* distype_str = cvReadString( find_timing_param( "dist_type" ), "l2_5x5" ); - mask_size = strstr( distype_str, "3x3" ) ? 3 : 5; - dist_type = distype_str[0] == 'c' ? CV_DIST_C : distype_str[1] == '1' ? CV_DIST_L1 : CV_DIST_L2; - fill_labels = cvReadInt( find_timing_param( "labels" ), 0 ); - - types[INPUT][0] = CV_8UC1; - types[OUTPUT][0] = CV_32FC1; - types[OUTPUT][1] = CV_32SC1; - - if( !fill_labels ) - sizes[OUTPUT][1] = whole_sizes[OUTPUT][1] = cvSize(0,0); -} - - -void CV_DisTransTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "dist_type" ), "l2_5x5" ) ); - ptr += strlen(ptr); - sprintf( ptr, "%s,", fill_labels ? "labels" : "no_labels" ); - ptr += strlen(ptr); - params_left -= 2; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -CV_DisTransTest distrans_test; - - diff --git a/tests/cv/src/adrawing.cpp b/tests/cv/src/adrawing.cpp deleted file mode 100644 index 5003532..0000000 --- a/tests/cv/src/adrawing.cpp +++ /dev/null @@ -1,411 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include "highgui.h" - -using namespace cv; - -//#define DRAW_TEST_IMAGE - -class CV_DrawingTest : public CvTest -{ -public: - CV_DrawingTest( const char* testName ) : CvTest( testName, "drawing funcs" ) {} -protected: - void run( int ); - virtual void draw( Mat& img ) = 0; - virtual int checkLineIterator( Mat& img) = 0; -}; - -void CV_DrawingTest::run( int ) -{ - int code = CvTS::OK; - Mat testImg, valImg; - const string name = "drawing/image.jpg"; - string path = ts->get_data_path(), filename; - filename = path + name; - - draw( testImg ); - -#ifdef DRAW_TEST_IMAGE - imwrite( filename, testImg ); -#else - valImg = imread( filename ); - if( valImg.empty() ) - { - ts->printf( CvTS::LOG, "test image can not be read"); - code = CvTS::FAIL_INVALID_TEST_DATA; - } - else - { - float err = (float)norm( testImg, valImg, CV_RELATIVE_L1 ); - float Eps = 0.9f; - if( err > Eps) - { - ts->printf( CvTS::LOG, "CV_RELATIVE_L1 between testImg and valImg is equal %f (larger than %f)\n", err, Eps ); - code = CvTS::FAIL_BAD_ACCURACY; - } - else - { - code = checkLineIterator( testImg ); - } - } -#endif - ts->set_failed_test_info( code ); -} - -class CV_DrawingTest_CPP : public CV_DrawingTest -{ -public: - CV_DrawingTest_CPP() : CV_DrawingTest( "drawing_cpp" ) {} -protected: - virtual void draw( Mat& img ); - virtual int checkLineIterator( Mat& img); -}; - -void CV_DrawingTest_CPP::draw( Mat& img ) -{ - Size imgSize( 600, 400 ); - img.create( imgSize, CV_8UC3 ); - - vector polyline(4); - polyline[0] = Point(0, 0); - polyline[1] = Point(imgSize.width, 0); - polyline[2] = Point(imgSize.width, imgSize.height); - polyline[3] = Point(0, imgSize.height); - const Point* pts = &polyline[0]; - int n = (int)polyline.size(); - fillPoly( img, &pts, &n, 1, Scalar::all(255) ); - - Point p1(1,1), p2(3,3); - if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) - circle( img, Point(300,100), 40, Scalar(0,0,255), 3 ); // draw - - p2 = Point(3,imgSize.height+1000); - if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) - circle( img, Point(500,300), 50, cvColorToScalar(255,CV_8UC3), 5, 8, 1 ); // draw - - p1 = Point(imgSize.width,1), p2 = Point(imgSize.width,3); - if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) - circle( img, Point(390,100), 10, Scalar(0,0,255), 3 ); // not draw - - p1 = Point(imgSize.width-1,1), p2 = Point(imgSize.width,3); - if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) - ellipse( img, Point(390,100), Size(20,30), 60, 0, 220.0, Scalar(0,200,0), 4 ); //draw - - ellipse( img, RotatedRect(Point(100,200),Size(200,100),160), Scalar(200,200,255), 5 ); - - polyline.clear(); - ellipse2Poly( Point(430,180), Size(100,150), 30, 0, 150, 20, polyline ); - pts = &polyline[0]; - n = (int)polyline.size(); - polylines( img, &pts, &n, 1, false, Scalar(0,0,150), 4, CV_AA ); - n = 0; - for( vector::const_iterator it = polyline.begin(); n < (int)polyline.size()-1; ++it, n++ ) - { - line( img, *it, *(it+1), Scalar(50,250,100)); - } - - polyline.clear(); - ellipse2Poly( Point(500,300), Size(50,80), 0, 0, 180, 10, polyline ); - pts = &polyline[0]; - n = (int)polyline.size(); - polylines( img, &pts, &n, 1, true, Scalar(100,200,100), 20 ); - fillConvexPoly( img, pts, n, Scalar(0, 80, 0) ); - - polyline.resize(8); - // external rectengular - polyline[0] = Point(0, 0); - polyline[1] = Point(80, 0); - polyline[2] = Point(80, 80); - polyline[3] = Point(0, 80); - // internal rectangular - polyline[4] = Point(20, 20); - polyline[5] = Point(60, 20); - polyline[6] = Point(60, 60); - polyline[7] = Point(20, 60); - const Point* ppts[] = {&polyline[0], &polyline[0]+4}; - int pn[] = {4, 4}; - fillPoly( img, ppts, pn, 2, Scalar(100, 100, 0), 8, 0, Point(500, 20) ); - - rectangle( img, Point(0, 300), Point(50, 398), Scalar(0,0,255) ); - - string text1 = "OpenCV"; - int baseline = 0, thickness = 3, fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; - float fontScale = 2; - Size textSize = getTextSize( text1, fontFace, fontScale, thickness, &baseline); - baseline += thickness; - Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/2); - rectangle(img, textOrg + Point(0, baseline), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255)); - line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255)); - putText(img, text1, textOrg, fontFace, fontScale, Scalar(150,0,150), thickness, 8); - - string text2 = "abcdefghijklmnopqrstuvwxyz1234567890"; - Scalar color(200,0,0); - fontScale = 0.5, thickness = 1; - int dist = 5; - - textSize = getTextSize( text2, FONT_HERSHEY_SIMPLEX, fontScale, thickness, &baseline); - textOrg = Point(5,5)+Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, CV_AA); - - fontScale = 1; - textSize = getTextSize( text2, FONT_HERSHEY_PLAIN, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_PLAIN, fontScale, color, thickness, CV_AA); - - fontScale = 0.5; - textSize = getTextSize( text2, FONT_HERSHEY_DUPLEX, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_DUPLEX, fontScale, color, thickness, CV_AA); - - textSize = getTextSize( text2, FONT_HERSHEY_COMPLEX, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX, fontScale, color, thickness, CV_AA); - - textSize = getTextSize( text2, FONT_HERSHEY_TRIPLEX, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_TRIPLEX, fontScale, color, thickness, CV_AA); - - fontScale = 1; - textSize = getTextSize( text2, FONT_HERSHEY_COMPLEX_SMALL, fontScale, thickness, &baseline); - textOrg += Point(0,180) + Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX_SMALL, fontScale, color, thickness, CV_AA); - - textSize = getTextSize( text2, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, color, thickness, CV_AA); - - textSize = getTextSize( text2, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, color, thickness, CV_AA); - - dist = 15, fontScale = 0.5; - textSize = getTextSize( text2, FONT_ITALIC, fontScale, thickness, &baseline); - textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_ITALIC, fontScale, color, thickness, CV_AA); -} - -int CV_DrawingTest_CPP::checkLineIterator( Mat& img ) -{ - LineIterator it( img, Point(0,300), Point(1000, 300) ); - for(int i = 0; i < it.count; ++it, i++ ) - { - Vec3b v = (Vec3b)(*(*it)) - img.at(300,i); - float err = (float)norm( v ); - if( err != 0 ) - { - ts->printf( CvTS::LOG, "LineIterator works incorrect" ); - return CvTS::FAIL_INVALID_OUTPUT; - } - } - return CvTS::OK; -} - -class CV_DrawingTest_C : public CV_DrawingTest -{ -public: - CV_DrawingTest_C() : CV_DrawingTest( "drawing_c" ) {} -protected: - virtual void draw( Mat& img ); - virtual int checkLineIterator( Mat& img); -}; - -void CV_DrawingTest_C::draw( Mat& _img ) -{ - CvSize imgSize = cvSize(600, 400); - _img.create( imgSize, CV_8UC3 ); - CvMat img = _img; - - vector polyline(4); - polyline[0] = cvPoint(0, 0); - polyline[1] = cvPoint(imgSize.width, 0); - polyline[2] = cvPoint(imgSize.width, imgSize.height); - polyline[3] = cvPoint(0, imgSize.height); - CvPoint* pts = &polyline[0]; - int n = (int)polyline.size(); - cvFillPoly( &img, &pts, &n, 1, cvScalar(255,255,255) ); - - CvPoint p1 = cvPoint(1,1), p2 = cvPoint(3,3); - if( cvClipLine(imgSize, &p1, &p2) ) - cvCircle( &img, cvPoint(300,100), 40, cvScalar(0,0,255), 3 ); // draw - - p1 = cvPoint(1,1), p2 = cvPoint(3,imgSize.height+1000); - if( cvClipLine(imgSize, &p1, &p2) ) - cvCircle( &img, cvPoint(500,300), 50, cvScalar(255,0,0), 5, 8, 1 ); // draw - - p1 = cvPoint(imgSize.width,1), p2 = cvPoint(imgSize.width,3); - if( cvClipLine(imgSize, &p1, &p2) ) - cvCircle( &img, cvPoint(390,100), 10, cvScalar(0,0,255), 3 ); // not draw - - p1 = Point(imgSize.width-1,1), p2 = Point(imgSize.width,3); - if( cvClipLine(imgSize, &p1, &p2) ) - cvEllipse( &img, cvPoint(390,100), cvSize(20,30), 60, 0, 220.0, cvScalar(0,200,0), 4 ); //draw - - CvBox2D box; - box.center.x = 100; - box.center.y = 200; - box.size.width = 200; - box.size.height = 100; - box.angle = 160; - cvEllipseBox( &img, box, Scalar(200,200,255), 5 ); - - polyline.resize(9); - pts = &polyline[0]; - n = (int)polyline.size(); - assert( cvEllipse2Poly( cvPoint(430,180), cvSize(100,150), 30, 0, 150, &polyline[0], 20 ) == n ); - cvPolyLine( &img, &pts, &n, 1, false, cvScalar(0,0,150), 4, CV_AA ); - n = 0; - for( vector::const_iterator it = polyline.begin(); n < (int)polyline.size()-1; ++it, n++ ) - { - cvLine( &img, *it, *(it+1), cvScalar(50,250,100) ); - } - - polyline.resize(19); - pts = &polyline[0]; - n = (int)polyline.size(); - assert( cvEllipse2Poly( cvPoint(500,300), cvSize(50,80), 0, 0, 180, &polyline[0], 10 ) == n ); - cvPolyLine( &img, &pts, &n, 1, true, Scalar(100,200,100), 20 ); - cvFillConvexPoly( &img, pts, n, cvScalar(0, 80, 0) ); - - polyline.resize(8); - // external rectengular - polyline[0] = cvPoint(500, 20); - polyline[1] = cvPoint(580, 20); - polyline[2] = cvPoint(580, 100); - polyline[3] = cvPoint(500, 100); - // internal rectangular - polyline[4] = cvPoint(520, 40); - polyline[5] = cvPoint(560, 40); - polyline[6] = cvPoint(560, 80); - polyline[7] = cvPoint(520, 80); - CvPoint* ppts[] = {&polyline[0], &polyline[0]+4}; - int pn[] = {4, 4}; - cvFillPoly( &img, ppts, pn, 2, cvScalar(100, 100, 0), 8, 0 ); - - cvRectangle( &img, cvPoint(0, 300), cvPoint(50, 398), cvScalar(0,0,255) ); - - string text1 = "OpenCV"; - CvFont font; - cvInitFont( &font, FONT_HERSHEY_SCRIPT_SIMPLEX, 2, 2, 0, 3 ); - int baseline = 0; - CvSize textSize; - cvGetTextSize( text1.c_str(), &font, &textSize, &baseline ); - baseline += font.thickness; - CvPoint textOrg = cvPoint((imgSize.width - textSize.width)/2, (imgSize.height + textSize.height)/2); - cvRectangle( &img, cvPoint( textOrg.x, textOrg.y + baseline), - cvPoint(textOrg.x + textSize.width, textOrg.y - textSize.height), cvScalar(0,0,255)); - cvLine( &img, cvPoint(textOrg.x, textOrg.y + font.thickness), - cvPoint(textOrg.x + textSize.width, textOrg.y + font.thickness), cvScalar(0, 0, 255)); - cvPutText( &img, text1.c_str(), textOrg, &font, cvScalar(150,0,150) ); - - int dist = 5; - string text2 = "abcdefghijklmnopqrstuvwxyz1234567890"; - CvScalar color = cvScalar(200,0,0); - cvInitFont( &font, FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(5, 5+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_PLAIN, 1, 1, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_DUPLEX, 0.5, 0.5, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_TRIPLEX, 0.5, 0.5, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_COMPLEX_SMALL, 1, 1, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist + 180); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_SCRIPT_SIMPLEX, 1, 1, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - cvInitFont( &font, FONT_HERSHEY_SCRIPT_COMPLEX, 1, 1, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); - - dist = 15; - cvInitFont( &font, FONT_ITALIC, 0.5, 0.5, 0, 1, CV_AA ); - cvGetTextSize( text2.c_str(), &font, &textSize, &baseline ); - textOrg = cvPoint(textOrg.x,textOrg.y+textSize.height+dist); - cvPutText(&img, text2.c_str(), textOrg, &font, color ); -} - -int CV_DrawingTest_C::checkLineIterator( Mat& _img ) -{ - CvLineIterator it; - CvMat img = _img; - int count = cvInitLineIterator( &img, cvPoint(0,300), cvPoint(1000, 300), &it ); - for(int i = 0; i < count; i++ ) - { - Vec3b v = (Vec3b)(*(it.ptr)) - _img.at(300,i); - float err = (float)norm( v ); - if( err != 0 ) - { - ts->printf( CvTS::LOG, "CvLineIterator works incorrect" ); - return CvTS::FAIL_INVALID_OUTPUT; - } - CV_NEXT_LINE_POINT(it); - } - return CvTS::OK; -} - -CV_DrawingTest_CPP drawing_test_cpp; -CV_DrawingTest_C drawing_test_c; diff --git a/tests/cv/src/adrawing_regress.cpp b/tests/cv/src/adrawing_regress.cpp deleted file mode 100644 index 66a2160..0000000 --- a/tests/cv/src/adrawing_regress.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#include -#include "highgui.h" - -static char* funcs = "cvLine cvLineAA cvRectangle cvCircle cvCircleAA " - "cvEllipse cvEllipseAA cvFillConvexPoly cvFillPoly" - "cvPolyLine cvPolyLineAA cvPutText"; -static char* test_desc = "Drawing to image (regression test)"; - -static char* filedir_ = "drawing"; - -#ifndef RGB -#define RGB(r,g,b) CV_RGB(b,g,r) -#endif - -static int my_tolower( int c ) -{ - return 'A' <= c && c <= 'Z' ? c + ('a' - 'A') : c; -} - -static int CheckImage(IplImage* image, char* file, char* /*funcname*/) -{ - //printf("loading %s\n", file ); - IplImage* read = cvLoadImage( file, 1 ); - - if( !read ) - { - trsWrite( ATS_CON | ATS_LST, "can't read image\n" ); - return 1; - } - - int err = 0; - -#if 0 - { - IplImage* temp = cvCloneImage( read ); - cvAbsDiff( image, read, temp ); - cvThreshold( temp, temp, 0, 255, CV_THRESH_BINARY ); - cvvNamedWindow( "Original", 0 ); - cvvNamedWindow( "Diff", 0 ); - cvvShowImage( "Original", read ); - cvvShowImage( "Diff", temp ); - cvvWaitKey(0); - cvvDestroyWindow( "Original" ); - cvvDestroyWindow( "Diff" ); - } -#endif - - cvAbsDiff( image, read, read ); - cvThreshold( read, read, 0, 1, CV_THRESH_BINARY ); - err = cvRound( cvNorm( read, 0, CV_L1 ))/3; - - cvReleaseImage( &read ); - return err; -} - -static int ProcessImage( IplImage* image, char* funcname, int read ) -{ - char name[1000]; - char lowername[1000]; - int i = 0, err; - - do - { - lowername[i] = (char)my_tolower(funcname[i]); - } - while( funcname[i++] != '\0' ); - - if( read ) - { - err = CheckImage( image, - atsGetTestDataPath(name, filedir_, lowername, "bmp"), - funcname ); - if( err ) - { - trsWrite( ATS_CON | ATS_LST, "Error in %s: %d\n", funcname, err ); - } - return 0; //err; - } - else - { - cvvSaveImage( atsGetTestDataPath(name, filedir_, lowername, "bmp"), image ); - return 0; - } -} - -static int drawing_test() -{ - static int read_params = 0; - static int read = 0; - const int channel = 3; - CvSize size = cvSize(600, 300); - - int i, j; - int Errors = 0; - - if( !read_params ) - { - read_params = 1; - - trsCaseRead( &read, "/n/y", "y", "Read from file ?" ); - } - // Create image - IplImage* image = cvCreateImage( size, IPL_DEPTH_8U, channel ); - - // cvLine - cvZero( image ); - - for( i = 0; i < 100; i++ ) - { - CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); - CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); - - cvLine( image, p1, p2, CV_RGB(178+i, 255-i, i), i % 10 ); - } - Errors += ProcessImage( image, "cvLine", read ); - - // cvLineAA - cvZero( image ); - - for( i = 0; i < 100; i++ ) - { - CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); - CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); - - cvLine( image, p1, p2, CV_RGB(178+i, 255-i, i), 1, CV_AA, 0 ); - } - //Errors += ProcessImage( image, "cvLineAA", read ); - - // cvRectangle - cvZero( image ); - - for( i = 0; i < 100; i++ ) - { - CvPoint p1 = cvPoint( i - 30, i * 4 + 10 ); - CvPoint p2 = cvPoint( size.width + 30 - i, size.height - 10 - i * 4 ); - - cvRectangle( image, p1, p2, CV_RGB(178+i, 255-i, i), i % 10 ); - } - Errors += ProcessImage( image, "cvRectangle", read ); - -#if 0 - named_window( "Diff", 0 ); -#endif - - // cvCircle - cvZero( image ); - - for( i = 0; i < 100; i++ ) - { - CvPoint p1 = cvPoint( i * 3, i * 2 ); - CvPoint p2 = cvPoint( size.width - i * 3, size.height - i * 2 ); - - cvCircle( image, p1, i, CV_RGB(178+i, 255-i, i), i % 10 ); - cvCircle( image, p2, i, CV_RGB(178+i, 255-i, i), i % 10 ); - -#if 0 - show_iplimage( "Diff", image ); - wait_key(0); -#endif - } - Errors += ProcessImage( image, "cvCircle", read ); - - // cvCircleAA - cvZero( image ); - - for( i = 0; i < 100; i++ ) - { - CvPoint p1 = cvPoint( i * 3, i * 2 ); - CvPoint p2 = cvPoint( size.width - i * 3, size.height - i * 2 ); - - cvCircleAA( image, p1, i, RGB(i, 255 - i, 178 + i), 0 ); - cvCircleAA( image, p2, i, RGB(i, 255 - i, 178 + i), 0 ); - } - Errors += ProcessImage( image, "cvCircleAA", read ); - - // cvEllipse - cvZero( image ); - - for( i = 10; i < 100; i += 10 ) - { - CvPoint p1 = cvPoint( i * 6, i * 3 ); - CvSize axes = cvSize( i * 3, i * 2 ); - - cvEllipse( image, p1, axes, - 180 * i / 100, 90 * i / 100, 90 * (i - 100) / 100, - CV_RGB(178+i, 255-i, i), i % 10 ); - } - Errors += ProcessImage( image, "cvEllipse", read ); - - // cvEllipseAA - cvZero( image ); - - for( i = 10; i < 100; i += 10 ) - { - CvPoint p1 = cvPoint( i * 6, i * 3 ); - CvSize axes = cvSize( i * 3, i * 2 ); - - cvEllipseAA( image, p1, axes, - 180 * i / 100, 90 * i / 100, 90 * (i - 100) / 100, - RGB(i, 255 - i, 178 + i), i % 10 ); - } - Errors += ProcessImage( image, "cvEllipseAA", read ); - - // cvFillConvexPoly - cvZero( image ); - - for( j = 0; j < 5; j++ ) - for( i = 0; i < 100; i += 10 ) - { - CvPoint p[4] = {{ j * 100 - 10, i }, { j * 100 + 10, i }, - { j * 100 + 30, i * 2 }, { j * 100 + 170, i * 3 }}; - cvFillConvexPoly( image, p, 4, CV_RGB(178+i, 255-i, i) ); - - } - Errors += ProcessImage( image, "cvFillConvexPoly", read ); - - // cvFillPoly - cvZero( image ); - - for( i = 0; i < 100; i += 10 ) - { - CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; - CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; - CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; - CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; - CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; - - CvPoint* p[] = {p0, p1, p2, p3, p4}; - - int n[] = {4, 4, 4, 4, 4}; - cvFillPoly( image, p, n, 5, CV_RGB(178+i, 255-i, i) ); - } - Errors += ProcessImage( image, "cvFillPoly", read ); - - // cvPolyLine - cvZero( image ); - - for( i = 0; i < 100; i += 10 ) - { - CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; - CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; - CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; - CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; - CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; - - CvPoint* p[] = {p0, p1, p2, p3, p4}; - - int n[] = {4, 4, 4, 4, 4}; - cvPolyLine( image, p, n, 5, 1, CV_RGB(178+i, 255-i, i), i % 10 ); - } - Errors += ProcessImage( image, "cvPolyLine", read ); - - // cvPolyLineAA - cvZero( image ); - - for( i = 0; i < 100; i += 10 ) - { - CvPoint p0[] = {{-10, i}, { 10, i}, { 30, i * 2}, {170, i * 3}}; - CvPoint p1[] = {{ 90, i}, {110, i}, {130, i * 2}, {270, i * 3}}; - CvPoint p2[] = {{190, i}, {210, i}, {230, i * 2}, {370, i * 3}}; - CvPoint p3[] = {{290, i}, {310, i}, {330, i * 2}, {470, i * 3}}; - CvPoint p4[] = {{390, i}, {410, i}, {430, i * 2}, {570, i * 3}}; - - CvPoint* p[] = {p0, p1, p2, p3, p4}; - - int n[] = {4, 4, 4, 4, 4}; - cvPolyLineAA( image, p, n, 5, 1, RGB(i, 255 - i, 178 + i), 0 ); - } - Errors += ProcessImage( image, "cvPolyLineAA", read ); - - // cvPolyLineAA - cvZero( image ); - - for( i = 1; i < 10; i++ ) - { - CvFont font; - cvInitFont( &font, CV_FONT_VECTOR0, - (double)i / 5, (double)i / 5, (double)i / 10, i ); - cvPutText( image, "privet. this is test. :)", cvPoint(0, i * 20), &font, CV_RGB(178+i, 255-i, i) ); - } - Errors += ProcessImage( image, "cvPutText", read ); - - cvReleaseImage( &image ); - - return Errors ? trsResult( TRS_FAIL, "errors" ) : trsResult( TRS_OK, "ok" ); -} - -#if 0 -static int resize_test() -{ - IplImage* src = load_iplimage( "d:/user/vp/archive/art/greatwave.jpg" ); - IplImage* image = cvCreateImage( cvGetSize( src ), 8, 1 ); - - cvCvtColor( src, image, CV_BGR2GRAY ); - - named_window( "image", 1 ); - show_iplimage( "image", image ); - wait_key( 0 ); - - named_window( "result", 1 ); - - for( int i = 0; i < 30; i++ ) - { - IplImage* dst = cvCreateImage( - cvSize( (rand() % 1000) + 1, (rand() % 1000) + 1), - 8, image->nChannels ); - - cvResize( image, dst, CV_INTER_LINEAR ); - show_iplimage( "result", dst ); - - wait_key_ex( 0, 1000 ); - cvReleaseImage( &dst ); - } - - cvReleaseImage( &image ); - destroy_window( "image" ); - destroy_window( "result" ); - - return CV_OK; -} -#endif - -void InitADrawingRegress() -{ - /* Register test functions */ - trsReg( funcs, test_desc, atsAlgoClass, drawing_test ); - //trsReg( "cvResize", "", atsAlgoClass, resize_test ); -} - -#endif diff --git a/tests/cv/src/aeigenobjects.cpp b/tests/cv/src/aeigenobjects.cpp deleted file mode 100644 index 6008561..0000000 --- a/tests/cv/src/aeigenobjects.cpp +++ /dev/null @@ -1,771 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#include "aeigenobjects.inc" - -#define __8U 8 -#define __32F 32 -#define MAXDIFF 1.01 -#define RELDIFF 1.0e-4 - -typedef struct _UserData /* User data structure for callback mode */ -{ - void* addr1; /* Array of objects ROI start addresses */ - void* addr2; - int step1; /* Step in bytes */ - int step2; - CvSize size1; /* ROI or full size */ - CvSize size2; -} UserData; - -/* Testing parameters */ -static char FuncName[] = -"cvCalcCovarMatrixEx, cvCalcEigenObjects, cvCalcDecompCoeff, cvEigenDecomposite, cvEigenProjection"; -static char TestName[] = "Eigen objects functions group test"; -static char TestClass[] = "Algorithm"; -static int obj_number, obj_width, obj_height; -static double rel_bufSize; - -/*-----------------------------=--=-=== Callback functions ===-=--=---------------------*/ - -int read_callback_8u( int ind, void* buf, void* userData) -{ - int i, j, k = 0; - UserData* data = (UserData*)userData; - uchar* start = ((uchar**)(data->addr1))[ind]; - uchar* buff = (uchar*)buf; - - if( ind<0 ) return CV_BADFACTOR_ERR; - if( buf==NULL || userData==NULL ) return CV_NULLPTR_ERR; - - for( i=0; isize1.height; i++, start+=data->step1 ) - for( j=0; jsize1.width; j++, k++ ) - buff[k] = start[j]; - return CV_NO_ERR; -} -/*----------------------*/ -int read_callback_32f( int ind, void* buf, void* userData) -{ - int i, j, k = 0; - UserData* data = (UserData*)userData; - float* start = ((float**)(data->addr2))[ind]; - float* buff = (float*)buf; - - if( ind<0 ) return CV_BADFACTOR_ERR; - if( buf==NULL || userData==NULL ) return CV_NULLPTR_ERR; - - for( i=0; isize2.height; i++, start+=data->step2/4 ) - for( j=0; jsize2.width; j++, k++ ) - buff[k] = start[j]; - return CV_NO_ERR; -} -/*========================*/ -int write_callback_8u( int ind, void* buf, void* userData) -{ - int i, j, k = 0; - UserData* data = (UserData*)userData; - uchar* start = ((uchar**)(data->addr1))[ind]; - uchar* buff = (uchar*)buf; - - if( ind<0 ) return CV_BADFACTOR_ERR; - if( buf==NULL || userData==NULL ) return CV_NULLPTR_ERR; - - for( i=0; isize1.height; i++, start+=data->step1 ) - for( j=0; jsize1.width; j++, k++ ) - start[j] = buff[k]; - return CV_NO_ERR; -} -/*----------------------*/ -int write_callback_32f( int ind, void* buf, void* userData) -{ - int i, j, k = 0; - UserData* data = (UserData*)userData; - float* start = ((float**)(data->addr2))[ind]; - float* buff = (float*)buf; - - if( ind<0 ) return CV_BADFACTOR_ERR; - if( buf==NULL || userData==NULL ) return CV_NULLPTR_ERR; - - for( i=0; isize2.height; i++, start+=data->step2/4 ) - for( j=0; jsize2.width; j++, k++ ) - start[j] = buff[k]; - return CV_NO_ERR; -} - -/*##########################################=-- Test body --=###########################*/ -static int fmaEigenObjects( void ) -{ - int n, n4, i, j, ie, m1, rep = 0, roi, roi4, bufSize; - int roix=0, roiy=0, sizex, sizey, step, step4, step44; - int err0, err1, err2, err3, err4, err5, err6, err7, err=0; - uchar *pro, *pro0, *object; - uchar** objs; - float *covMatr, *covMatr0, *avg, *avg0, *eigVal, *eigVal0, *coeffs, *coeffs0, - covMatrMax, coeffm, singleCoeff0; - float **eigObjs, **eigObjs0; - IplImage **Objs, **EigObjs, **EigObjs0, *Pro, *Pro0, *Object, *Avg, *Avg0; - double eps0, amax=0, singleCoeff, p; - AtsRandState state; - CvSize size; - int r; - CvTermCriteria limit; - UserData userData; - int (*read_callback)( int ind, void* buf, void* userData)= - read_callback_8u; - int (*read2_callback)( int ind, void* buf, void* userData)= - read_callback_32f; - int (*write_callback)( int ind, void* buf, void* userData)= - write_callback_32f; - CvInput* u_r = (CvInput*)&read_callback; - CvInput* u_r2= (CvInput*)&read2_callback; - CvInput* u_w = (CvInput*)&write_callback; - void* read_ = (u_r)->data; - void* read_2 = (u_r2)->data; - void* write_ = (u_w)->data; - - /* Reading test parameters */ - trsiRead( &obj_width, "100", "width of objects" ); - trsiRead( &obj_height, "100", "height of objects" ); - trsiRead( &obj_number, "11", "number of objects" ); - trsdRead( &rel_bufSize, "0.09", "relative i/o buffer size" ); - - if( rel_bufSize < 0.0 ) rel_bufSize = 0.0; - m1 = obj_number - 1; - eps0= 1.0e-27; - n = obj_width * obj_height; - sizex = obj_width, sizey = obj_height; - - Objs = (IplImage**)cvAlloc(sizeof(IplImage*) * obj_number ); - EigObjs = (IplImage**)cvAlloc(sizeof(IplImage*) * m1 ); - EigObjs0 = (IplImage**)cvAlloc(sizeof(IplImage*) * m1 ); - - objs = (uchar**)cvAlloc(sizeof(uchar*) * obj_number ); - eigObjs = (float**)cvAlloc(sizeof(float*) * m1 ); - eigObjs0 = (float**)cvAlloc(sizeof(float*) * m1 ); - covMatr = (float*) cvAlloc(sizeof(float) * obj_number * obj_number ); - covMatr0 = (float*) cvAlloc(sizeof(float) * obj_number * obj_number ); - coeffs = (float*) cvAlloc(sizeof(float*) * m1 ); - coeffs0 = (float*) cvAlloc(sizeof(float*) * m1 ); - eigVal = (float*) cvAlloc(sizeof(float) * obj_number ); - eigVal0 = (float*) cvAlloc(sizeof(float) * obj_number ); - - size.width = obj_width; size.height = obj_height; - atsRandInit( &state, 0, 255, 13 ); - - Avg = cvCreateImage( size, IPL_DEPTH_32F, 1 ); - cvSetImageROI( Avg, cvRect(0, 0, Avg->width, Avg->height) ); - Avg0 = cvCreateImage( size, IPL_DEPTH_32F, 1 ); - cvSetImageROI( Avg0, cvRect(0, 0, Avg0->width, Avg0->height) ); - avg = (float*)Avg->imageData; - avg0 = (float*)Avg0->imageData; - Pro = cvCreateImage( size, IPL_DEPTH_8U, 1 ); - cvSetImageROI( Pro, cvRect(0, 0, Pro->width, Pro->height) ); - Pro0 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); - cvSetImageROI( Pro0, cvRect(0, 0, Pro0->width, Pro0->height) ); - pro = (uchar*)Pro->imageData; - pro0 = (uchar*)Pro0->imageData; - Object = cvCreateImage( size, IPL_DEPTH_8U, 1 ); - cvSetImageROI( Object, cvRect(0, 0, Object->width, Object->height) ); - object = (uchar*)Object->imageData; - - step = Pro->widthStep; step4 = Avg->widthStep; step44 = step4/4; - n = step*obj_height; n4= step44*obj_height; - atsbRand8u ( &state, object, n ); - - for( i=0; iwidth, Objs[i]->height) ); - objs[i] = (uchar*)Objs[i]->imageData; - atsbRand8u ( &state, objs[i], n ); - if( i < m1 ) - { - EigObjs[i] = cvCreateImage( size, IPL_DEPTH_32F, 1 ); - cvSetImageROI( EigObjs[i], cvRect(0, 0, EigObjs[i]->width, EigObjs[i]->height) ); - EigObjs0[i] = cvCreateImage( size, IPL_DEPTH_32F, 1 ); - cvSetImageROI( EigObjs0[i], cvRect(0, 0, EigObjs0[i]->width, EigObjs0[i]->height) ); - } - } - - limit.type = CV_TERMCRIT_ITER; limit.max_iter = m1; limit.epsilon = 1;//(float)eps0; - - bufSize = (int)(4*n*obj_number*rel_bufSize); -trsWrite(TW_RUN|TW_CON, "\n i/o buffer size : %10d bytes\n", bufSize ); - -trsWrite(TW_RUN|TW_CON, "\n ROI unsupported\n" ); - -/* User data fill */ - userData.addr1 = (void*)objs; - userData.addr2 = (void*)eigObjs; - userData.step1 = step; - userData.step2 = step4; - - -repeat: - roi = roiy*step + roix; - roi4 = roiy*step44 + roix; - - Avg->roi->xOffset = roix; Avg->roi->yOffset = roiy; - Avg->roi->height = size.height; Avg->roi->width = size.width; - Avg0->roi->xOffset = roix; Avg0->roi->yOffset = roiy; - Avg0->roi->height = size.height; Avg0->roi->width = size.width; - Pro->roi->xOffset = roix; Pro->roi->yOffset = roiy; - Pro->roi->height = size.height; Pro->roi->width = size.width; - Pro0->roi->xOffset = roix; Pro0->roi->yOffset = roiy; - Pro0->roi->height = size.height; Pro0->roi->width = size.width; - Object->roi->xOffset = roix; Object->roi->yOffset = roiy; - Object->roi->height = size.height; Object->roi->width = size.width; - - for( i=0; iroi->xOffset = roix; Objs[i]->roi->yOffset = roiy; - Objs[i]->roi->height = size.height; Objs[i]->roi->width = size.width; - objs[i] = (uchar*)Objs[i]->imageData + roi; - if( i < m1 ) - { - EigObjs[i]->roi->xOffset = roix; EigObjs[i]->roi->yOffset = roiy; - EigObjs[i]->roi->height = size.height; EigObjs[i]->roi->width = size.width; - EigObjs0[i]->roi->xOffset = roix; EigObjs0[i]->roi->yOffset = roiy; - EigObjs0[i]->roi->height = size.height; EigObjs0[i]->roi->width = size.width; - eigObjs[i] = (float*)EigObjs[i]->imageData + roi4; - eigObjs0[i] = (float*)EigObjs0[i]->imageData + roi4; - } - } - - userData.size1 = userData.size2 = size; - -/* =================================== Test functions run ============================= */ - - r = _cvCalcEigenObjects_8u32fR_q( obj_number, objs, step, eigObjs0, step4, - size, eigVal0, avg0+roi4, step4, &m1, &eps0 ); - - r = _cvEigenDecomposite_8u32fR_q( object+roi, step, m1, eigObjs0, step4, - avg0+roi4, step4, size, coeffs0 ); - - r = _cvEigenProjection_8u32fR_q( m1, eigObjs0, step4, coeffs0, avg0+roi4, step4, - pro0+roi, step, size ); - - r = _cvCalcCovarMatrix_8u32fR_q( obj_number, objs, step, avg0+roi4, step4, - size, covMatr0 ); - - singleCoeff0 = _cvCalcDecompCoeff_8u32fR_q( object+roi, step, eigObjs0[0], step4, - avg0+roi4, step4, size ); - - covMatrMax = 0.f; - for( i=0; i RELDIFF ) err7++; - - cvEigenDecomposite( Object, - m1, - (void*)EigObjs, - CV_EIGOBJ_NO_CALLBACK, - (void*)&userData, - Avg, - coeffs ); - cvEigenProjection ( (void*)EigObjs, - m1, - CV_EIGOBJ_NO_CALLBACK, - (void*)&userData, - coeffs, - Avg, - Pro ); - -/* Covariance matrix comparision */ - for( i=0; i RELDIFF*fabs(covMatrMax) ) err6++; - -/* Averaged object comparision */ - for( i=0; i MAXDIFF ) err1++; - } - -/* Eigen objects comparision */ - for( ie=0; ie RELDIFF ) err2++; - } - -/* Eigen values comparision */ - for( i=0; i RELDIFF ) err3++; - } - -/* Decomposition coefficients comparision */ - for( i=0; i RELDIFF ) err4++; - -/* Projection comparision */ - for( i=0; i MAXDIFF ) err5++; - } - - err0 = 0; - p = 100.f*err6/(float)(obj_number*obj_number); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Covar. matrix - %d errors (%7.3f %% );\n", err6, p ); - err0 += err6; - } - p = 100.f*err1/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Averaged obj. - %d errors (%7.3f %% );\n", err1, p ); - err0 += err1; - } - p = 100.f*err3/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen values - %d errors (%7.3f %% );\n", err3, p ); - err0 += err3; - } - p = 100.f*err2/(float)(size.height*size.width*m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen objects - %d errors (%7.3f %% );\n", err2, p ); - err0 += err2; - } - p = 100.f*err4/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Decomp.coeffs - %d errors (%7.3f %% );\n", err4, p ); - err0 += err4; - } - if( ((float)err7)/m1 > 0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Single dec.c. - %d errors ;\n", err7); - err0 += err7; - } - p = 100.f*err5/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Projection - %d errors (%7.3f %% );\n", err5, p ); - err0 += err5; - } - trsWrite(TW_RUN|TW_CON, " without callbacks : %8d errors;\n", err0 ); - - err += err0; - -/*- - - - - - - - - - - - - - - - - - - - - input callback - - - - - - - - - - - - - */ - for( i=0; i MAXDIFF ) err1++; - } - -/* Eigen objects comparision */ - for( ie=0; ie RELDIFF ) err2++; - } - -/* Eigen values comparision */ - for( i=0; i RELDIFF ) err3++; - } - -/* Projection comparision */ - for( i=0; i MAXDIFF ) err5++; - } - -/* Decomposition coefficients comparision */ - for( i=0; i RELDIFF ) err4++; - - err0 = 0; - p = 100.f*err1/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Averaged obj. - %d errors (%7.3f %% );\n", err1, p ); - err0 += err1; - } - p = 100.f*err3/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen values - %d errors (%7.3f %% );\n", err3, p ); - err0 += err3; - } - p = 100.f*err2/(float)(size.height*size.width*m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen objects - %d errors (%7.3f %% );\n", err2, p ); - err0 += err2; - } - p = 100.f*err4/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Decomp.coeffs - %d errors (%7.3f %% );\n", err4, p ); - err0 += err4; - } - p = 100.f*err5/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Projection - %d errors (%7.3f %% );\n", err5, p ); - err0 += err5; - } - trsWrite(TW_RUN|TW_CON, " input callback : %8d errors;\n", err0 ); - - err += err0; - -/*- - - - - - - - - - - - - - - - - - - - - output callback - - - - - - - - - - - - - */ - for( i=0; i MAXDIFF ) err1++; - } - -/* Eigen objects comparision */ - for( ie=0; ie RELDIFF ) err2++; - } - -/* Eigen values comparision */ - for( i=0; i RELDIFF ) err3++; - } - - err0 = 0; - p = 100.f*err1/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Averaged obj. - %d errors (%7.3f %% );\n", err1, p ); - err0 += err1; - } - p = 100.f*err3/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen values - %d errors (%7.3f %% );\n", err3, p ); - err0 += err3; - } - p = 100.f*err2/(float)(size.height*size.width*m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen objects - %d errors (%7.3f %% );\n", err2, p ); - err0 += err2; - } - trsWrite(TW_RUN|TW_CON, " output callback : %8d errors;\n", err0 ); - - err += err0; - -/*- - - - - - - - - - - - - - - - - - - - - both callbacks - - - - - - - - - - - - - */ - for( i=0; i MAXDIFF ) err1++; - } - -/* Eigen objects comparision */ - for( ie=0; ie RELDIFF ) err2++; - } - -/* Eigen values comparision */ - for( i=0; i RELDIFF ) err3++; - } - - err0 = 0; - p = 100.f*err1/(float)(size.height*size.width); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Averaged obj. - %d errors (%7.3f %% );\n", err1, p ); - err0 += err1; - } - p = 100.f*err3/(float)(m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen values - %d errors (%7.3f %% );\n", err3, p ); - err0 += err3; - } - p = 100.f*err2/(float)(size.height*size.width*m1); - if( p>0.1 ) - { - trsWrite(TW_RUN|TW_CON, " Eigen objects - %d errors (%7.3f %% );\n", err2, p ); - err0 += err2; - } - trsWrite(TW_RUN|TW_CON, " both callbacks : %8d errors;\n", err0 ); - - err += err0; - - -/*================================-- test with ROI --===================================*/ - - if(!rep) - { - roix = (int)(0.157f*obj_width); - roiy = (int)(0.131f*obj_height); - sizex = (int)(0.611f*obj_width); - sizey = (int)(0.737f*obj_height); - roi = roiy*obj_width + roix; - -trsWrite(TW_RUN|TW_CON, "\n ROI supported\n" ); - rep++; - size.width = sizex; size.height = sizey; - - goto repeat; - } - -/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ free memory ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/ - cvReleaseImage( &Avg ); - cvReleaseImage( &Avg0 ); - cvReleaseImage( &Pro ); - cvReleaseImage( &Pro0 ); - cvReleaseImage( &Object ); - for( i=0; i objStep || 4*size.width > avgStep || size.height < 1) - return CV_BADSIZE_ERR; - if ( objects == NULL || avg == NULL || covarMatrix == NULL ) return CV_NULLPTR_ERR; - - avgStep /= 4; - - for(i=0; i ax ) - { - Amax /= n; - do /* while (ind) */ - { - int p, q; - float *V1 = V, *A1 = A; - ind = 0; - for(p=0; p ax ) */ - - for(i=0, k=0; i objStep || 4*size.width > eigStep || - 4*size.width > avgStep || size.height < 1) return CV_BADSIZE_ERR; - if ( objects == NULL || eigObjs == NULL || eigVals == NULL || - avg == NULL || nEigObjs == NULL || eps == NULL ) return CV_NULLPTR_ERR; - for( i=0; i objStep || 4*size.width > eigStep - || 4*size.width > avgStep || size.height < 1) return -1.0e30f; - if ( obj == NULL || eigObj == NULL || avg == NULL ) return -1.0e30f; - - eigStep /= 4; - avgStep /= 4; - - for(i = 0; i < size.height; i++, obj += objStep, eigObj += eigStep, avg += avgStep) - for(k = 0; k < size.width; k++) - w += eigObj[k]*( (float)obj[k] - avg[k] ); - - return w; -} -/*______________________________________________________________________________________*/ - -int _cvEigenDecomposite_8u32fR_q( uchar* obj, - int objStep, - int nEigObjs, - float** eigObjs, - int eigStep, - float* avg, - int avgStep, - CvSize size, - float* coeffs ) -{ - int i; - - if ( nEigObjs < 2 ) return CV_BADFACTOR_ERR; - if ( size.width > objStep || 4*size.width > eigStep || - 4*size.width > avgStep || size.height < 1) return CV_BADSIZE_ERR; - if ( obj == NULL || eigObjs == NULL || coeffs == NULL || avg == NULL) - return CV_NULLPTR_ERR; - - for(i=0; i avgStep || 4*size.width > eigStep || size.height < 1) - return CV_BADSIZE_ERR; - if ( rest == NULL || eigens == NULL || avg == NULL || coeffs == NULL ) - return CV_NULLPTR_ERR; - eigStep /= 4; - avgStep /= 4; - - for(i = 0; i < size.height; i++, rest+=restStep, avg+=avgStep) - { - int ij = i*eigStep; - for(j = 0; j < size.width; j++, ij++) - { - float w = avg[j]; - for(k=0; k255.499f ? 255.499f : w; - rest[j] = (uchar)cvRound( w ); - } - } - return CV_NO_ERR; -} -/*______________________________________________________________________________________*/ - -/* << End of file >> */ diff --git a/tests/cv/src/aemd.cpp b/tests/cv/src/aemd.cpp deleted file mode 100644 index 6869b40..0000000 --- a/tests/cv/src/aemd.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -/*////////////////////// emd_test /////////////////////////*/ - -typedef struct matr_info -{ - float* x_origin; - float* y_origin; - float* matr; - int rows; - int cols; -} -matr_info; - -static float matr_dist( const float* x, const float* y, void* param ) -{ - matr_info* mi = (matr_info*)param; - int i = (int)(x - mi->x_origin) - 1; - int j = (int)(y - mi->y_origin) - 1; - assert( 0 <= i && i < mi->rows && - 0 <= j && j < mi->cols ); - return mi->matr[i*mi->cols + j]; -} - -class CV_EMDTest : public CvTest -{ -public: - CV_EMDTest(); -protected: - void run(int); -}; - - -CV_EMDTest::CV_EMDTest(): - CvTest( "emd", "cvCalcEMD" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_EMDTest::run( int ) -{ - int code = CvTS::OK; - const double success_error_level = 1e-6; - #define M 10000 - double emd0 = 2460./210; - static float cost[] = - { - 16, 16, 13, 22, 17, - 14, 14, 13, 19, 15, - 19, 19, 20, 23, M, - M , 0, M, 0, 0 - }; - static float w1[] = { 50, 60, 50, 50 }, - w2[] = { 30, 20, 70, 30, 60 }; - matr_info mi; - float emd; - - mi.x_origin = w1; - mi.y_origin = w2; - - mi.rows = sizeof(w1)/sizeof(w1[0]); - mi.cols = sizeof(w2)/sizeof(w2[0]); - mi.matr = cost; - - emd = cvCalcEMD( w1, mi.rows, w2, mi.cols, 0, (CvDisType)-1, - matr_dist, 0, &mi ); - - if( fabs( emd - emd0 ) > success_error_level*emd0 ) - { - ts->printf( CvTS::LOG, - "The computed distance is %.2f, while it should be %.2f\n", emd, emd0 ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_EMDTest emd_test; - -/* End of file. */ diff --git a/tests/cv/src/aestimaterigid.cpp b/tests/cv/src/aestimaterigid.cpp deleted file mode 100644 index b698339..0000000 --- a/tests/cv/src/aestimaterigid.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -class CV_RigidTransform_Test : public CvTest -{ -public: - CV_RigidTransform_Test(); - ~CV_RigidTransform_Test(); -protected: - void run(int); - - bool testNPoints(int); - bool testImage(); -}; - -CV_RigidTransform_Test::CV_RigidTransform_Test(): CvTest( "optflow-estimate-rigid", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_RigidTransform_Test::~CV_RigidTransform_Test() {} - -struct WrapAff2D -{ - const double *F; - WrapAff2D(const Mat& aff) : F(aff.ptr()) {} - Point2f operator()(const Point2f& p) - { - return Point2d( p.x * F[0] + p.y * F[1] + F[2], - p.x * F[3] + p.y * F[4] + F[5]); - } -}; - -bool CV_RigidTransform_Test::testNPoints(int from) -{ - cv::RNG rng(*ts->get_rng()); - - int progress = 0; - int k, ntests = 10000; - - for( k = from; k < ntests; k++ ) - { - ts->update_context( this, k, true ); - progress = update_progress(progress, k, ntests, 0); - - Mat aff(2, 3, CV_64F); - rng.fill(aff, CV_RAND_UNI, Scalar(-2), Scalar(2)); - - int n = (unsigned)rng % 100 + 10; - - Mat fpts(1, n, CV_32FC2); - Mat tpts(1, n, CV_32FC2); - - rng.fill(fpts, CV_RAND_UNI, Scalar(0,0), Scalar(10,10)); - transform(fpts.ptr(), fpts.ptr() + n, tpts.ptr(), WrapAff2D(aff)); - - Mat noise(1, n, CV_32FC2); - rng.fill(noise, CV_RAND_NORMAL, Scalar::all(0), Scalar::all(0.001*(n<=7 ? 0 : n <= 30 ? 1 : 10))); - tpts += noise; - - Mat aff_est = estimateRigidTransform(fpts, tpts, true); - - double thres = 0.1*norm(aff); - double d = norm(aff_est, aff, NORM_L2); - if (d > thres) - { - double dB=0, nB=0; - if (n <= 4) - { - Mat A = fpts.reshape(1, 3); - Mat B = A - repeat(A.row(0), 3, 1), Bt = B.t(); - B = Bt*B; - dB = cv::determinant(B); - nB = norm(B); - if( fabs(dB) < 0.01*nB ) - continue; - } - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - ts->printf( CvTS::LOG, "Threshold = %f, norm of difference = %f", thres, d ); - return false; - } - } - return true; -} - -bool CV_RigidTransform_Test::testImage() -{ - Mat img; - pyrDown(imread( string(ts->get_data_path()) + "shared/graffiti.png", 1), img); - - Mat aff = cv::getRotationMatrix2D(Point(img.cols/2, img.rows/2), 1, 0.99); - aff.ptr()[2]+=3; - aff.ptr()[5]+=3; - - Mat rotated; - warpAffine(img, rotated, aff, img.size()); - - Mat aff_est = estimateRigidTransform(img, rotated, true); - - const double thres = 0.03; - if (norm(aff_est, aff, NORM_INF) > thres) - { - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - ts->printf( CvTS::LOG, "Threshold = %f, norm of difference = %f", thres, - norm(aff_est, aff, NORM_INF) ); - return false; - } - - return true; -} - -void CV_RigidTransform_Test::run( int start_from ) -{ - DefaultRngAuto dra; (void)dra; - - if (!testNPoints(start_from)) - return; - - if (!testImage()) - return; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_RigidTransform_Test CV_RigidTransform_test; - diff --git a/tests/cv/src/afeatures2d.cpp b/tests/cv/src/afeatures2d.cpp deleted file mode 100644 index 59a4ac2..0000000 --- a/tests/cv/src/afeatures2d.cpp +++ /dev/null @@ -1,1014 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ -#include "cvtest.h" -#include "opencv2/core/core.hpp" - -using namespace std; -using namespace cv; - -const string FEATURES2D_DIR = "features2d"; -const string DETECTOR_DIR = FEATURES2D_DIR + "/feature_detectors"; -const string DESCRIPTOR_DIR = FEATURES2D_DIR + "/descriptor_extractors"; -const string IMAGE_FILENAME = "tsukuba.png"; - -/****************************************************************************************\ -* Regression tests for feature detectors comparing keypoints. * -\****************************************************************************************/ - -class CV_FeatureDetectorTest : public CvTest -{ -public: - CV_FeatureDetectorTest( const char* testName, const Ptr& _fdetector ) : - CvTest( testName, "cv::FeatureDetector::detect"), fdetector(_fdetector) {} - -protected: - bool isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 ); - void compareKeypointSets( const vector& validKeypoints, const vector& calcKeypoints ); - - void emptyDataTest(); - void regressionTest(); // TODO test of detect() with mask - - virtual void run( int ); - - Ptr fdetector; -}; - -void CV_FeatureDetectorTest::emptyDataTest() -{ - assert( !fdetector.empty() && !fdetector->empty() ); - - // One image. - Mat image; - vector keypoints; - try - { - fdetector->detect( image, keypoints ); - } - catch(...) - { - ts->printf( CvTS::LOG, "detect() on empty image must not generate exception (1).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - if( !keypoints.empty() ) - { - ts->printf( CvTS::LOG, "detect() on empty image must return empty keypoints vector (1).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - // Several images. - vector images; - vector > keypointCollection; - try - { - fdetector->detect( images, keypointCollection ); - } - catch(...) - { - ts->printf( CvTS::LOG, "detect() on empty image vector must not generate exception (2).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } -} - -bool CV_FeatureDetectorTest::isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 ) -{ - const float maxPtDif = 1.f; - const float maxSizeDif = 1.f; - const float maxAngleDif = 2.f; - const float maxResponseDif = 0.1f; - - float dist = (float)norm( p1.pt - p2.pt ); - return (dist < maxPtDif && - fabs(p1.size - p2.size) < maxSizeDif && - abs(p1.angle - p2.angle) < maxAngleDif && - abs(p1.response - p2.response) < maxResponseDif && - p1.octave == p2.octave && - p1.class_id == p2.class_id ); -} - -void CV_FeatureDetectorTest::compareKeypointSets( const vector& validKeypoints, const vector& calcKeypoints ) -{ - const float maxCountRatioDif = 0.01f; - - // Compare counts of validation and calculated keypoints. - float countRatio = (float)validKeypoints.size() / (float)calcKeypoints.size(); - if( countRatio < 1 - maxCountRatioDif || countRatio > 1.f + maxCountRatioDif ) - { - ts->printf( CvTS::LOG, "Bad keypoints count ratio (validCount = %d, calcCount = %d).\n", - validKeypoints.size(), calcKeypoints.size() ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - int progress = 0, progressCount = validKeypoints.size() * calcKeypoints.size(); - int badPointCount = 0, commonPointCount = max(validKeypoints.size(), calcKeypoints.size()); - for( size_t v = 0; v < validKeypoints.size(); v++ ) - { - int nearestIdx = -1; - float minDist = std::numeric_limits::max(); - - for( size_t c = 0; c < calcKeypoints.size(); c++ ) - { - progress = update_progress( progress, v*calcKeypoints.size() + c, progressCount, 0 ); - float curDist = (float)norm( calcKeypoints[c].pt - validKeypoints[v].pt ); - if( curDist < minDist ) - { - minDist = curDist; - nearestIdx = c; - } - } - - assert( minDist >= 0 ); - if( !isSimilarKeypoints( validKeypoints[v], calcKeypoints[nearestIdx] ) ) - badPointCount++; - } - ts->printf( CvTS::LOG, "badPointCount = %d; validPointCount = %d; calcPointCount = %d\n", - badPointCount, validKeypoints.size(), calcKeypoints.size() ); - if( badPointCount > 0.9 * commonPointCount ) - { - ts->printf( CvTS::LOG, " - Bad accuracy!\n" ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - ts->printf( CvTS::LOG, " - OK\n" ); -} - -void CV_FeatureDetectorTest::regressionTest() -{ - assert( !fdetector.empty() && !fdetector->empty() ); - string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME; - string resFilename = string(ts->get_data_path()) + DETECTOR_DIR + "/" + string(name) + ".xml.gz"; - - // Read the test image. - Mat image = imread( imgFilename ); - if( image.empty() ) - { - ts->printf( CvTS::LOG, "Image %s can not be read.\n", imgFilename.c_str() ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - FileStorage fs( resFilename, FileStorage::READ ); - - // Compute keypoints. - vector calcKeypoints; - fdetector->detect( image, calcKeypoints ); - - if( fs.isOpened() ) // Compare computed and valid keypoints. - { - // TODO compare saved feature detector params with current ones - - // Read validation keypoints set. - vector validKeypoints; - read( fs["keypoints"], validKeypoints ); - if( validKeypoints.empty() ) - { - ts->printf( CvTS::LOG, "Keypoints can not be read.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - compareKeypointSets( validKeypoints, calcKeypoints ); - } - else // Write detector parameters and computed keypoints as validation data. - { - fs.open( resFilename, FileStorage::WRITE ); - if( !fs.isOpened() ) - { - ts->printf( CvTS::LOG, "File %s can not be opened to write.\n", resFilename.c_str() ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - else - { - fs << "detector_params" << "{"; - fdetector->write( fs ); - fs << "}"; - - write( fs, "keypoints", calcKeypoints ); - } - } -} - -void CV_FeatureDetectorTest::run( int /*start_from*/ ) -{ - if( fdetector.empty() || fdetector->empty() ) - { - ts->printf( CvTS::LOG, "Feature detector is empty.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - emptyDataTest(); - regressionTest(); - - ts->set_failed_test_info( CvTS::OK ); -} - -/****************************************************************************************\ -* Regression tests for descriptor extractors. * -\****************************************************************************************/ -static void writeMatInBin( const Mat& mat, const string& filename ) -{ - FILE* f = fopen( filename.c_str(), "wb"); - if( f ) - { - int type = mat.type(); - fwrite( (void*)&mat.rows, sizeof(int), 1, f ); - fwrite( (void*)&mat.cols, sizeof(int), 1, f ); - fwrite( (void*)&type, sizeof(int), 1, f ); - int dataSize = mat.step * mat.rows * mat.channels(); - fwrite( (void*)&dataSize, sizeof(int), 1, f ); - fwrite( (void*)mat.data, 1, dataSize, f ); - fclose(f); - } -} - -static Mat readMatFromBin( const string& filename ) -{ - FILE* f = fopen( filename.c_str(), "rb" ); - if( f ) - { - int rows, cols, type, dataSize; - fread( (void*)&rows, sizeof(int), 1, f ); - fread( (void*)&cols, sizeof(int), 1, f ); - fread( (void*)&type, sizeof(int), 1, f ); - fread( (void*)&dataSize, sizeof(int), 1, f ); - - uchar* data = (uchar*)cvAlloc(dataSize); - fread( (void*)data, 1, dataSize, f ); - fclose(f); - - return Mat( rows, cols, type, data ); - } - return Mat(); -} - -template -class CV_DescriptorExtractorTest : public CvTest -{ -public: - typedef typename Distance::ValueType ValueType; - typedef typename Distance::ResultType DistanceType; - - CV_DescriptorExtractorTest( const char* testName, DistanceType _maxDist, const Ptr& _dextractor, float _prevTime, - Distance d = Distance() ): - CvTest( testName, "cv::DescriptorExtractor::compute" ), - maxDist(_maxDist), prevTime(_prevTime), dextractor(_dextractor), distance(d) {} -protected: - virtual void createDescriptorExtractor(){} - - void compareDescriptors( const Mat& validDescriptors, const Mat& calcDescriptors ) - { - if( validDescriptors.size != calcDescriptors.size || validDescriptors.type() != calcDescriptors.type() ) - { - ts->printf(CvTS::LOG, "Valid and computed descriptors matrices must have the same size and type.\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - CV_Assert( DataType::type == validDescriptors.type() ); - - int dimension = validDescriptors.cols; - DistanceType curMaxDist = -std::numeric_limits::max(); - for( int y = 0; y < validDescriptors.rows; y++ ) - { - DistanceType dist = distance( validDescriptors.ptr(y), calcDescriptors.ptr(y), dimension ); - if( dist > curMaxDist ) - curMaxDist = dist; - } - - stringstream ss; - ss << "Max distance between valid and computed descriptors " << curMaxDist; - if( curMaxDist < maxDist ) - ss << "." << endl; - else - { - ss << ">" << maxDist << " - bad accuracy!"<< endl; - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - } - ts->printf(CvTS::LOG, ss.str().c_str() ); - } - - void emptyDataTest() - { - assert( !dextractor.empty() && !dextractor->empty() ); - - // One image. - Mat image; - vector keypoints; - Mat descriptors; - - try - { - dextractor->compute( image, keypoints, descriptors ); - } - catch(...) - { - ts->printf( CvTS::LOG, "compute() on empty image and empty keypoints must not generate exception (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - } - - image.create( 50, 50, CV_8UC3 ); - try - { - dextractor->compute( image, keypoints, descriptors ); - } - catch(...) - { - ts->printf( CvTS::LOG, "compute() on nonempty image and empty keypoints must not generate exception (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - } - - // Several images. - vector images; - vector > keypointsCollection; - vector descriptorsCollection; - try - { - dextractor->compute( images, keypointsCollection, descriptorsCollection ); - } - catch(...) - { - ts->printf( CvTS::LOG, "compute() on empty images and empty keypoints collection must not generate exception (2).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - } - } - - void regressionTest() - { - assert( !dextractor.empty() && !dextractor->empty() ); - - // Read the test image. - string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME; - - Mat img = imread( imgFilename ); - if( img.empty() ) - { - ts->printf( CvTS::LOG, "Image %s can not be read.\n", imgFilename.c_str() ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - vector keypoints; - FileStorage fs( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::READ ); - if( fs.isOpened() ) - { - read( fs.getFirstTopLevelNode(), keypoints ); - - Mat calcDescriptors; - double t = (double)getTickCount(); - dextractor->compute( img, keypoints, calcDescriptors ); - t = getTickCount() - t; - ts->printf(CvTS::LOG, "\nAverage time of computiting one descriptor = %g ms (previous time = %g ms).\n", t/((double)cvGetTickFrequency()*1000.)/calcDescriptors.rows, prevTime ); - - if( calcDescriptors.rows != (int)keypoints.size() ) - { - ts->printf( CvTS::LOG, "Count of computed descriptors and keypoints count must be equal.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - if( calcDescriptors.cols != dextractor->descriptorSize() || calcDescriptors.type() != dextractor->descriptorType() ) - { - ts->printf( CvTS::LOG, "Incorrect descriptor size or descriptor type.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - // TODO read and write descriptor extractor parameters and check them - Mat validDescriptors = readDescriptors(); - if( !validDescriptors.empty() ) - compareDescriptors( validDescriptors, calcDescriptors ); - else - { - if( !writeDescriptors( calcDescriptors ) ) - { - ts->printf( CvTS::LOG, "Descriptors can not be written.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - } - } - else - { - ts->printf( CvTS::LOG, "Compute and write keypoints.\n" ); - fs.open( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::WRITE ); - if( fs.isOpened() ) - { - SurfFeatureDetector fd; - fd.detect(img, keypoints); - write( fs, "keypoints", keypoints ); - } - else - { - ts->printf(CvTS::LOG, "File for writting keypoints can not be opened.\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - } - } - - void run(int) - { - createDescriptorExtractor(); - if( dextractor.empty() || dextractor->empty() ) - { - ts->printf(CvTS::LOG, "Descriptor extractor is empty.\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - emptyDataTest(); - regressionTest(); - - ts->set_failed_test_info( CvTS::OK ); - } - - virtual Mat readDescriptors() - { - Mat res = readMatFromBin( string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) ); - return res; - } - - virtual bool writeDescriptors( Mat& descs ) - { - writeMatInBin( descs, string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) ); - return true; - } - - const DistanceType maxDist; - const float prevTime; - - Ptr dextractor; - Distance distance; - -private: - CV_DescriptorExtractorTest& operator=(const CV_DescriptorExtractorTest&) { return *this; } -}; - -template -class CV_CalonderDescriptorExtractorTest : public CV_DescriptorExtractorTest -{ -public: - CV_CalonderDescriptorExtractorTest( const char* testName, float _normDif, float _prevTime ) : - CV_DescriptorExtractorTest( testName, _normDif, Ptr(), _prevTime ) - {} - -protected: - virtual void createDescriptorExtractor() - { - string filename = string(CV_DescriptorExtractorTest::ts->get_data_path()) + - FEATURES2D_DIR + "/calonder_classifier.rtc"; - CV_DescriptorExtractorTest::dextractor = - new CalonderDescriptorExtractor( filename ); - if( CV_DescriptorExtractorTest::dextractor->empty() ) - { - stringstream ss; ss << "Calonder descriptor extractor can not be loaded from file" << filename<< endl; - CV_DescriptorExtractorTest::ts->printf( CvTS::LOG, ss.str().c_str() ); - CV_DescriptorExtractorTest::ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - } - } -}; - -/****************************************************************************************\ -* Algorithmic tests for descriptor matchers * -\****************************************************************************************/ -class CV_DescriptorMatcherTest : public CvTest -{ -public: - CV_DescriptorMatcherTest( const char* testName, const Ptr& _dmatcher, float _badPart ) : - CvTest( testName, "cv::DescritorMatcher::[,knn,radius]match()"), badPart(_badPart), dmatcher(_dmatcher) - {} -protected: - static const int dim = 500; - static const int queryDescCount = 300; // must be even number because we split train data in some cases in two - static const int countFactor = 4; // do not change it - const float badPart; - - virtual void run( int ); - void generateData( Mat& query, Mat& train ); - - void emptyDataTest(); - void matchTest( const Mat& query, const Mat& train ); - void knnMatchTest( const Mat& query, const Mat& train ); - void radiusMatchTest( const Mat& query, const Mat& train ); - - Ptr dmatcher; -private: - CV_DescriptorMatcherTest& operator=(const CV_DescriptorMatcherTest&) { return *this; } -}; - -void CV_DescriptorMatcherTest::emptyDataTest() -{ - assert( !dmatcher.empty() && !dmatcher->empty() ); - - Mat queryDescriptors, trainDescriptors, mask; - vector trainDescriptorCollection, masks; - vector matches; - vector > vmatches; - - try - { - dmatcher->match( queryDescriptors, trainDescriptors, matches, mask ); - } - catch(...) - { - ts->printf( CvTS::LOG, "match() on empty descriptors must not generate exception (1).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->knnMatch( queryDescriptors, trainDescriptors, vmatches, 2, mask ); - } - catch(...) - { - ts->printf( CvTS::LOG, "knnMatch() on empty descriptors must not generate exception (1).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->radiusMatch( queryDescriptors, trainDescriptors, vmatches, 10.f, mask ); - } - catch(...) - { - ts->printf( CvTS::LOG, "radiusMatch() on empty descriptors must not generate exception (1).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->add( trainDescriptorCollection ); - } - catch(...) - { - ts->printf( CvTS::LOG, "add() on empty descriptors must not generate exception.\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->match( queryDescriptors, matches, masks ); - } - catch(...) - { - ts->printf( CvTS::LOG, "match() on empty descriptors must not generate exception (2).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->knnMatch( queryDescriptors, vmatches, 2, masks ); - } - catch(...) - { - ts->printf( CvTS::LOG, "knnMatch() on empty descriptors must not generate exception (2).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - try - { - dmatcher->radiusMatch( queryDescriptors, vmatches, 10.f, masks ); - } - catch(...) - { - ts->printf( CvTS::LOG, "radiusMatch() on empty descriptors must not generate exception (2).\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - -} - -void CV_DescriptorMatcherTest::generateData( Mat& query, Mat& train ) -{ - RNG& rng = theRNG(); - - // Generate query descriptors randomly. - // Descriptor vector elements are integer values. - Mat buf( queryDescCount, dim, CV_32SC1 ); - rng.fill( buf, RNG::UNIFORM, Scalar::all(0), Scalar(3) ); - buf.convertTo( query, CV_32FC1 ); - - // Generate train decriptors as follows: - // copy each query descriptor to train set countFactor times - // and perturb some one element of the copied descriptors in - // in ascending order. General boundaries of the perturbation - // are (0.f, 1.f). - train.create( query.rows*countFactor, query.cols, CV_32FC1 ); - float step = 1.f / countFactor; - for( int qIdx = 0; qIdx < query.rows; qIdx++ ) - { - Mat queryDescriptor = query.row(qIdx); - for( int c = 0; c < countFactor; c++ ) - { - int tIdx = qIdx * countFactor + c; - Mat trainDescriptor = train.row(tIdx); - queryDescriptor.copyTo( trainDescriptor ); - int elem = rng(dim); - float diff = rng.uniform( step*c, step*(c+1) ); - trainDescriptor.at(0, elem) += diff; - } - } -} - -void CV_DescriptorMatcherTest::matchTest( const Mat& query, const Mat& train ) -{ - dmatcher->clear(); - - // test const version of match() - { - vector matches; - dmatcher->match( query, train, matches ); - - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test match() function (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - else - { - int badCount = 0; - for( size_t i = 0; i < matches.size(); i++ ) - { - DMatch match = matches[i]; - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) ) - badCount++; - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - ts->printf( CvTS::LOG, "%f - too large bad matches part while test match() function (1).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - } - } - - // test version of match() with add() - { - vector matches; - // make add() twice to test such case - dmatcher->add( vector(1,train.rowRange(0, train.rows/2)) ); - dmatcher->add( vector(1,train.rowRange(train.rows/2, train.rows)) ); - // prepare masks (make first nearest match illegal) - vector masks(2); - for(int mi = 0; mi < 2; mi++ ) - { - masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1)); - for( int di = 0; di < queryDescCount/2; di++ ) - masks[mi].col(di*countFactor).setTo(Scalar::all(0)); - } - - dmatcher->match( query, matches, masks ); - - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test match() function (2).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - else - { - int badCount = 0; - for( size_t i = 0; i < matches.size(); i++ ) - { - DMatch match = matches[i]; - int shift = dmatcher->isMaskSupported() ? 1 : 0; - { - if( i < queryDescCount/2 ) - { - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + shift) || (match.imgIdx != 0) ) - badCount++; - } - else - { - if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + shift) || (match.imgIdx != 1) ) - badCount++; - } - } - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - ts->printf( CvTS::LOG, "%f - too large bad matches part while test match() function (2).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - } - } - } -} - -void CV_DescriptorMatcherTest::knnMatchTest( const Mat& query, const Mat& train ) -{ - dmatcher->clear(); - - // test const version of knnMatch() - { - const int knn = 3; - - vector > matches; - dmatcher->knnMatch( query, train, matches, knn ); - - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test knnMatch() function (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - else - { - int badCount = 0; - for( size_t i = 0; i < matches.size(); i++ ) - { - if( (int)matches[i].size() != knn ) - badCount++; - else - { - int localBadCount = 0; - for( int k = 0; k < knn; k++ ) - { - DMatch match = matches[i][k]; - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor+k) || (match.imgIdx != 0) ) - localBadCount++; - } - badCount += localBadCount > 0 ? 1 : 0; - } - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - ts->printf( CvTS::LOG, "%f - too large bad matches part while test knnMatch() function (1).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - } - } - - // test version of knnMatch() with add() - { - const int knn = 2; - vector > matches; - // make add() twice to test such case - dmatcher->add( vector(1,train.rowRange(0, train.rows/2)) ); - dmatcher->add( vector(1,train.rowRange(train.rows/2, train.rows)) ); - // prepare masks (make first nearest match illegal) - vector masks(2); - for(int mi = 0; mi < 2; mi++ ) - { - masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1)); - for( int di = 0; di < queryDescCount/2; di++ ) - masks[mi].col(di*countFactor).setTo(Scalar::all(0)); - } - - dmatcher->knnMatch( query, matches, knn, masks ); - - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test knnMatch() function (2).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - else - { - int badCount = 0; - int shift = dmatcher->isMaskSupported() ? 1 : 0; - for( size_t i = 0; i < matches.size(); i++ ) - { - if( (int)matches[i].size() != knn ) - badCount++; - else - { - int localBadCount = 0; - for( int k = 0; k < knn; k++ ) - { - DMatch match = matches[i][k]; - { - if( i < queryDescCount/2 ) - { - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) || - (match.imgIdx != 0) ) - localBadCount++; - } - else - { - if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) || - (match.imgIdx != 1) ) - localBadCount++; - } - } - } - badCount += localBadCount > 0 ? 1 : 0; - } - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - ts->printf( CvTS::LOG, "%f - too large bad matches part while test knnMatch() function (2).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - } - } - } -} - -void CV_DescriptorMatcherTest::radiusMatchTest( const Mat& query, const Mat& train ) -{ - dmatcher->clear(); - // test const version of match() - { - const float radius = 1.f/countFactor; - vector > matches; - dmatcher->radiusMatch( query, train, matches, radius ); - - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - else - { - int badCount = 0; - for( size_t i = 0; i < matches.size(); i++ ) - { - if( (int)matches[i].size() != 1 ) - badCount++; - else - { - DMatch match = matches[i][0]; - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) ) - badCount++; - } - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - ts->printf( CvTS::LOG, "%f - too large bad matches part while test radiusMatch() function (1).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - } - } - - // test version of match() with add() - { - int n = 3; - const float radius = 1.f/countFactor * n; - vector > matches; - // make add() twice to test such case - dmatcher->add( vector(1,train.rowRange(0, train.rows/2)) ); - dmatcher->add( vector(1,train.rowRange(train.rows/2, train.rows)) ); - // prepare masks (make first nearest match illegal) - vector masks(2); - for(int mi = 0; mi < 2; mi++ ) - { - masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1)); - for( int di = 0; di < queryDescCount/2; di++ ) - masks[mi].col(di*countFactor).setTo(Scalar::all(0)); - } - - dmatcher->radiusMatch( query, matches, radius, masks ); - - int curRes = CvTS::OK; - if( (int)matches.size() != queryDescCount ) - { - ts->printf(CvTS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n"); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - } - - int badCount = 0; - int shift = dmatcher->isMaskSupported() ? 1 : 0; - int needMatchCount = dmatcher->isMaskSupported() ? n-1 : n; - for( size_t i = 0; i < matches.size(); i++ ) - { - if( (int)matches[i].size() != needMatchCount ) - badCount++; - else - { - int localBadCount = 0; - for( int k = 0; k < needMatchCount; k++ ) - { - DMatch match = matches[i][k]; - { - if( i < queryDescCount/2 ) - { - if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) || - (match.imgIdx != 0) ) - localBadCount++; - } - else - { - if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) || - (match.imgIdx != 1) ) - localBadCount++; - } - } - } - badCount += localBadCount > 0 ? 1 : 0; - } - } - if( (float)badCount > (float)queryDescCount*badPart ) - { - curRes = CvTS::FAIL_INVALID_OUTPUT; - ts->printf( CvTS::LOG, "%f - too large bad matches part while test radiusMatch() function (2).\n", - (float)badCount/(float)queryDescCount ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - } - } -} - -void CV_DescriptorMatcherTest::run( int ) -{ - Mat query, train; - generateData( query, train ); - - matchTest( query, train ); - - knnMatchTest( query, train ); - - radiusMatchTest( query, train ); -} - -/****************************************************************************************\ -* Tests registrations * -\****************************************************************************************/ - -/* - * Detectors - * "detector-fast, detector-gftt, detector-harris, detector-mser, detector-sift, detector-star, detector-surf, detector-grid-fast, detector-pyramid-fast" - */ -CV_FeatureDetectorTest fastTest( "detector-fast", FeatureDetector::create("FAST") ); -CV_FeatureDetectorTest gfttTest( "detector-gftt", FeatureDetector::create("GFTT") ); -CV_FeatureDetectorTest harrisTest( "detector-harris", FeatureDetector::create("HARRIS") ); -CV_FeatureDetectorTest mserTest( "detector-mser", FeatureDetector::create("MSER") ); -CV_FeatureDetectorTest siftTest( "detector-sift", FeatureDetector::create("SIFT") ); -CV_FeatureDetectorTest starTest( "detector-star", FeatureDetector::create("STAR") ); -CV_FeatureDetectorTest surfTest( "detector-surf", FeatureDetector::create("SURF") ); -CV_FeatureDetectorTest gridFastfTest( "detector-grid-fast", FeatureDetector::create("GridFAST") ); -CV_FeatureDetectorTest pyramidFastTest( "detector-pyramid-fast", FeatureDetector::create("PyramidFAST") ); - -/* - * Descriptors - * "descriptor-sift, descriptor-surf, descriptor-calonder-uchar, descriptor-calonder-float, descriptor-brief, descriptor-opponent-sift, descriptor-opponent-surf" - */ -CV_DescriptorExtractorTest > siftDescriptorTest( "descriptor-sift", 0.03f, - DescriptorExtractor::create("SIFT"), 8.06652f ); -CV_DescriptorExtractorTest > surfDescriptorTest( "descriptor-surf", 0.035f, - DescriptorExtractor::create("SURF"), 0.147372f ); -CV_DescriptorExtractorTest briefDescriptorTest( "descriptor-brief", 1, - DescriptorExtractor::create("BRIEF"), 0.00527548f ); - -CV_DescriptorExtractorTest > oppSiftDescriptorTest( "descriptor-opponent-sift", 0.18f, - DescriptorExtractor::create("OpponentSIFT"), 8.06652f ); -CV_DescriptorExtractorTest > oppurfDescriptorTest( "descriptor-opponent-surf", 0.18f, - DescriptorExtractor::create("OpponentSURF"), 0.147372f ); - -#if CV_SSE2 -CV_CalonderDescriptorExtractorTest > ucharCalonderTest( "descriptor-calonder-uchar", - std::numeric_limits::epsilon() + 1, - 0.0132175f ); -CV_CalonderDescriptorExtractorTest > floatCalonderTest( "descriptor-calonder-float", - std::numeric_limits::epsilon(), - 0.0221308f ); -#endif // CV_SSE2 - -/* - * Matchers - * "descriptor-matcher-brute-force, descriptor-matcher-flann-based" - */ -CV_DescriptorMatcherTest bruteForceMatcherTest( "descriptor-matcher-brute-force", - new BruteForceMatcher >, 0.01f ); -CV_DescriptorMatcherTest flannBasedMatcherTest( "descriptor-matcher-flann-based", - new FlannBasedMatcher, 0.04f ); - diff --git a/tests/cv/src/affine3d_estimator.cpp b/tests/cv/src/affine3d_estimator.cpp deleted file mode 100644 index 2b59951..0000000 --- a/tests/cv/src/affine3d_estimator.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -class CV_Affine3D_EstTest : public CvTest -{ -public: - CV_Affine3D_EstTest(); - ~CV_Affine3D_EstTest(); -protected: - void run(int); - - bool test4Points(); - bool testNPoints(); -}; - -CV_Affine3D_EstTest::CV_Affine3D_EstTest(): CvTest( "algorithm-estimateAffine3D", "cv::estimateAffine3D" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_Affine3D_EstTest::~CV_Affine3D_EstTest() {} - - -float rngIn(float from, float to) { return from + (to-from) * (float)theRNG(); } - - -struct WrapAff -{ - const double *F; - WrapAff(const Mat& aff) : F(aff.ptr()) {} - Point3f operator()(const Point3f& p) - { - return Point3d( p.x * F[0] + p.y * F[1] + p.z * F[2] + F[3], - p.x * F[4] + p.y * F[5] + p.z * F[6] + F[7], - p.x * F[8] + p.y * F[9] + p.z * F[10] + F[11] ); - } -}; - -bool CV_Affine3D_EstTest::test4Points() -{ - Mat aff(3, 4, CV_64F); - cv::randu(aff, Scalar(1), Scalar(3)); - - // setting points that are no in the same line - - Mat fpts(1, 4, CV_32FC3); - Mat tpts(1, 4, CV_32FC3); - - fpts.ptr()[0] = Point3f( rngIn(1,2), rngIn(1,2), rngIn(5, 6) ); - fpts.ptr()[1] = Point3f( rngIn(3,4), rngIn(3,4), rngIn(5, 6) ); - fpts.ptr()[2] = Point3f( rngIn(1,2), rngIn(3,4), rngIn(5, 6) ); - fpts.ptr()[3] = Point3f( rngIn(3,4), rngIn(1,2), rngIn(5, 6) ); - - transform(fpts.ptr(), fpts.ptr() + 4, tpts.ptr(), WrapAff(aff)); - - Mat aff_est; - vector outliers; - estimateAffine3D(fpts, tpts, aff_est, outliers); - - const double thres = 1e-3; - if (norm(aff_est, aff, NORM_INF) > thres) - { - //cout << norm(aff_est, aff, NORM_INF) << endl; - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -struct Noise -{ - float l; - Noise(float level) : l(level) {} - Point3f operator()(const Point3f& p) - { - RNG& rng = theRNG(); - return Point3f( p.x + l * (float)rng, p.y + l * (float)rng, p.z + l * (float)rng); - } -}; - -bool CV_Affine3D_EstTest::testNPoints() -{ - Mat aff(3, 4, CV_64F); - cv::randu(aff, Scalar(-2), Scalar(2)); - - // setting points that are no in the same line - - const int n = 100; - const int m = 3*n/5; - const Point3f shift_outl = Point3f(15, 15, 15); - const float noise_level = 20.f; - - Mat fpts(1, n, CV_32FC3); - Mat tpts(1, n, CV_32FC3); - - randu(fpts, Scalar::all(0), Scalar::all(100)); - transform(fpts.ptr(), fpts.ptr() + n, tpts.ptr(), WrapAff(aff)); - - /* adding noise*/ - transform(tpts.ptr() + m, tpts.ptr() + n, tpts.ptr() + m, bind2nd(plus(), shift_outl)); - transform(tpts.ptr() + m, tpts.ptr() + n, tpts.ptr() + m, Noise(noise_level)); - - Mat aff_est; - vector outl; - int res = estimateAffine3D(fpts, tpts, aff_est, outl); - - if (!res) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - - const double thres = 1e-4; - if (norm(aff_est, aff, NORM_INF) > thres) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - - bool outl_good = count(outl.begin(), outl.end(), 1) == m && - m == accumulate(outl.begin(), outl.begin() + m, 0); - - if (!outl_good) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - - -void CV_Affine3D_EstTest::run( int /* start_from */) -{ - DefaultRngAuto dra; (void)dra; - - if (!test4Points()) - return; - - if (!testNPoints()) - return; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_Affine3D_EstTest CV_Affine3D_Est_test; - diff --git a/tests/cv/src/afilter.cpp b/tests/cv/src/afilter.cpp deleted file mode 100644 index 2ebf961..0000000 --- a/tests/cv/src/afilter.cpp +++ /dev/null @@ -1,2758 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const CvSize filter_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize filter_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; -static const int filter_depths[] = { CV_8U, CV_16U, CV_32F, -1 }; -static const int filter_channels[] = { 1, 3, 4, -1 }; - -class CV_FilterBaseTestImpl : public CvArrTest -{ -public: - CV_FilterBaseTestImpl( const char* test_name, const char* test_funcs, bool _fp_kernel ); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - int read_params( CvFileStorage* fs ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - int write_default_params(CvFileStorage* fs); - CvSize aperture_size; - CvPoint anchor; - int max_aperture_size; - bool fp_kernel; - bool inplace; -}; - - -CV_FilterBaseTestImpl::CV_FilterBaseTestImpl( const char* test_name, const char* test_funcs, bool _fp_kernel ) - : CvArrTest( test_name, test_funcs, "" ), fp_kernel(_fp_kernel) -{ - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - max_aperture_size = 13; - inplace = false; - aperture_size = cvSize(0,0); - anchor = cvPoint(0,0); - element_wise_relative_error = false; - - size_list = filter_sizes; - whole_size_list = filter_whole_sizes; - depth_list = filter_depths; - cn_list = filter_channels; -} - - -int CV_FilterBaseTestImpl::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - max_aperture_size = cvReadInt( find_param( fs, "max_aperture_size" ), max_aperture_size ); - max_aperture_size = cvTsClipInt( max_aperture_size, 1, 100 ); - } - - return code; -} - - -int CV_FilterBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - write_param( fs, "max_aperture_size", max_aperture_size ); - } - - return code; -} - - -void CV_FilterBaseTestImpl::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT ) - { - if( j == 1 ) - { - if( fp_kernel ) - { - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - *low = cvScalarAll(-1); - *high = cvScalarAll(1); - } - else - { - CvRNG* rng = ts->get_rng(); - double val = exp( cvTsRandReal(rng)*10 - 4 ); - *low = cvScalarAll(-val); - *high = cvScalarAll(val); - } - } - else - { - *low = cvScalarAll(0); - *high = cvScalarAll(2); - } - } - else if( CV_MAT_DEPTH(type) == CV_32F ) - { - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); - } - } -} - - -void CV_FilterBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % CV_32F; - int cn = cvTsRandInt(rng) % 3 + 1; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth += depth == CV_8S; - cn += cn == 2; - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0] = CV_MAKETYPE(depth, cn); - - aperture_size.width = cvTsRandInt(rng) % max_aperture_size + 1; - aperture_size.height = cvTsRandInt(rng) % max_aperture_size + 1; - anchor.x = cvTsRandInt(rng) % aperture_size.width; - anchor.y = cvTsRandInt(rng) % aperture_size.height; - - types[INPUT][1] = fp_kernel ? CV_32FC1 : CV_8UC1; - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width += aperture_size.width - 1; - sizes[TEMP][0].height += aperture_size.height - 1; - - inplace = cvTsRandInt(rng) % 2 != 0; -} - - -int CV_FilterBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - if( inplace && CV_ARE_TYPES_EQ(&test_mat[INPUT][0],&test_mat[OUTPUT][0])) - cvTsCopy( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ); - else - inplace = false; - } - return code; -} - - -void CV_FilterBaseTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - - if( !CV_ARE_TYPES_EQ( src, &test_mat[TEMP][0] )) - { - cvTsConvert( src, &test_mat[REF_OUTPUT][0] ); - src = &test_mat[REF_OUTPUT][0]; - } - cvTsPrepareToFilter( src, &test_mat[TEMP][0], - anchor, CV_TS_BORDER_REPLICATE ); -} - - -CV_FilterBaseTestImpl filter_base( "filter", "", false ); - - -class CV_FilterBaseTest : public CV_FilterBaseTestImpl -{ -public: - CV_FilterBaseTest( const char* test_name, const char* test_funcs, bool _fp_kernel ); -}; - - -CV_FilterBaseTest::CV_FilterBaseTest( const char* test_name, const char* test_funcs, bool _fp_kernel ) - : CV_FilterBaseTestImpl( test_name, test_funcs, _fp_kernel ) -{ - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -///////////////////////// - -static const char* morph_param_names[] = { "mask_size", "shape", "size", "channels", "depth", 0 }; -static const int morph_depths[] = { CV_8U, CV_32F, -1 }; -static const int morph_mask_size[] = { 3, 5, 11 }; -static const char* morph_mask_shape[] = { "rect", "ellipse", 0 }; - -class CV_MorphologyBaseTestImpl : public CV_FilterBaseTest -{ -public: - CV_MorphologyBaseTestImpl( const char* test_name, const char* test_funcs ); - -protected: - void prepare_to_validation( int test_case_idx ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - double get_success_error_level( int test_case_idx, int i, int j ); - int write_default_params(CvFileStorage* fs); - int optype, optype_min, optype_max; - int shape; - IplConvKernel* element; -}; - - -CV_MorphologyBaseTestImpl::CV_MorphologyBaseTestImpl( const char* test_name, const char* test_funcs ) - : CV_FilterBaseTest( test_name, test_funcs, false ) -{ - shape = -1; - element = 0; - size_list = filter_sizes; - whole_size_list = filter_whole_sizes; - depth_list = morph_depths; - cn_list = filter_channels; - optype = optype_min = optype_max = -1; - - element = 0; -} - - -int CV_MorphologyBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CV_FilterBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE && strcmp(tested_functions,"") == 0 ) - { - start_write_param( fs ); - write_int_list( fs, "mask_size", morph_mask_size, CV_DIM(morph_mask_size) ); - write_string_list( fs, "shape", morph_mask_shape ); - } - return code; -} - - -void CV_MorphologyBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvTsRandInt(rng) % 4; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - int cn = CV_MAT_CN(types[INPUT][0]); - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0] = CV_MAKETYPE(depth, cn); - shape = cvTsRandInt(rng) % 4; - if( shape >= 3 ) - shape = CV_SHAPE_CUSTOM; - else - sizes[INPUT][1] = cvSize(0,0); - optype = cvTsRandInt(rng) % (optype_max - optype_min + 1) + optype_min; -} - - -void CV_MorphologyBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_FilterBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* shape_str = cvReadString( find_timing_param( "shape" ), "rect" ); - shape = strcmp( shape_str, "rect" ) == 0 ? CV_SHAPE_RECT : CV_SHAPE_ELLIPSE; - aperture_size.width = cvReadInt( find_timing_param( "mask_size" ), 3 ); - aperture_size.height = aperture_size.width; - anchor.x = anchor.y = aperture_size.width / 2; -} - - -void CV_MorphologyBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%dx%d,", aperture_size.width, aperture_size.height ); - ptr += strlen(ptr); - sprintf( ptr, "%s,", shape == CV_SHAPE_RECT ? "rect" : "ellipse" ); - ptr += strlen(ptr); - params_left -= 2; - - CV_FilterBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CV_MorphologyBaseTestImpl::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return CV_MAT_DEPTH(test_mat[INPUT][0].type) < CV_32F || - (optype == CV_MOP_ERODE || optype == CV_MOP_DILATE || - optype == CV_MOP_OPEN || optype == CV_MOP_CLOSE) ? 0 : 1e-5; -} - - -int CV_MorphologyBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CV_FilterBaseTest::prepare_test_case( test_case_idx ); - int* eldata = 0; - - if( code <= 0 ) - return code; - - if( shape == CV_SHAPE_CUSTOM ) - { - eldata = (int*)alloca( aperture_size.width*aperture_size.height*sizeof(eldata[0]) ); - uchar* src = test_mat[INPUT][1].data.ptr; - int srcstep = test_mat[INPUT][1].step; - int i, j, nonzero = 0; - - for( i = 0; i < aperture_size.height; i++ ) - { - for( j = 0; j < aperture_size.width; j++ ) - { - eldata[i*aperture_size.width + j] = src[i*srcstep + j]; - nonzero += src[i*srcstep + j] != 0; - } - } - - if( nonzero == 0 ) - eldata[anchor.y*aperture_size.width + anchor.x] = 1; - } - - cvReleaseStructuringElement( &element ); - element = cvCreateStructuringElementEx( aperture_size.width, aperture_size.height, - anchor.x, anchor.y, shape, eldata ); - return code; -} - - -void CV_MorphologyBaseTestImpl::prepare_to_validation( int test_case_idx ) -{ - CV_FilterBaseTest::prepare_to_validation( test_case_idx ); - CvMat *src = &test_mat[TEMP][0], *dst = &test_mat[REF_OUTPUT][0]; - - if( optype == CV_MOP_ERODE || optype == CV_MOP_DILATE ) - { - cvTsMinMaxFilter( src, dst, element, optype ); - } - else - { - cv::Ptr dst0 = cvCloneMat(dst), src1 = cvCloneMat(src); - if( optype == CV_MOP_OPEN ) - { - cvTsMinMaxFilter( src, dst0, element, CV_MOP_ERODE ); - cvTsPrepareToFilter( dst0, src1, anchor, CV_TS_BORDER_REPLICATE ); - cvTsMinMaxFilter( src1, dst, element, CV_MOP_DILATE ); - } - else if( optype == CV_MOP_CLOSE ) - { - cvTsMinMaxFilter( src, dst0, element, CV_MOP_DILATE ); - cvTsPrepareToFilter( dst0, src1, anchor, CV_TS_BORDER_REPLICATE ); - cvTsMinMaxFilter( src1, dst, element, CV_MOP_ERODE ); - } - else if( optype == CV_MOP_GRADIENT ) - { - cvTsMinMaxFilter( src, dst0, element, CV_MOP_ERODE ); - cvTsMinMaxFilter( src, dst, element, CV_MOP_DILATE ); - cvTsAdd( dst, cvScalarAll(1), dst0, cvScalarAll(-1), cvScalarAll(0), dst, 0 ); - } - else if( optype == CV_MOP_TOPHAT ) - { - cvTsMinMaxFilter( src, dst0, element, CV_MOP_ERODE ); - cvTsPrepareToFilter( dst0, src1, anchor, CV_TS_BORDER_REPLICATE ); - cvTsMinMaxFilter( src1, dst, element, CV_MOP_DILATE ); - cvTsAdd( dst, cvScalarAll(-1), &test_mat[INPUT][0], cvScalarAll(1), cvScalarAll(0), dst, 0 ); - } - else - { - cvTsMinMaxFilter( src, dst0, element, CV_MOP_DILATE ); - cvTsPrepareToFilter( dst0, src1, anchor, CV_TS_BORDER_REPLICATE ); - cvTsMinMaxFilter( src1, dst, element, CV_MOP_ERODE ); - cvTsAdd( dst, cvScalarAll(1), &test_mat[INPUT][0], cvScalarAll(-1), cvScalarAll(0), dst, 0 ); - } - } - - cvReleaseStructuringElement( &element ); -} - - -CV_MorphologyBaseTestImpl morph( "morph", "" ); - - -class CV_MorphologyBaseTest : public CV_MorphologyBaseTestImpl -{ -public: - CV_MorphologyBaseTest( const char* test_name, const char* test_funcs ); -}; - - -CV_MorphologyBaseTest::CV_MorphologyBaseTest( const char* test_name, const char* test_funcs ) - : CV_MorphologyBaseTestImpl( test_name, test_funcs ) -{ - default_timing_param_names = morph_param_names; - depth_list = 0; - size_list = 0; - cn_list = 0; -} - - -/////////////// erode /////////////// - -class CV_ErodeTest : public CV_MorphologyBaseTest -{ -public: - CV_ErodeTest(); -protected: - void run_func(); -}; - - -CV_ErodeTest::CV_ErodeTest() - : CV_MorphologyBaseTest( "morph-erode", "cvErode" ) -{ - optype_min = optype_max = CV_MOP_ERODE; -} - - -void CV_ErodeTest::run_func() -{ - cvErode( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], element, 1 ); -} - -CV_ErodeTest erode_test; - - -/////////////// dilate /////////////// - -class CV_DilateTest : public CV_MorphologyBaseTest -{ -public: - CV_DilateTest(); -protected: - void run_func(); -}; - - -CV_DilateTest::CV_DilateTest() - : CV_MorphologyBaseTest( "morph-dilate", "cvDilate" ) -{ - optype_min = optype_max = CV_MOP_DILATE; -} - - -void CV_DilateTest::run_func() -{ - cvDilate( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], element, 1 ); -} - -CV_DilateTest dilate_test; - -/////////////// morphEx /////////////// - -class CV_MorphExTest : public CV_MorphologyBaseTest -{ -public: - CV_MorphExTest(); -protected: - void run_func(); -}; - - -CV_MorphExTest::CV_MorphExTest() - : CV_MorphologyBaseTest( "morph-ex", "cvMorphologyEx" ) -{ - optype_min = CV_MOP_ERODE; - optype_max = CV_MOP_BLACKHAT; -} - - -void CV_MorphExTest::run_func() -{ - cvMorphologyEx( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], 0, element, optype, 1 ); -} - -CV_MorphExTest morphex_test; - -/////////////// generic filter /////////////// - -static const char* filter_generic_param_names[] = { "mask_size", "size", "channels", "depth", 0 }; - -class CV_FilterTest : public CV_FilterBaseTest -{ -public: - CV_FilterTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int write_default_params(CvFileStorage* fs); -}; - - -CV_FilterTest::CV_FilterTest() - : CV_FilterBaseTest( "filter-generic", "cvFilter2D", true ) -{ - default_timing_param_names = filter_generic_param_names; -} - - -int CV_FilterTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_FilterBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "mask_size", morph_mask_size, CV_DIM(morph_mask_size) ); - } - return code; -} - - -void CV_FilterTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng)%3; - int cn = CV_MAT_CN(types[INPUT][0]); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : CV_32F; - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0] = CV_MAKETYPE(depth, cn); -} - - -void CV_FilterTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_FilterBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - aperture_size.width = cvReadInt( find_timing_param( "mask_size" ), 3 ); - aperture_size.height = aperture_size.width; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; -} - - -void CV_FilterTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%dx%d,", aperture_size.width, aperture_size.height ); - ptr += strlen(ptr); - params_left--; - - CV_FilterBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CV_FilterTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 2 : depth <= CV_32S ? 32 : - depth == CV_32F ? 1e-4 : 1e-10; -} - - -void CV_FilterTest::run_func() -{ - cvFilter2D( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], &test_mat[INPUT][1], anchor ); -} - - -void CV_FilterTest::prepare_to_validation( int test_case_idx ) -{ - CV_FilterBaseTest::prepare_to_validation( test_case_idx ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], &test_mat[INPUT][1], anchor ); -} - -CV_FilterTest filter; - - -//////////////////////// - -static const int laplace_aperture[] = { 3, 5, 7 }; -static const int sobel_aperture[] = { -1, 3, 5, 7 }; -static const char* laplace_param_names[] = { "aperture", "size", "depth", 0 }; -static const char* sobel_param_names[] = { "deriv_type", "aperture", "size", "depth", 0 }; -static const char* sobel_deriv_type[] = { "dx", "dy", "d2x", "d2y", "dxdy", 0 }; - -class CV_DerivBaseTest : public CV_FilterBaseTest -{ -public: - CV_DerivBaseTest( const char* test_name, const char* test_funcs ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - int _aperture_size; -}; - - -CV_DerivBaseTest::CV_DerivBaseTest( const char* test_name, const char* test_funcs ) - : CV_FilterBaseTest( test_name, test_funcs, true ) -{ - max_aperture_size = 7; - depth_list = morph_depths; - cn_list = 0; -} - - -void CV_DerivBaseTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvTsRandInt(rng) % 2; - depth = depth == 0 ? CV_8U : CV_32F; - types[INPUT][0] = CV_MAKETYPE(depth,1); - types[TEMP][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth==CV_8U?CV_16S:CV_32F,1); - _aperture_size = (cvTsRandInt(rng)%5)*2 - 1; - sizes[INPUT][1] = aperture_size = cvSize(_aperture_size, _aperture_size); -} - - -double CV_DerivBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 2 : 5e-4; -} - - -void CV_DerivBaseTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_FilterBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - _aperture_size = cvReadInt( find_timing_param( "aperture" ), 3 ); - aperture_size.width = aperture_size.height = _aperture_size < 0 ? 3 : _aperture_size; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; - types[OUTPUT][0] = types[INPUT][0] == CV_8UC1 ? CV_16SC1 : types[INPUT][0]; -} - - -/////////////// sobel /////////////// - -class CV_SobelTest : public CV_DerivBaseTest -{ -public: - CV_SobelTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int dx, dy, origin; - IplImage img; - void* src; -}; - - -CV_SobelTest::CV_SobelTest() : CV_DerivBaseTest( "filter-sobel", "cvSobel" ) -{ - src = 0; - default_timing_param_names = sobel_param_names; -} - - -int CV_SobelTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_DerivBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "aperture", sobel_aperture, CV_DIM(sobel_aperture) ); - write_string_list( fs, "deriv_type", sobel_deriv_type ); - } - return code; -} - - -void CV_SobelTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_DerivBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int max_d = _aperture_size > 0 ? 2 : 1; - origin = cvTsRandInt(rng) % 2; - dx = cvTsRandInt(rng) % (max_d + 1); - dy = cvTsRandInt(rng) % (max_d + 1 - dx); - if( dx == 0 && dy == 0 ) - dx = 1; - if( cvTsRandInt(rng) % 2 ) - { - int t; - CV_SWAP( dx, dy, t ); - } - - if( _aperture_size < 0 ) - aperture_size = cvSize(3, 3); - else if( _aperture_size == 1 ) - { - if( dx == 0 ) - aperture_size = cvSize(1, 3); - else if( dy == 0 ) - aperture_size = cvSize(3, 1); - else - { - _aperture_size = 3; - aperture_size = cvSize(3, 3); - } - } - else - aperture_size = cvSize(_aperture_size, _aperture_size); - - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; - anchor.x = aperture_size.width / 2; - anchor.y = aperture_size.height / 2; -} - - -void CV_SobelTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_DerivBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - //_aperture_size = cvReadInt( find_timing_param( "mask_size" ), 3 ); - const char* mask_type = cvReadString( find_timing_param( "deriv_type" ), "dx" ); - if( strcmp( mask_type, "dx" ) == 0 ) - dx = 1, dy = 0; - else if( strcmp( mask_type, "dy" ) == 0 ) - dx = 0, dy = 1; - else if( strcmp( mask_type, "d2x" ) == 0 ) - dx = 2, dy = 0; - else if( strcmp( mask_type, "d2y" ) == 0 ) - dx = 0, dy = 2; - else - dx = 1, dy = 1; - origin = 0; - - aperture_size.width = aperture_size.height = _aperture_size < 0 ? 3 : _aperture_size; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; - types[OUTPUT][0] = types[INPUT][0] == CV_8UC1 ? CV_16SC1 : types[INPUT][0]; -} - - -int CV_SobelTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_DerivBaseTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - if( _aperture_size < 0 && ((dx != 1 || dy != 0) && (dx != 0 || dy != 1)) ) - return 0; - - if( origin ) - { - src = inplace ? &test_mat[OUTPUT][0] : &test_mat[INPUT][0]; - cvGetImage( src, &img ); - img.origin = origin; - src = &img; - } - else - src = inplace ? test_array[OUTPUT][0] : test_array[INPUT][0]; - } - return code; -} - - -void CV_SobelTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - const char* mask_type = cvReadString( find_timing_param( "deriv_type" ), "dx" ); - sprintf( ptr, "%dx%d,%s_%s,", aperture_size.width, aperture_size.height, - _aperture_size > 0 ? "Sobel" : "Scharr", mask_type ); - ptr += strlen(ptr); - params_left -= 2; - - CV_DerivBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_SobelTest::run_func() -{ - cvSobel( src, test_array[OUTPUT][0], dx, dy, _aperture_size ); -} - - -static void cvTsCalcSobelKernel1D( int order, int _aperture_size, int size, int* kernel ) -{ - int i, j, oldval, newval; - - if( _aperture_size < 0 ) - { - static const int scharr[] = { 3, 10, 3, -1, 0, 1 }; - assert( size == 3 ); - memcpy( kernel, scharr + order*3, 3*sizeof(scharr[0])); - return; - } - - memset( kernel + 1, 0, size * sizeof(kernel[0])); - kernel[0] = 1; - - for( i = 0; i < size - order - 1; i++ ) - { - oldval = kernel[0]; - for( j = 1; j <= size; j++ ) - { - newval = kernel[j] + kernel[j-1]; - kernel[j-1] = oldval; - oldval = newval; - } - } - - for( i = 0; i < order; i++ ) - { - oldval = -kernel[0]; - for( j = 1; j <= size; j++ ) - { - newval = kernel[j-1] - kernel[j]; - kernel[j-1] = oldval; - oldval = newval; - } - } -} - - -void cvTsCalcSobelKernel2D( int dx, int dy, int _aperture_size, int origin, CvMat* kernel ) -{ - int i, j; - int* kx = (int*)alloca( (kernel->cols+1)*sizeof(kx[0]) ); - int* ky = (int*)alloca( (kernel->rows+1)*sizeof(ky[0]) ); - - assert( CV_MAT_TYPE(kernel->type) == CV_32F ); - - cvTsCalcSobelKernel1D( dx, _aperture_size, kernel->cols, kx ); - cvTsCalcSobelKernel1D( dy, _aperture_size, kernel->rows, ky ); - - for( i = 0; i < kernel->rows; i++ ) - { - float* kdata = (float*)(kernel->data.ptr + i*kernel->step); - float ay = (float)ky[i]*(origin && (dy & 1) ? -1 : 1); - for( j = 0; j < kernel->cols; j++ ) - { - kdata[j] = kx[j]*ay; - } - } -} - - -void CV_SobelTest::prepare_to_validation( int test_case_idx ) -{ - CV_DerivBaseTest::prepare_to_validation( test_case_idx ); - cvTsCalcSobelKernel2D( dx, dy, _aperture_size, origin, &test_mat[INPUT][1] ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], &test_mat[INPUT][1], anchor ); -} - -CV_SobelTest sobel_test; - - -/////////////// laplace /////////////// - -class CV_LaplaceTest : public CV_DerivBaseTest -{ -public: - CV_LaplaceTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_LaplaceTest::CV_LaplaceTest() : CV_DerivBaseTest( "filter-laplace", "cvLaplace" ) -{ - default_timing_param_names = laplace_param_names; -} - - -int CV_LaplaceTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_DerivBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "aperture", laplace_aperture, CV_DIM(laplace_aperture) ); - } - return code; -} - - -void CV_LaplaceTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CV_DerivBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - if( _aperture_size <= 1 ) - { - if( _aperture_size < 0 ) - _aperture_size = 1; - aperture_size = cvSize(3, 3); - } - else - aperture_size = cvSize(_aperture_size, _aperture_size); - - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; - anchor.x = aperture_size.width / 2; - anchor.y = aperture_size.height / 2; -} - - -void CV_LaplaceTest::run_func() -{ - cvLaplace( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], _aperture_size ); -} - - -static void cvTsCalcLaplaceKernel2D( int _aperture_size, CvMat* kernel ) -{ - int i, j; - int* kx = (int*)alloca( (kernel->cols+1)*sizeof(kx[0]) ); - int* ky = (int*)alloca( (kernel->rows+1)*sizeof(ky[0]) ); - - cvTsCalcSobelKernel1D( 2, _aperture_size, kernel->cols, kx ); - if( _aperture_size > 1 ) - cvTsCalcSobelKernel1D( 0, _aperture_size, kernel->rows, ky ); - else - ky[0] = ky[2] = 0, ky[1] = 1; - - for( i = 0; i < kernel->rows; i++ ) - { - float* kdata = (float*)(kernel->data.ptr + i*kernel->step); - for( j = 0; j < kernel->cols; j++ ) - { - kdata[j] = (float)(kx[j]*ky[i] + kx[i]*ky[j]); - } - } -} - - -int CV_LaplaceTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_DerivBaseTest::prepare_test_case( test_case_idx ); - return _aperture_size < 0 ? 0 : code; -} - - -void CV_LaplaceTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%dx%d,", aperture_size.width, aperture_size.height ); - ptr += strlen(ptr); - params_left--; - - CV_DerivBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_LaplaceTest::prepare_to_validation( int test_case_idx ) -{ - CV_DerivBaseTest::prepare_to_validation( test_case_idx ); - cvTsCalcLaplaceKernel2D( _aperture_size, &test_mat[INPUT][1] ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], &test_mat[INPUT][1], anchor ); -} - - -CV_LaplaceTest laplace_test; - - -//////////////////////////////////////////////////////////// - -static const char* smooth_param_names[] = { "mask_size", "size", "channels", "depth", 0 }; -static const int smooth_depths[] = { CV_8U, CV_32F, -1 }; - -class CV_SmoothBaseTest : public CV_FilterBaseTest -{ -public: - CV_SmoothBaseTest( const char* test_name, const char* test_funcs ); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - const char* smooth_type; -}; - - -CV_SmoothBaseTest::CV_SmoothBaseTest( const char* test_name, const char* test_funcs ) - : CV_FilterBaseTest( test_name, test_funcs, true ) -{ - default_timing_param_names = smooth_param_names; - depth_list = smooth_depths; - smooth_type = ""; -} - - -int CV_SmoothBaseTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_FilterBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "mask_size", morph_mask_size, CV_DIM(morph_mask_size) ); - } - return code; -} - -void CV_SmoothBaseTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvTsRandInt(rng) % 2; - int cn = CV_MAT_CN(types[INPUT][0]); - depth = depth == 0 ? CV_8U : CV_32F; - types[INPUT][0] = types[TEMP][0] = - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - anchor.x = cvTsRandInt(rng)%(max_aperture_size/2+1); - anchor.y = cvTsRandInt(rng)%(max_aperture_size/2+1); - aperture_size.width = anchor.x*2 + 1; - aperture_size.height = anchor.y*2 + 1; - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; -} - - -double CV_SmoothBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 1 : 1e-5; -} - - -void CV_SmoothBaseTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_FilterBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - - aperture_size.width = aperture_size.height = cvReadInt( find_timing_param( "mask_size" ), 3 ); - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; -} - - -void CV_SmoothBaseTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%dx%d,%s,", aperture_size.width, aperture_size.height, smooth_type ); - ptr += strlen(ptr); - params_left -= 2; - - CV_FilterBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -/////////////// blur /////////////// - -static const char* blur_param_names[] = { "normalize", "mask_size", "size", "channels", "depth", 0 }; -static const int blur_normalize[] = { 0, 1 }; - -class CV_BlurTest : public CV_SmoothBaseTest -{ -public: - CV_BlurTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - int write_default_params( CvFileStorage* fs ); - bool normalize; -}; - - -CV_BlurTest::CV_BlurTest() : CV_SmoothBaseTest( "filter-blur", "cvSmooth" ) -{ - default_timing_param_names = blur_param_names; -} - - -void CV_BlurTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - normalize = cvTsRandInt(rng) % 2 != 0; - if( !normalize ) - { - int depth = CV_MAT_DEPTH(types[INPUT][0]); - types[INPUT][0] = CV_MAKETYPE(depth, 1); - types[TEMP][0] = types[OUTPUT][0] = - types[REF_OUTPUT][0] = CV_MAKETYPE(depth==CV_8U?CV_16S:CV_32F,1); - } -} - - -int CV_BlurTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_SmoothBaseTest::write_default_params( fs ); - if( code >= 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - write_int_list( fs, "normalize", blur_normalize, CV_DIM(blur_normalize) ); - } - return code; -} - - -void CV_BlurTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_SmoothBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - normalize = cvReadInt( find_timing_param( "normalize" ), 1 ) != 0; - smooth_type = normalize ? "Blur" : "Blur_NoScale"; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; - if( !normalize && types[INPUT][0] == CV_8UC1 ) - types[OUTPUT][0] = CV_16SC1; -} - - -void CV_BlurTest::run_func() -{ - cvSmooth( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], normalize ? CV_BLUR : CV_BLUR_NO_SCALE, - aperture_size.width, aperture_size.height ); -} - - -int CV_BlurTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_SmoothBaseTest::prepare_test_case( test_case_idx ); - return code > 0 && !normalize && CV_MAT_CN(test_mat[INPUT][0].type) > 1 ? 0 : code; -} - - -void CV_BlurTest::prepare_to_validation( int test_case_idx ) -{ - CvMat* kernel = &test_mat[INPUT][1]; - CV_SmoothBaseTest::prepare_to_validation( test_case_idx ); - cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), - cvScalarAll(normalize ? 1./(kernel->rows*kernel->cols) : 1.), kernel, 0 ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], kernel, anchor ); -} - - -CV_BlurTest blur_test; - - -/////////////// gaussian /////////////// - -class CV_GaussianBlurTest : public CV_SmoothBaseTest -{ -public: - CV_GaussianBlurTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - double sigma; - int param1, param2; -}; - - -CV_GaussianBlurTest::CV_GaussianBlurTest() : CV_SmoothBaseTest( "filter-gaussian", "cvSmooth" ) -{ - sigma = 0.; - smooth_type = "Gaussian"; -} - - -double CV_GaussianBlurTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 8 : 1e-5; -} - - -void CV_GaussianBlurTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int kernel_case = cvTsRandInt(rng) % 2; - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - anchor = cvPoint(aperture_size.width/2,aperture_size.height/2); - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; - - sigma = exp(cvTsRandReal(rng)*5-2); - param1 = aperture_size.width; - param2 = aperture_size.height; - - if( kernel_case == 0 ) - sigma = 0.; - /*else if( kernel_case == 2 ) - { - int depth = CV_MAT_DEPTH(types[INPUT][0]); - // !!! Copied from cvSmooth, if this formula is changed in cvSmooth, - // make sure to update this one too. - aperture_size.width = cvRound(sigma*(depth == CV_8U ? 3 : 4)*2 + 1)|1; - aperture_size.width = MIN( aperture_size.width, 31 ); - aperture_size.height = aperture_size.width; - anchor.x = aperture_size.width / 2; - anchor.y = aperture_size.height / 2; - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; - param1 = aperture_size.width; param2 = aperture_size.height; - }*/ -} - - -void CV_GaussianBlurTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_SmoothBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - param1 = aperture_size.width; - param2 = aperture_size.height; - sigma = sqrt(2.); -} - -void CV_GaussianBlurTest::run_func() -{ - cvSmooth( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], CV_GAUSSIAN, param1, param2, sigma ); -} - - -// !!! Copied from cvSmooth, if the code is changed in cvSmooth, -// make sure to update this one too. -#define SMALL_GAUSSIAN_SIZE 7 -static void -icvCalcGaussianKernel( int n, double sigma, float* kernel ) -{ - static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] = - { - {1.f}, - {0.25f, 0.5f, 0.25f}, - {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f}, - {0.03125, 0.109375, 0.21875, 0.28125, 0.21875, 0.109375, 0.03125} - }; - - if( n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ) - { - assert( n%2 == 1 ); - memcpy( kernel, small_gaussian_tab[n>>1], n*sizeof(kernel[0])); - } - else - { - double sigmaX = sigma > 0 ? sigma : (n/2 - 1)*0.3 + 0.8; - double scale2X = -0.5/(sigmaX*sigmaX); - double sum = 1.; - int i; - sum = kernel[n/2] = 1.f; - - for( i = 1; i <= n/2; i++ ) - { - kernel[n/2+i] = kernel[n/2-i] = (float)exp(scale2X*i*i); - sum += kernel[n/2+i]*2; - } - - sum = 1./sum; - for( i = 0; i <= n/2; i++ ) - kernel[n/2+i] = kernel[n/2-i] = (float)(kernel[n/2+i]*sum); - } -} - - -static void cvTsCalcGaussianKernel2D( double sigma, CvMat* kernel ) -{ - int i, j; - float* kx = (float*)alloca( kernel->cols*sizeof(kx[0]) ); - float* ky = (float*)alloca( kernel->rows*sizeof(ky[0]) ); - - icvCalcGaussianKernel( kernel->cols, sigma, kx ); - icvCalcGaussianKernel( kernel->rows, sigma, ky ); - - for( i = 0; i < kernel->rows; i++ ) - { - float* kdata = (float*)(kernel->data.ptr + i*kernel->step); - for( j = 0; j < kernel->cols; j++ ) - kdata[j] = kx[j]*ky[i]; - } -} - - -void CV_GaussianBlurTest::prepare_to_validation( int test_case_idx ) -{ - CvMat* kernel = &test_mat[INPUT][1]; - CV_SmoothBaseTest::prepare_to_validation( test_case_idx ); - cvTsCalcGaussianKernel2D( sigma, &test_mat[INPUT][1] ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], kernel, anchor ); -} - - -CV_GaussianBlurTest gaussianblur_test; - - -/////////////// median /////////////// - -static const int smooth_median_depths[] = { CV_8U, -1 }; - -class CV_MedianBlurTest : public CV_SmoothBaseTest -{ -public: - CV_MedianBlurTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); -}; - - -CV_MedianBlurTest::CV_MedianBlurTest() : CV_SmoothBaseTest( "filter-median", "cvSmooth" ) -{ - test_array[TEMP].push(NULL); - smooth_type = "Median"; - depth_list = smooth_median_depths; -} - - -void CV_MedianBlurTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = CV_8U; - int cn = CV_MAT_CN(types[INPUT][0]); - types[INPUT][0] = types[TEMP][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - types[INPUT][1] = types[TEMP][0] = types[TEMP][1] = CV_MAKETYPE(depth,1); - - aperture_size.height = aperture_size.width; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = cvSize(aperture_size.width,aperture_size.height); - - sizes[OUTPUT][0] = sizes[INPUT][0]; - sizes[REF_OUTPUT][0] = sizes[INPUT][0]; - - sizes[TEMP][0].width = sizes[INPUT][0].width + aperture_size.width - 1; - sizes[TEMP][0].height = sizes[INPUT][0].height + aperture_size.height - 1; - - sizes[TEMP][1] = cn > 1 ? sizes[INPUT][0] : cvSize(0,0); - inplace = false; -} - - -double CV_MedianBlurTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CV_MedianBlurTest::run_func() -{ - cvSmooth( test_array[INPUT][0], test_array[OUTPUT][0], - CV_MEDIAN, aperture_size.width ); -} - - -struct median_pair -{ - int col; - int val; - median_pair() {}; - median_pair( int _col, int _val ) : col(_col), val(_val) {}; -}; - - -static void cvTsMedianFilter( const CvMat* src, CvMat* dst, int m ) -{ - int i, j, k, l, m2 = m*m, n; - int* col_buf = (int*)cvAlloc( (m+1)*sizeof(col_buf[0])); - median_pair* buf0 = (median_pair*)cvAlloc( (m*m+1)*sizeof(buf0[0])); - median_pair* buf1 = (median_pair*)cvAlloc( (m*m+1)*sizeof(buf1[0])); - median_pair* tbuf; - int step = src->step/CV_ELEM_SIZE(src->type); - - assert( src->rows == dst->rows + m - 1 && src->cols == dst->cols + m - 1 && - CV_ARE_TYPES_EQ(src,dst) && CV_MAT_TYPE(src->type) == CV_8UC1 ); - - for( i = 0; i < dst->rows; i++ ) - { - uchar* dst1 = (uchar*)(dst->data.ptr + dst->step*i); - for( k = 0; k < m; k++ ) - { - const uchar* src1 = (const uchar*)(src->data.ptr + (i+k)*src->step); - for( j = 0; j < m-1; j++ ) - *buf0++ = median_pair(j, src1[j]); - } - - n = m2 - m; - buf0 -= n; - for( k = n-1; k > 0; k-- ) - { - int f = 0; - for( j = 0; j < k; j++ ) - { - if( buf0[j].val > buf0[j+1].val ) - { - median_pair t; - CV_SWAP( buf0[j], buf0[j+1], t ); - f = 1; - } - } - if( !f ) - break; - } - - for( j = 0; j < dst->cols; j++ ) - { - int ins_col = j + m - 1; - int del_col = j - 1; - const uchar* src1 = (const uchar*)(src->data.ptr + src->step*i) + ins_col; - for( k = 0; k < m; k++, src1 += step ) - { - col_buf[k] = src1[0]; - for( l = k-1; l >= 0; l-- ) - { - int t; - if( col_buf[l] < col_buf[l+1] ) - break; - CV_SWAP( col_buf[l], col_buf[l+1], t ); - } - } - - col_buf[m] = INT_MAX; - - for( k = 0, l = 0; k < n; ) - { - if( buf0[k].col == del_col ) - k++; - else if( buf0[k].val < col_buf[l] ) - *buf1++ = buf0[k++]; - else - { - assert( col_buf[l] < INT_MAX ); - *buf1++ = median_pair(ins_col,col_buf[l++]); - } - } - - for( ; l < m; l++ ) - *buf1++ = median_pair(ins_col,col_buf[l]); - - if( del_col < 0 ) - n += m; - buf1 -= n; - assert( n == m2 ); - dst1[j] = (uchar)buf1[n/2].val; - CV_SWAP( buf0, buf1, tbuf ); - } - } - - cvFree(&col_buf); - cvFree(&buf0); - cvFree(&buf1); -} - - -void CV_MedianBlurTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - // CV_SmoothBaseTest::prepare_to_validation( test_case_idx ); - CvMat* src0 = &test_mat[INPUT][0]; - CvMat* dst0 = &test_mat[REF_OUTPUT][0]; - int i, cn = CV_MAT_CN(src0->type); - CvMat* src = &test_mat[TEMP][0], *dst = dst0; - if( cn > 1 ) - dst = &test_mat[TEMP][1]; - - for( i = 0; i < cn; i++ ) - { - CvMat* ptr = src0; - if( cn > 1 ) - { - cvTsExtract( src0, dst, i ); - ptr = dst; - } - cvTsPrepareToFilter( ptr, src, anchor, CV_TS_BORDER_REPLICATE ); - cvTsMedianFilter( src, dst, aperture_size.width ); - if( cn > 1 ) - cvTsInsert( dst, dst0, i ); - } -} - - -CV_MedianBlurTest medianblur_test; - - -/////////////// pyramid tests /////////////// - -static const char* pyramid_param_names[] = { "size", "channels", "depth", 0 }; -static int pyramid_channels[] = { 1, 3, -1 }; - -class CV_PyramidBaseTest : public CV_FilterBaseTest -{ -public: - CV_PyramidBaseTest( const char* test_name, const char* test_funcs, bool downsample ); - -protected: - int prepare_test_case( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - bool downsample; -}; - - -CV_PyramidBaseTest::CV_PyramidBaseTest( const char* test_name, const char* test_funcs, bool _downsample ) - : CV_FilterBaseTest( test_name, test_funcs, true ), downsample(_downsample) -{ - test_array[TEMP].push(NULL); - size_list = filter_sizes; - depth_list = smooth_depths; - cn_list = pyramid_channels; - default_timing_param_names = 0; - if( strcmp( test_funcs, "" ) != 0 ) - { - default_timing_param_names = pyramid_param_names; - size_list = 0; - cn_list = 0; - depth_list = 0; - } -} - - -double CV_PyramidBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 1 : 1e-5; -} - - -void CV_PyramidBaseTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvSize sz; - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - int depth = cvTsRandInt(rng) % 2 ? CV_32F : CV_8U; - int cn = cvTsRandInt(rng) & 1 ? 3 : 1; - - aperture_size = cvSize(5,5); - anchor = cvPoint(aperture_size.width/2, aperture_size.height/2); - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = - types[TEMP][0] = types[TEMP][1] = CV_MAKETYPE(depth, cn); - - sz.width = MAX( sizes[INPUT][0].width/2, 1 ); - sz.height = MAX( sizes[INPUT][0].height/2, 1 ); - - if( downsample ) - { - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sz; - sz.width *= 2; - sz.height *= 2; - sizes[INPUT][0] = sizes[TEMP][1] = sz; - } - else - { - sizes[INPUT][0] = sz; - sz.width *= 2; - sz.height *= 2; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sz; - sizes[TEMP][1] = cvSize(0,0); - } - - sizes[INPUT][1] = aperture_size; - sizes[TEMP][0].width = sz.width + aperture_size.width - 1; - sizes[TEMP][0].height = sz.height + aperture_size.height - 1; - inplace = false; -} - - -void CV_PyramidBaseTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_FilterBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - CvSize sz = sizes[INPUT][0]; - sz.width /= 2; - sz.height /= 2; - if( downsample ) - sizes[OUTPUT][0] = sz; - else - sizes[INPUT][0] = sz; - aperture_size.width = aperture_size.height = 5; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = aperture_size; - types[INPUT][1] = CV_32FC1; -} - - -int CV_PyramidBaseTest::prepare_test_case( int test_case_idx ) -{ - static const float kdata[] = { 1.f, 4.f, 6.f, 4.f, 1.f }; - int i, j; - double scale = 1./256; - CvMat* kernel; - int code = CV_FilterBaseTest::prepare_test_case( test_case_idx ); - - if( code <= 0 ) - return code; - - if( !downsample ) - scale *= 4; - - kernel = &test_mat[INPUT][1]; - - for( i = 0; i < aperture_size.height; i++ ) - { - float* krow = (float*)(kernel->data.ptr + i*kernel->step); - for( j = 0; j < aperture_size.width; j++ ) - krow[j] = (float)(scale*kdata[i]*kdata[j]); - } - return code; -} - - -CV_PyramidBaseTest pyr_base( "pyramid", "", false ); - - -/////// pyrdown //////// - -static void cvTsDownsample( const CvMat* src, CvMat* dst ) -{ - int i, j, k; - int elem_size = CV_ELEM_SIZE(src->type); - int ncols = dst->cols*elem_size; - int is_dword = elem_size % sizeof(int) == 0; - - if( is_dword ) - { - elem_size /= sizeof(int); - ncols /= sizeof(int); - } - - for( i = 0; i < dst->rows; i++ ) - { - const uchar* src_row = src->data.ptr + i*2*src->step; - uchar* dst_row = dst->data.ptr + i*dst->step; - - if( !is_dword ) - { - for( j = 0; j < ncols; j += elem_size ) - { - for( k = 0; k < elem_size; k++ ) - dst_row[j+k] = src_row[j*2+k]; - } - } - else - { - for( j = 0; j < ncols; j += elem_size ) - { - for( k = 0; k < elem_size; k++ ) - ((int*)dst_row)[j+k] = ((const int*)src_row)[j*2+k]; - } - } - } -} - - -class CV_PyramidDownTest : public CV_PyramidBaseTest -{ -public: - CV_PyramidDownTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_PyramidDownTest::CV_PyramidDownTest() - : CV_PyramidBaseTest( "pyramid-down", "cvPyrDown", true ) -{ -} - - -void CV_PyramidDownTest::run_func() -{ - cvPyrDown( test_array[INPUT][0], test_array[OUTPUT][0], CV_GAUSSIAN_5x5 ); -} - - -void CV_PyramidDownTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsPrepareToFilter( &test_mat[INPUT][0], &test_mat[TEMP][0], - anchor, CV_TS_BORDER_REFLECT ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[TEMP][1], - &test_mat[INPUT][1], anchor ); - cvTsDownsample( &test_mat[TEMP][1], &test_mat[REF_OUTPUT][0] ); -} - - -CV_PyramidDownTest pyrdown; - - -/////// pyrup //////// - -static void cvTsUpsample( const CvMat* src, CvMat* dst ) -{ - int i, j, k; - int elem_size = CV_ELEM_SIZE(src->type); - int ncols = src->cols*elem_size; - int is_dword = elem_size % sizeof(int) == 0; - - if( is_dword ) - { - elem_size /= sizeof(int); - ncols /= sizeof(int); - } - - for( i = 0; i < src->rows; i++ ) - { - const uchar* src_row = src->data.ptr + i*src->step; - uchar* dst_row = dst->data.ptr + i*2*dst->step; - - if( !is_dword ) - { - memset( dst_row + dst->step, 0, dst->cols*elem_size ); - for( j = 0; j < ncols; j += elem_size ) - { - for( k = 0; k < elem_size; k++ ) - { - dst_row[j*2+k] = src_row[j+k]; - dst_row[j*2+k+elem_size] = 0; - } - } - } - else - { - memset( dst_row + dst->step, 0, dst->cols*elem_size*sizeof(int) ); - for( j = 0; j < ncols; j += elem_size ) - { - for( k = 0; k < elem_size; k++ ) - { - ((int*)dst_row)[j*2+k] = ((const int*)src_row)[j+k]; - ((int*)dst_row)[j*2+k+elem_size] = 0; - } - } - } - } -} - - -class CV_PyramidUpTest : public CV_PyramidBaseTest -{ -public: - CV_PyramidUpTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_PyramidUpTest::CV_PyramidUpTest() - : CV_PyramidBaseTest( "pyramid-up", "cvPyrUp", false ) -{ -} - - -void CV_PyramidUpTest::run_func() -{ - cvPyrUp( test_array[INPUT][0], test_array[OUTPUT][0], CV_GAUSSIAN_5x5 ); -} - - -void CV_PyramidUpTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat src2, dst2; - CvSize sz; - cvTsUpsample( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0] ); - cvTsPrepareToFilter( &test_mat[REF_OUTPUT][0], &test_mat[TEMP][0], - anchor, CV_TS_BORDER_REFLECT ); - cvTsConvolve2D( &test_mat[TEMP][0], &test_mat[REF_OUTPUT][0], - &test_mat[INPUT][1], anchor ); - // currently IPP and OpenCV process right/bottom part of the image differently, so - // we just patch the last two rows/columns to have consistent test results. - sz = cvGetMatSize( &test_mat[REF_OUTPUT][0]); - cvTsSelect( &test_mat[REF_OUTPUT][0], &src2, cvRect(sz.width-2,0,2,sz.height) ); - cvTsSelect( &test_mat[OUTPUT][0], &dst2, cvRect(sz.width-2,0,2,sz.height) ); - cvTsCopy( &src2, &dst2, 0 ); - cvTsSelect( &test_mat[REF_OUTPUT][0], &src2, cvRect(0,sz.height-2,sz.width,2) ); - cvTsSelect( &test_mat[OUTPUT][0], &dst2, cvRect(0,sz.height-2,sz.width,2) ); - cvTsCopy( &src2, &dst2, 0 ); -} - - -CV_PyramidUpTest pyrup; - - - -//////////////////////// feature selection ////////////////////////// - -static const char* featuresel_param_names[] = { "block_size", "aperture", "size", "depth", 0 }; -static const int featuresel_block_size[] = { 3, 5, 11 }; - -class CV_FeatureSelBaseTestImpl : public CvArrTest -{ -public: - CV_FeatureSelBaseTestImpl( const char* test_name, const char* test_funcs, int width_factor ); - -protected: - int read_params( CvFileStorage* fs ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int aperture_size, block_size; - int max_aperture_size; - int max_block_size; - int width_factor; -}; - - -CV_FeatureSelBaseTestImpl::CV_FeatureSelBaseTestImpl( const char* test_name, const char* test_funcs, int _width_factor ) - : CvArrTest( test_name, test_funcs, "" ) -{ - max_aperture_size = 7; - max_block_size = 21; - // 1 input, 1 output, temp arrays are allocated in the reference functions - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - element_wise_relative_error = false; - width_factor = _width_factor; - - size_list = filter_sizes; - whole_size_list = filter_whole_sizes; - depth_list = morph_depths; - cn_list = 0; -} - - -int CV_FeatureSelBaseTestImpl::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - max_aperture_size = cvReadInt( find_param( fs, "max_aperture_size" ), max_aperture_size ); - max_aperture_size = cvTsClipInt( max_aperture_size, 1, 9 ); - max_block_size = cvReadInt( find_param( fs, "max_block_size" ), max_block_size ); - max_block_size = cvTsClipInt( max_aperture_size, 1, 100 ); - } - - return code; -} - - -int CV_FeatureSelBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - write_param( fs, "max_aperture_size", max_aperture_size ); - write_param( fs, "max_block_size", max_block_size ); - } - else if( ts->get_testing_mode() == CvTS::TIMING_MODE && strcmp( tested_functions, "" ) == 0 ) - { - start_write_param( fs ); - write_int_list( fs, "aperture", sobel_aperture, CV_DIM(sobel_aperture) ); - write_int_list( fs, "block_size", featuresel_block_size, CV_DIM(featuresel_block_size) ); - } - - return code; -} - - -double CV_FeatureSelBaseTestImpl::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 3e-2 : depth == CV_32F ? 1e-3 : 1e-10; -} - - -void CV_FeatureSelBaseTestImpl::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT && CV_MAT_DEPTH(type) == CV_32F ) - { - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); - } -} - - -void CV_FeatureSelBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvTsRandInt(rng) % 2, asz; - - depth = depth == 0 ? CV_8U : CV_32F; - types[INPUT][0] = depth; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_32FC1; - - aperture_size = (cvTsRandInt(rng) % (max_aperture_size+2) - 1) | 1; - if( aperture_size == 1 ) - aperture_size = 3; - if( depth == CV_8U ) - aperture_size = MIN( aperture_size, 5 ); - block_size = (cvTsRandInt(rng) % max_block_size + 1) | 1; - if( block_size <= 3 ) - block_size = 3; - asz = aperture_size > 0 ? aperture_size : 3; - - sizes[INPUT][0].width = MAX( sizes[INPUT][0].width, asz + block_size ); - sizes[INPUT][0].height = MAX( sizes[INPUT][0].height, asz + block_size ); - sizes[OUTPUT][0].height = sizes[REF_OUTPUT][0].height = sizes[INPUT][0].height; - sizes[OUTPUT][0].width = sizes[REF_OUTPUT][0].width = sizes[INPUT][0].width*width_factor; -} - - -void CV_FeatureSelBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - aperture_size = cvReadInt( find_timing_param( "aperture" ), 3 ); - block_size = cvReadInt( find_timing_param( "block_size" ), 0 ); - int asz = aperture_size < 0 ? 3 : aperture_size; - - sizes[INPUT][0].width = MAX( sizes[INPUT][0].width, asz + block_size ); - sizes[INPUT][0].height = MAX( sizes[INPUT][0].height, asz + block_size ); - whole_sizes[INPUT][0].width = MAX( whole_sizes[INPUT][0].width, asz + block_size ); - whole_sizes[INPUT][0].height = MAX( whole_sizes[INPUT][0].height, asz + block_size ); - sizes[OUTPUT][0].height = sizes[INPUT][0].height; - sizes[OUTPUT][0].width = sizes[INPUT][0].width*width_factor; - whole_sizes[OUTPUT][0].height = whole_sizes[INPUT][0].height; - whole_sizes[OUTPUT][0].width = MAX(whole_sizes[OUTPUT][0].width,sizes[OUTPUT][0].width); - types[OUTPUT][0] = CV_32FC1; -} - - -void CV_FeatureSelBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - int asz = aperture_size < 0 ? 3 : aperture_size; - sprintf( ptr, "%s(%dx%d),", aperture_size < 0 ? "Scharr" : "Sobel", asz, asz ); - ptr += strlen(ptr); - params_left--; - if( block_size > 0 ) - { - sprintf( ptr, "block_size=%dx%d,", block_size, block_size ); - ptr += strlen(ptr); - params_left--; - } - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -CV_FeatureSelBaseTestImpl featuresel_base( "features", "", 0 ); - - - -class CV_FeatureSelBaseTest : public CV_FeatureSelBaseTestImpl -{ -public: - CV_FeatureSelBaseTest( const char* test_name, const char* test_funcs, int width_factor ); -}; - - -CV_FeatureSelBaseTest::CV_FeatureSelBaseTest( const char* test_name, const char* test_funcs, int _width_factor ) - : CV_FeatureSelBaseTestImpl( test_name, test_funcs, _width_factor ) -{ - depth_list = 0; - size_list = whole_size_list = 0; - default_timing_param_names = featuresel_param_names; -} - - -static void -cvTsCornerEigenValsVecs( const CvMat* _src, CvMat* eigenv, CvMat* ocv_eigenv, - int block_size, int _aperture_size, int mode ) -{ - CvMat *dx2 = 0, *dxdy = 0, *dy2 = 0; - CvMat* kernel = 0, *src2 = 0; - const CvMat* src = _src; - - int type, ftype; - double denom; - - CV_FUNCNAME( "cvTsCornerEigenValsVecs" ); - - __BEGIN__; - - int i, j; - int aperture_size = _aperture_size < 0 ? 3 : _aperture_size; - CvPoint anchor = { aperture_size/2, aperture_size/2 }; - - assert( (CV_MAT_TYPE(src->type) == CV_8UC1 || - CV_MAT_TYPE(src->type) == CV_32FC1) && - CV_MAT_TYPE(eigenv->type) == CV_32FC1 ); - - assert( src->rows == eigenv->rows && - ((mode > 0 && src->cols == eigenv->cols) || - (mode == 0 && src->cols*6 == eigenv->cols)) ); - - type = CV_MAT_TYPE(src->type); - ftype = CV_32FC1; - - CV_CALL( dx2 = cvCreateMat( src->rows, src->cols, ftype )); - CV_CALL( dy2 = cvCreateMat( src->rows, src->cols, ftype )); - CV_CALL( dxdy = cvCreateMat( src->rows, src->cols, ftype )); - - CV_CALL( kernel = cvCreateMat( aperture_size, aperture_size, CV_32FC1 )); - CV_CALL( src2 = cvCreateMat( src->rows + aperture_size - 1, - src->cols + aperture_size - 1, ftype )); - - if( type != ftype ) - { - cvTsAdd( src, cvScalarAll(1./255), 0, cvScalarAll(0.), cvScalarAll(0.), dx2, 0 ); - src = dx2; - } - - cvTsPrepareToFilter( src, src2, anchor, CV_TS_BORDER_REPLICATE ); - cvTsCalcSobelKernel2D( 1, 0, _aperture_size, 0, kernel ); - cvTsConvolve2D( src2, dx2, kernel, anchor ); - cvTsCalcSobelKernel2D( 0, 1, _aperture_size, 0, kernel ); - cvTsConvolve2D( src2, dy2, kernel, anchor ); - cvReleaseMat( &src2 ); - cvReleaseMat( &kernel ); - - denom = (1 << (aperture_size-1))*block_size; - denom = denom * denom; - if( _aperture_size < 0 ) - denom *= 4; - denom = 1./denom; - - for( i = 0; i < src->rows; i++ ) - { - float* dxdyp = (float*)(dxdy->data.ptr + i*dxdy->step); - float* dx2p = (float*)(dx2->data.ptr + i*dx2->step); - float* dy2p = (float*)(dy2->data.ptr + i*dy2->step); - - for( j = 0; j < src->cols; j++ ) - { - double xval = dx2p[j], yval = dy2p[j]; - dxdyp[j] = (float)(xval*yval*denom); - dx2p[j] = (float)(xval*xval*denom); - dy2p[j] = (float)(yval*yval*denom); - } - } - - CV_CALL( src2 = cvCreateMat( src->rows + block_size - 1, src->cols + block_size - 1, CV_32F )); - CV_CALL( kernel = cvCreateMat( block_size, block_size, CV_32F )); - cvTsAdd( 0, cvScalarAll(0), 0, cvScalarAll(0), cvScalarAll(1./*(block_size*block_size)*/), kernel, 0 ); - anchor = cvPoint( block_size/2, block_size/2 ); - - cvTsPrepareToFilter( dx2, src2, anchor, CV_TS_BORDER_REPLICATE ); - cvTsConvolve2D( src2, dx2, kernel, anchor ); - cvTsPrepareToFilter( dy2, src2, anchor, CV_TS_BORDER_REPLICATE ); - cvTsConvolve2D( src2, dy2, kernel, anchor ); - cvTsPrepareToFilter( dxdy, src2, anchor, CV_TS_BORDER_REPLICATE ); - cvTsConvolve2D( src2, dxdy, kernel, anchor ); - - if( mode == 0 ) - { - for( i = 0; i < src->rows; i++ ) - { - float* eigenvp = (float*)(eigenv->data.ptr + i*eigenv->step); - float* ocv_eigenvp = (float*)(ocv_eigenv->data.ptr + i*ocv_eigenv->step); - const float* dxdyp = (float*)(dxdy->data.ptr + i*dxdy->step); - const float* dx2p = (float*)(dx2->data.ptr + i*dx2->step); - const float* dy2p = (float*)(dy2->data.ptr + i*dy2->step); - - for( j = 0; j < src->cols; j++ ) - { - double a = dx2p[j], b = dxdyp[j], c = dy2p[j]; - double d = sqrt((a-c)*(a-c) + 4*b*b); - double l1 = 0.5*(a + c + d); - double l2 = 0.5*(a + c - d); - double x1, y1, x2, y2, s; - - if( fabs(a - l1) + fabs(b) >= 1e-3 ) - x1 = b, y1 = l1 - a; - else - x1 = l1 - c, y1 = b; - s = 1./(sqrt(x1*x1+y1*y1)+DBL_EPSILON); - x1 *= s; y1 *= s; - - if( fabs(a - l2) + fabs(b) >= 1e-3 ) - x2 = b, y2 = l2 - a; - else - x2 = l2 - c, y2 = b; - s = 1./(sqrt(x2*x2+y2*y2)+DBL_EPSILON); - x2 *= s; y2 *= s; - - /* the orientation of eigen vectors might be inversed relative to OpenCV function, - which is normal */ - if( (fabs(x1) >= fabs(y1) && ocv_eigenvp[j*6+2]*x1 < 0) || - (fabs(x1) < fabs(y1) && ocv_eigenvp[j*6+3]*y1 < 0) ) - x1 = -x1, y1 = -y1; - - if( (fabs(x2) >= fabs(y2) && ocv_eigenvp[j*6+4]*x2 < 0) || - (fabs(x2) < fabs(y2) && ocv_eigenvp[j*6+5]*y2 < 0) ) - x2 = -x2, y2 = -y2; - - eigenvp[j*6] = (float)l1; - eigenvp[j*6+1] = (float)l2; - eigenvp[j*6+2] = (float)x1; - eigenvp[j*6+3] = (float)y1; - eigenvp[j*6+4] = (float)x2; - eigenvp[j*6+5] = (float)y2; - } - } - } - else if( mode == 1 ) - { - for( i = 0; i < src->rows; i++ ) - { - float* eigenvp = (float*)(eigenv->data.ptr + i*eigenv->step); - const float* dxdyp = (float*)(dxdy->data.ptr + i*dxdy->step); - const float* dx2p = (float*)(dx2->data.ptr + i*dx2->step); - const float* dy2p = (float*)(dy2->data.ptr + i*dy2->step); - - for( j = 0; j < src->cols; j++ ) - { - double a = dx2p[j], b = dxdyp[j], c = dy2p[j]; - double d = sqrt((a-c)*(a-c) + 4*b*b); - eigenvp[j] = (float)(0.5*(a + c - d)); - } - } - } - - __END__; - - cvReleaseMat( &dx2 ); - cvReleaseMat( &dy2 ); - cvReleaseMat( &dxdy ); - cvReleaseMat( &src2 ); - cvReleaseMat( &kernel ); -} - - -// min eigenval -class CV_MinEigenValTest : public CV_FeatureSelBaseTest -{ -public: - CV_MinEigenValTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_MinEigenValTest::CV_MinEigenValTest() - : CV_FeatureSelBaseTest( "features-mineval", "cvCornerMinEigenVal", 1 ) -{ -} - - -void CV_MinEigenValTest::run_func() -{ - cvCornerMinEigenVal( test_array[INPUT][0], test_array[OUTPUT][0], - block_size, aperture_size ); -} - - -void CV_MinEigenValTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsCornerEigenValsVecs( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - &test_mat[OUTPUT][0], block_size, aperture_size, 1 ); -} - - -CV_MinEigenValTest features_mineval; - - -// eigenval's & vec's -class CV_EigenValVecTest : public CV_FeatureSelBaseTest -{ -public: - CV_EigenValVecTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_EigenValVecTest::CV_EigenValVecTest() - : CV_FeatureSelBaseTest( "features-evalvec", "cvCornerEigenValsAndVecs", 6 ) -{ -} - - -void CV_EigenValVecTest::run_func() -{ - cvCornerEigenValsAndVecs( test_array[INPUT][0], test_array[OUTPUT][0], - block_size, aperture_size ); -} - - -void CV_EigenValVecTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsCornerEigenValsVecs( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - &test_mat[OUTPUT][0], block_size, aperture_size, 0 ); -} - - -CV_EigenValVecTest features_evalvec; - - - -static const char* precorner_param_names[] = { "aperture", "size", "depth", 0 }; -static const int precorner_aperture[] = { 3, 5, 7 }; - -// precornerdetect -class CV_PreCornerDetectTest : public CV_FeatureSelBaseTest -{ -public: - CV_PreCornerDetectTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); - int prepare_test_case( int ); - int write_default_params(CvFileStorage* fs); -}; - - -CV_PreCornerDetectTest::CV_PreCornerDetectTest() - : CV_FeatureSelBaseTest( "features-precorner", "cvPreCornerDetect", 1 ) -{ - default_timing_param_names = precorner_param_names; -} - - -int CV_PreCornerDetectTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_FeatureSelBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "aperture", precorner_aperture, CV_DIM(precorner_aperture) ); - } - - return code; -} - - -void CV_PreCornerDetectTest::run_func() -{ - cvPreCornerDetect( test_array[INPUT][0], test_array[OUTPUT][0], aperture_size ); -} - - -int CV_PreCornerDetectTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_FeatureSelBaseTest::prepare_test_case( test_case_idx ); - if( aperture_size < 0 ) - aperture_size = 3; - return code; -} - - -void CV_PreCornerDetectTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - /*cvTsCornerEigenValsVecs( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - block_size, aperture_size, 0 );*/ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_OUTPUT][0]; - - int type = CV_MAT_TYPE(src->type), ftype = CV_32FC1; - CvPoint anchor = { aperture_size/2, aperture_size/2 }; - double denom; - int i, j; - - CvMat* dx = cvCreateMat( src->rows, src->cols, ftype ); - CvMat* dy = cvCreateMat( src->rows, src->cols, ftype ); - CvMat* d2x = cvCreateMat( src->rows, src->cols, ftype ); - CvMat* d2y = cvCreateMat( src->rows, src->cols, ftype ); - CvMat* dxy = cvCreateMat( src->rows, src->cols, ftype ); - CvMat* tmp = cvCreateMat( src->rows + aperture_size - 1, - src->cols + aperture_size - 1, ftype ); - CvMat* kernel = cvCreateMat( aperture_size, aperture_size, ftype ); - - if( type != ftype ) - { - cvTsAdd( src, cvScalarAll(1./255), 0, cvScalarAll(0.), cvScalarAll(0.), dx, 0 ); - src = dx; - } - - cvTsPrepareToFilter( src, tmp, anchor, CV_TS_BORDER_REPLICATE ); - - cvTsCalcSobelKernel2D( 1, 0, aperture_size, 0, kernel ); - cvTsConvolve2D( tmp, dx, kernel, anchor ); - cvTsCalcSobelKernel2D( 0, 1, aperture_size, 0, kernel ); - cvTsConvolve2D( tmp, dy, kernel, anchor ); - cvTsCalcSobelKernel2D( 2, 0, aperture_size, 0, kernel ); - cvTsConvolve2D( tmp, d2x, kernel, anchor ); - cvTsCalcSobelKernel2D( 0, 2, aperture_size, 0, kernel ); - cvTsConvolve2D( tmp, d2y, kernel, anchor ); - cvTsCalcSobelKernel2D( 1, 1, aperture_size, 0, kernel ); - cvTsConvolve2D( tmp, dxy, kernel, anchor ); - - denom = 1 << (aperture_size-1); - denom = denom * denom * denom; - denom = 1./denom; - - for( i = 0; i < src->rows; i++ ) - { - const float* _dx = (const float*)(dx->data.ptr + i*dx->step); - const float* _dy = (const float*)(dy->data.ptr + i*dy->step); - const float* _d2x = (const float*)(d2x->data.ptr + i*d2x->step); - const float* _d2y = (const float*)(d2y->data.ptr + i*d2y->step); - const float* _dxy = (const float*)(dxy->data.ptr + i*dxy->step); - float* corner = (float*)(dst->data.ptr + i*dst->step); - - for( j = 0; j < src->cols; j++ ) - { - double x = _dx[j]; - double y = _dy[j]; - - corner[j] = (float)(denom*(x*x*_d2y[j] + y*y*_d2x[j] - 2*x*y*_dxy[j])); - } - } - - cvReleaseMat( &dx ); - cvReleaseMat( &dy ); - cvReleaseMat( &d2x ); - cvReleaseMat( &d2y ); - cvReleaseMat( &dxy ); - cvReleaseMat( &tmp ); - cvReleaseMat( &kernel ); -} - - -CV_PreCornerDetectTest precorner; - - -///////// integral ///////// - -static const char* integral_param_names[] = { "output", "size", "channels", "sum_depth", "depth", 0 }; -static const int integral_sum_depth[] = { CV_32S, CV_64F, -1 }; -static const int integral_block_size[] = { 3, 5, 11 }; -static const char* integral_output[] = { "sum", "sum+sqsum", "all", 0 }; - -class CV_IntegralTest : public CvArrTest -{ -public: - CV_IntegralTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int prepare_test_case( int test_case_idx ); - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_IntegralTest::CV_IntegralTest() - : CvArrTest( "integral", "cvIntegral", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - element_wise_relative_error = false; - - size_list = filter_sizes; - whole_size_list = filter_whole_sizes; - default_timing_param_names = integral_param_names; - depth_list = morph_depths; - cn_list = filter_channels; -} - - -void CV_IntegralTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - int depth = CV_MAT_DEPTH(type); - if( depth == CV_32F ) - { - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); - } -} - - -int CV_IntegralTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "sum_depth", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; integral_sum_depth[i] >= 0; i++ ) - cvWriteString( fs, 0, cvTsGetTypeName(integral_sum_depth[i]) ); - cvEndWriteStruct(fs); - - write_string_list( fs, "output", integral_output ); - } - - return code; -} - - -void CV_IntegralTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2, sum_depth; - int cn = cvTsRandInt(rng) % 3 + 1; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize sum_size; - - depth = depth == 0 ? CV_8U : CV_32F; - cn += cn == 2; - sum_depth = depth == CV_8U && (cvTsRandInt(rng) & 1) == 1 ? CV_32S : CV_64F; - - //sizes[INPUT][0].width = 1; - - types[INPUT][0] = CV_MAKETYPE(depth,cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = - types[OUTPUT][2] = types[REF_OUTPUT][2] = CV_MAKETYPE(sum_depth, cn); - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_MAKETYPE(CV_64F, cn); - - sum_size.width = sizes[INPUT][0].width + 1; - sum_size.height = sizes[INPUT][0].height + 1; - - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sum_size; - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = - sizes[OUTPUT][2] = sizes[REF_OUTPUT][2] = cvSize(0,0); - - if( cvTsRandInt(rng) % 3 > 0 ) - { - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = sum_size; - if( cvTsRandInt(rng) % 2 > 0 ) - sizes[REF_OUTPUT][2] = sizes[OUTPUT][2] = sum_size; - } - - types[TEMP][0] = CV_MAKETYPE(depth,1); - types[TEMP][1] = CV_MAKETYPE(CV_32F,1); - types[TEMP][2] = types[TEMP][3] = types[TEMP][4] = CV_MAKETYPE(CV_64F,1); - - sizes[TEMP][0] = cn > 1 ? sizes[INPUT][0] : cvSize(0,0); - sizes[TEMP][1] = depth == CV_8U ? sum_size : cvSize(0,0); - - sizes[TEMP][2] = cn > 1 || sum_depth == CV_32S ? sizes[OUTPUT][0] : cvSize(0,0); - sizes[TEMP][3] = cn > 1 ? sizes[OUTPUT][1] : cvSize(0,0); - sizes[TEMP][4] = cn > 1 || sum_depth == CV_32S ? sizes[OUTPUT][2] : cvSize(0,0); -} - - -double CV_IntegralTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[i][j].type); - return depth == CV_32S ? 0 : FLT_EPSILON; -} - - -void CV_IntegralTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* output = cvReadString( find_timing_param( "output" ), "sum" ); - CvSize sum_size = { sizes[INPUT][0].width + 1, sizes[INPUT][0].height + 1 }; - const char* _sum_depth = cvReadString( find_timing_param( "sum_depth" ), "64f" ); - int cn = CV_MAT_CN(types[INPUT][0]); - int sum_depth = strcmp( _sum_depth, "32s" ) == 0 ? CV_32S : CV_64F; - - sizes[OUTPUT][0] = sizes[OUTPUT][1] = sizes[OUTPUT][2] = cvSize(0,0); - whole_sizes[OUTPUT][0] = whole_sizes[OUTPUT][1] = whole_sizes[OUTPUT][2] = cvSize(0,0); - - if( strcmp( output, "sum" ) == 0 ) - sizes[OUTPUT][0] = whole_sizes[OUTPUT][0] = sum_size; - else if( strcmp( output, "all" ) == 0 ) - sizes[OUTPUT][0] = sizes[OUTPUT][1] = sizes[OUTPUT][2] = - whole_sizes[OUTPUT][0] = whole_sizes[OUTPUT][1] = whole_sizes[OUTPUT][2] = sum_size; - else - sizes[OUTPUT][0] = sizes[OUTPUT][1] = - whole_sizes[OUTPUT][0] = whole_sizes[OUTPUT][1] = sum_size; - - sizes[TEMP][0] = sizes[TEMP][1] = sizes[TEMP][2] = sizes[TEMP][3] = sizes[TEMP][4] = cvSize(0,0); - - types[OUTPUT][0] = types[OUTPUT][2] = CV_MAKETYPE( sum_depth, cn ); - types[OUTPUT][1] = CV_MAKETYPE( CV_64F, cn ); -} - - -void CV_IntegralTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "output" ), "sum" ) ); - ptr += strlen(ptr); - params_left--; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CV_IntegralTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - return code > 0 && ((test_array[OUTPUT][2] && CV_MAT_CN(test_mat[OUTPUT][2].type) > 1) || - CV_MAT_DEPTH(test_mat[OUTPUT][0].type) < CV_MAT_DEPTH(test_mat[INPUT][0].type)) ? 0 : code; -} - - -void CV_IntegralTest::run_func() -{ - cvIntegral( test_array[INPUT][0], test_array[OUTPUT][0], - test_array[OUTPUT][1], test_array[OUTPUT][2] ); -} - - -static void -cvTsIntegral( const CvMat* img, const CvMat* sum, const CvMat* sqsum, const CvMat* tilted ) -{ - const float* data = img->data.fl; - double* sdata = sum->data.db; - double* sqdata = sqsum ? sqsum->data.db : 0; - double* tdata = tilted ? tilted->data.db : 0; - int step = img->step/sizeof(data[0]); - int sstep = sum->step/sizeof(sdata[0]); - int sqstep = sqsum ? sqsum->step/sizeof(sqdata[0]) : 0; - int tstep = tilted ? tilted->step/sizeof(tdata[0]) : 0; - CvSize size = cvGetMatSize( img ); - - memset( sdata, 0, (size.width+1)*sizeof(sdata[0]) ); - if( sqsum ) - memset( sqdata, 0, (size.width+1)*sizeof(sqdata[0]) ); - if( tilted ) - memset( tdata, 0, (size.width+1)*sizeof(tdata[0]) ); - - for( ; size.height--; data += step ) - { - double s = 0, sq = 0; - int x; - sdata += sstep; - sqdata += sqstep; - tdata += tstep; - - for( x = 0; x <= size.width; x++ ) - { - double t = x > 0 ? data[x-1] : 0, ts = t; - s += t; - sq += t*t; - - sdata[x] = s + sdata[x - sstep]; - if( sqdata ) - sqdata[x] = sq + sqdata[x - sqstep]; - - if( !tdata ) - continue; - - if( x == 0 ) - ts += tdata[-tstep+1]; - else - { - ts += tdata[x-tstep-1]; - if( data > img->data.fl ) - { - ts += data[x-step-1]; - if( x < size.width ) - ts += tdata[x-tstep+1] - tdata[x-tstep*2]; - } - } - - tdata[x] = ts; - } - } -} - - -void CV_IntegralTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src0 = &test_mat[INPUT][0]; - int i, cn = CV_MAT_CN(src0->type), depth = CV_MAT_DEPTH(src0->type); - CvMat* plane = cn > 1 ? &test_mat[TEMP][0] : 0; - CvMat ibuf, *plane32f = 0; - - CvMat* sum0 = &test_mat[REF_OUTPUT][0]; - CvMat* sqsum0 = test_array[REF_OUTPUT][1] ? &test_mat[REF_OUTPUT][1] : 0; - CvMat* tsum0 = test_array[REF_OUTPUT][2] ? &test_mat[REF_OUTPUT][2] : 0; - - CvMat* sum1 = test_array[TEMP][2] ? &test_mat[TEMP][2] : sum0; - CvMat* sqsum1 = test_array[TEMP][3] ? &test_mat[TEMP][3] : sqsum0; - CvMat* tsum1 = test_array[TEMP][4] ? &test_mat[TEMP][4] : tsum0; - CvMat buf, *ptr = 0; - - if( depth == CV_8U ) - { - ibuf = test_mat[TEMP][1]; - plane32f = &ibuf; - plane32f->cols--; - plane32f->rows--; - plane32f->type &= ~CV_MAT_CONT_FLAG; - - if( CV_MAT_DEPTH(sum0->type) == CV_32S && cn > 1 ) - { - // in case of 8u->32s integral transform aliase the temporary output buffer with temporary input buffer - buf = test_mat[TEMP][1]; - ptr = &buf; - ptr->type = (ptr->type & ~CV_MAT_DEPTH_MASK) | CV_32S; - } - } - - for( i = 0; i < cn; i++ ) - { - CvMat* sptr = src0; - CvMat* dptr; - if( cn > 1 ) - { - cvTsExtract( sptr, plane, i ); - sptr = plane; - } - - if( CV_MAT_DEPTH(sptr->type) != CV_32F ) - { - cvTsConvert( sptr, plane32f ); - sptr = plane32f; - } - - cvTsIntegral( sptr, sum1, sqsum1, tsum1 ); - if( sum1 != sum0 ) - { - dptr = sum1; - if( ptr ) - { - cvTsConvert( dptr, ptr ); - dptr = ptr; - } - if( cn == 1 ) - cvTsConvert( dptr, sum0 ); - else - cvTsInsert( dptr, sum0, i ); - } - - if( tsum1 != tsum0 ) - { - dptr = tsum1; - if( ptr ) - { - cvTsConvert( dptr, ptr ); - dptr = ptr; - } - if( cn == 1 ) - cvTsConvert( dptr, tsum0 ); - else - cvTsInsert( dptr, tsum0, i ); - } - - if( sqsum1 != sqsum0 ) - cvTsInsert( sqsum1, sqsum0, i ); - } -} - - -CV_IntegralTest integral_test; diff --git a/tests/cv/src/afloodfill.cpp b/tests/cv/src/afloodfill.cpp deleted file mode 100644 index 9674f02..0000000 --- a/tests/cv/src/afloodfill.cpp +++ /dev/null @@ -1,596 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const char* floodfill_param_names[] = { "size", "channels", "depth", "dist_type", "labels", 0 }; -static const CvSize floodfill_sizes[] = {{320, 240}, {720,480}, {-1,-1}}; -static const CvSize floodfill_whole_sizes[] = {{320, 240}, {720,480}, {-1,-1}}; -//static const char* floodfill_types[] = { "fixed_level", "fixed_range", "floating_range", 0 }; -static const int floodfill_depths[] = { CV_8U, CV_32F, -1 }; -static const int floodfill_channels[] = { 1, 3, -1 }; - -class CV_FloodFillTest : public CvArrTest -{ -public: - CV_FloodFillTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - /*int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left );*/ - CvPoint seed_pt; - CvScalar new_val; - CvScalar l_diff, u_diff; - int connectivity; - bool use_mask, mask_only; - int range_type; - int new_mask_val; - bool test_cpp; -}; - - -CV_FloodFillTest::CV_FloodFillTest() - : CvArrTest( "floodfill", "cvFloodFill", "" ) -{ - test_array[INPUT_OUTPUT].push(NULL); - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - optional_mask = false; - element_wise_relative_error = true; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - - default_timing_param_names = floodfill_param_names; - depth_list = floodfill_depths; - size_list = floodfill_sizes; - whole_size_list = floodfill_whole_sizes; - cn_list = floodfill_channels; - test_cpp = false; -} - - -void CV_FloodFillTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth, cn; - int i; - double buf[8]; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - depth = cvTsRandInt(rng) % 2; - depth = depth == 0 ? CV_8U : CV_32F; - cn = cvTsRandInt(rng) & 1 ? 3 : 1; - - use_mask = (cvTsRandInt(rng) & 1) != 0; - connectivity = (cvTsRandInt(rng) & 1) ? 4 : 8; - mask_only = use_mask && (cvTsRandInt(rng) & 1) != 0; - new_mask_val = cvTsRandInt(rng) & 255; - range_type = cvTsRandInt(rng) % 3; - - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(depth, cn); - types[INPUT_OUTPUT][1] = types[REF_INPUT_OUTPUT][1] = CV_8UC1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(9,1); - - if( !use_mask ) - sizes[INPUT_OUTPUT][1] = sizes[REF_INPUT_OUTPUT][1] = cvSize(0,0); - else - { - CvSize sz = sizes[INPUT_OUTPUT][0]; - sizes[INPUT_OUTPUT][1] = sizes[REF_INPUT_OUTPUT][1] = cvSize(sz.width+2,sz.height+2); - } - - seed_pt.x = cvTsRandInt(rng) % sizes[INPUT_OUTPUT][0].width; - seed_pt.y = cvTsRandInt(rng) % sizes[INPUT_OUTPUT][0].height; - - if( range_type == 0 ) - l_diff = u_diff = cvScalarAll(0.); - else - { - CvMat m = cvMat( 1, 8, CV_16S, buf ); - cvRandArr( rng, &m, CV_RAND_NORMAL, cvScalarAll(0), cvScalarAll(32) ); - for( i = 0; i < 4; i++ ) - { - l_diff.val[i] = fabs(m.data.s[i]/16.); - u_diff.val[i] = fabs(m.data.s[i+4]/16.); - } - } - - new_val = cvScalarAll(0.); - for( i = 0; i < cn; i++ ) - new_val.val[i] = cvTsRandReal(rng)*255; - - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -double CV_FloodFillTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - return i == OUTPUT ? FLT_EPSILON : j == 0 ? FLT_EPSILON : 0; -} - - -void CV_FloodFillTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - CvRNG* rng = ts->get_rng(); - - if( i != INPUT && i != INPUT_OUTPUT ) - { - CvArrTest::fill_array( test_case_idx, i, j, arr ); - return; - } - - if( j == 0 ) - { - CvMat* tmp = arr; - CvScalar m = cvScalarAll(128); - CvScalar s = cvScalarAll(10); - - if( CV_MAT_DEPTH(arr->type) == CV_32FC1 ) - tmp = cvCreateMat( arr->rows, arr->cols, arr->type & CV_MAT_CN_MASK ); - - if( range_type == 0 ) - s = cvScalarAll(2); - - cvRandArr( rng, tmp, CV_RAND_NORMAL, m, s ); - if( arr != tmp ) - { - cvTsConvert( tmp, arr ); - cvReleaseMat( &tmp ); - } - } - else - { - CvScalar l = cvScalarAll(-2); - CvScalar u = cvScalarAll(2); - cvRandArr( rng, arr, CV_RAND_UNI, l, u ); - cvRectangle( arr, cvPoint(0,0), cvPoint(arr->cols-1,arr->rows-1), cvScalarAll(1), 1, 8, 0 ); - } -} - - -void CV_FloodFillTest::run_func() -{ - int flags = connectivity + (mask_only ? CV_FLOODFILL_MASK_ONLY : 0) + - (range_type == 1 ? CV_FLOODFILL_FIXED_RANGE : 0) + (new_mask_val << 8); - double* odata = test_mat[OUTPUT][0].data.db; - - if(!test_cpp) - { - CvConnectedComp comp; - cvFloodFill( test_array[INPUT_OUTPUT][0], seed_pt, new_val, l_diff, u_diff, &comp, - flags, test_array[INPUT_OUTPUT][1] ); - odata[0] = comp.area; - odata[1] = comp.rect.x; - odata[2] = comp.rect.y; - odata[3] = comp.rect.width; - odata[4] = comp.rect.height; - odata[5] = comp.value.val[0]; - odata[6] = comp.value.val[1]; - odata[7] = comp.value.val[2]; - odata[8] = comp.value.val[3]; - } - else - { - cv::Mat img = cv::cvarrToMat(test_array[INPUT_OUTPUT][0]), - mask = test_array[INPUT_OUTPUT][1] ? cv::cvarrToMat(test_array[INPUT_OUTPUT][1]) : cv::Mat(); - cv::Rect rect; - int area; - if( !mask.data ) - area = cv::floodFill( img, seed_pt, new_val, &rect, l_diff, u_diff, flags ); - else - area = cv::floodFill( img, mask, seed_pt, new_val, &rect, l_diff, u_diff, flags ); - odata[0] = area; - odata[1] = rect.x; - odata[2] = rect.y; - odata[3] = rect.width; - odata[4] = rect.height; - odata[5] = odata[6] = odata[7] = odata[8] = 0; - } -} - - -typedef struct ff_offset_pair_t -{ - int mofs, iofs; -} -ff_offset_pair_t; - -static void -cvTsFloodFill( CvMat* _img, CvPoint seed_pt, CvScalar new_val, - CvScalar l_diff, CvScalar u_diff, CvMat* _mask, - double* comp, int connectivity, int range_type, - int new_mask_val, bool mask_only ) -{ - CvMemStorage* st = cvCreateMemStorage(); - ff_offset_pair_t p0, p; - CvSeq* seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(p0), st ); - CvMat* tmp = _img; - CvMat* mask; - CvRect r = cvRect( 0, 0, -1, -1 ); - int area = 0; - int i, j; - ushort* m; - float* img; - int mstep, step; - int cn = CV_MAT_CN(_img->type); - int mdelta[8], idelta[8], ncount; - int cols = _img->cols, rows = _img->rows; - int u0 = 0, u1 = 0, u2 = 0; - double s0 = 0, s1 = 0, s2 = 0; - - if( CV_MAT_DEPTH(_img->type) == CV_8U ) - { - tmp = cvCreateMat( rows, cols, CV_MAKETYPE(CV_32F,CV_MAT_CN(_img->type)) ); - cvTsConvert(_img, tmp); - } - - mask = cvCreateMat( rows + 2, cols + 2, CV_16UC1 ); - - if( _mask ) - cvTsConvert( _mask, mask ); - else - { - cvTsZero( mask ); - cvRectangle( mask, cvPoint(0,0), cvPoint(mask->cols-1,mask->rows-1), cvScalarAll(1.), 1, 8, 0 ); - } - - new_mask_val = (new_mask_val != 0 ? new_mask_val : 1) << 8; - - m = (ushort*)(mask->data.ptr + mask->step) + 1; - mstep = mask->step / sizeof(m[0]); - img = tmp->data.fl; - step = tmp->step / sizeof(img[0]); - - p0.mofs = seed_pt.y*mstep + seed_pt.x; - p0.iofs = seed_pt.y*step + seed_pt.x*cn; - - if( m[p0.mofs] ) - goto _exit_; - - cvSeqPush( seq, &p0 ); - m[p0.mofs] = (ushort)new_mask_val; - - if( connectivity == 4 ) - { - ncount = 4; - mdelta[0] = -mstep; idelta[0] = -step; - mdelta[1] = -1; idelta[1] = -cn; - mdelta[2] = 1; idelta[2] = cn; - mdelta[3] = mstep; idelta[3] = step; - } - else - { - ncount = 8; - mdelta[0] = -mstep-1; mdelta[1] = -mstep; mdelta[2] = -mstep+1; - idelta[0] = -step-cn; idelta[1] = -step; idelta[2] = -step+cn; - - mdelta[3] = -1; mdelta[4] = 1; - idelta[3] = -cn; idelta[4] = cn; - - mdelta[5] = mstep-1; mdelta[6] = mstep; mdelta[7] = mstep+1; - idelta[5] = step-cn; idelta[6] = step; idelta[7] = step+cn; - } - - if( cn == 1 ) - { - float a0 = (float)-l_diff.val[0]; - float b0 = (float)u_diff.val[0]; - - s0 = img[p0.iofs]; - - if( range_type < 2 ) - { - a0 += (float)s0; b0 += (float)s0; - } - - while( seq->total ) - { - cvSeqPop( seq, &p0 ); - float a = a0, b = b0; - float* ptr = img + p0.iofs; - ushort* mptr = m + p0.mofs; - - if( range_type == 2 ) - a += ptr[0], b += ptr[0]; - - for( i = 0; i < ncount; i++ ) - { - int md = mdelta[i], id = idelta[i]; - float v; - if( !mptr[md] && a <= (v = ptr[id]) && v <= b ) - { - mptr[md] = (ushort)new_mask_val; - p.mofs = p0.mofs + md; - p.iofs = p0.iofs + id; - cvSeqPush( seq, &p ); - } - } - } - } - else - { - float a0 = (float)-l_diff.val[0]; - float a1 = (float)-l_diff.val[1]; - float a2 = (float)-l_diff.val[2]; - float b0 = (float)u_diff.val[0]; - float b1 = (float)u_diff.val[1]; - float b2 = (float)u_diff.val[2]; - - s0 = img[p0.iofs]; - s1 = img[p0.iofs + 1]; - s2 = img[p0.iofs + 2]; - - if( range_type < 2 ) - { - a0 += (float)s0; b0 += (float)s0; - a1 += (float)s1; b1 += (float)s1; - a2 += (float)s2; b2 += (float)s2; - } - - while( seq->total ) - { - cvSeqPop( seq, &p0 ); - float _a0 = a0, _a1 = a1, _a2 = a2; - float _b0 = b0, _b1 = b1, _b2 = b2; - float* ptr = img + p0.iofs; - ushort* mptr = m + p0.mofs; - - if( range_type == 2 ) - { - _a0 += ptr[0]; _b0 += ptr[0]; - _a1 += ptr[1]; _b1 += ptr[1]; - _a2 += ptr[2]; _b2 += ptr[2]; - } - - for( i = 0; i < ncount; i++ ) - { - int md = mdelta[i], id = idelta[i]; - float v; - if( !mptr[md] && - _a0 <= (v = ptr[id]) && v <= _b0 && - _a1 <= (v = ptr[id+1]) && v <= _b1 && - _a2 <= (v = ptr[id+2]) && v <= _b2 ) - { - mptr[md] = (ushort)new_mask_val; - p.mofs = p0.mofs + md; - p.iofs = p0.iofs + id; - cvSeqPush( seq, &p ); - } - } - } - } - - r.x = r.width = seed_pt.x; - r.y = r.height = seed_pt.y; - - if( !mask_only ) - { - s0 = new_val.val[0]; - s1 = new_val.val[1]; - s2 = new_val.val[2]; - - if( tmp != _img ) - { - u0 = cvRound(s0); - u0 = CV_CAST_8U(u0); - u1 = cvRound(s1); - u1 = CV_CAST_8U(u1); - u2 = cvRound(s2); - u2 = CV_CAST_8U(u2); - - s0 = u0; - s1 = u1; - s2 = u2; - } - } - else - s0 = s1 = s2 = 0; - - new_mask_val >>= 8; - - for( i = 0; i < rows; i++ ) - { - float* ptr = img + i*step; - ushort* mptr = m + i*mstep; - uchar* dmptr = _mask ? _mask->data.ptr + (i+1)*_mask->step + 1 : 0; - uchar* dptr = tmp != _img ? _img->data.ptr + i*_img->step : 0; - double area0 = area; - - for( j = 0; j < cols; j++ ) - { - if( mptr[j] > 255 ) - { - if( dmptr ) - dmptr[j] = (uchar)new_mask_val; - if( !mask_only ) - { - if( cn == 1 ) - { - if( dptr ) - dptr[j] = (uchar)u0; - else - ptr[j] = (float)s0; - } - else - { - if( dptr ) - { - dptr[j*3] = (uchar)u0; - dptr[j*3+1] = (uchar)u1; - dptr[j*3+2] = (uchar)u2; - } - else - { - ptr[j*3] = (float)s0; - ptr[j*3+1] = (float)s1; - ptr[j*3+2] = (float)s2; - } - } - } - else - { - if( cn == 1 ) - s0 += ptr[j]; - else - { - s0 += ptr[j*3]; - s1 += ptr[j*3+1]; - s2 += ptr[j*3+2]; - } - } - - area++; - if( r.x > j ) - r.x = j; - if( r.width < j ) - r.width = j; - } - } - - if( area != area0 ) - { - if( r.y > i ) - r.y = i; - if( r.height < i ) - r.height = i; - } - } - -_exit_: - cvReleaseMat( &mask ); - if( tmp != _img ) - cvReleaseMat( &tmp ); - - comp[0] = area; - comp[1] = r.x; - comp[2] = r.y; - comp[3] = r.width - r.x + 1; - comp[4] = r.height - r.y + 1; - if( mask_only ) - { - double t = area ? 1./area : 0; - s0 *= t; - s1 *= t; - s2 *= t; - } - comp[5] = s0; - comp[6] = s1; - comp[7] = s2; - comp[8] = 0; -} - - -void CV_FloodFillTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - double* comp = test_mat[REF_OUTPUT][0].data.db; - cvTsFloodFill( &test_mat[REF_INPUT_OUTPUT][0], seed_pt, new_val, l_diff, u_diff, - test_array[REF_INPUT_OUTPUT][1] ? &test_mat[REF_INPUT_OUTPUT][1] : 0, - comp, connectivity, range_type, new_mask_val, mask_only ); - if(test_cpp) - comp[5] = comp[6] = comp[7] = comp[8] = 0; -} - - -/*int CV_FloodFillTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_string_list( fs, "dist_type", floodfill_types ); - write_int_list( fs, "labels", floodfill_labels, -1, -1 ); - } - - return code; -} - - -void CV_FloodFillTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* distype_str = cvReadString( find_timing_param( "dist_type" ), "l2_5x5" ); - mask_size = strstr( distype_str, "3x3" ) ? 3 : 5; - dist_type = distype_str[0] == 'c' ? CV_DIST_C : distype_str[1] == '1' ? CV_DIST_L1 : CV_DIST_L2; - fill_labels = cvReadInt( find_timing_param( "labels" ), 0 ); - - types[INPUT][0] = CV_8UC1; - types[OUTPUT][0] = CV_32FC1; - types[OUTPUT][1] = CV_32SC1; - - if( !fill_labels ) - sizes[OUTPUT][0] = whole_sizes[OUTPUT][0] = cvSize(0,0); -} - - -void CV_FloodFillTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "dist_type" ), "l2_5x5" ) ); - ptr += strlen(ptr); - sprintf( ptr, "%s,", fill_labels ? "labels" : "no_labels" ); - ptr += strlen(ptr); - params_left -= 2; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -}*/ - - -CV_FloodFillTest floodfill_test; - -/* End of file. */ diff --git a/tests/cv/src/afundam.cpp b/tests/cv/src/afundam.cpp deleted file mode 100644 index 4a93d95..0000000 --- a/tests/cv/src/afundam.cpp +++ /dev/null @@ -1,1409 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -int cvTsRodrigues( const CvMat* src, CvMat* dst, CvMat* jacobian ) -{ - int depth; - int i; - float Jf[27]; - double J[27]; - CvMat _Jf, matJ = cvMat( 3, 9, CV_64F, J ); - - depth = CV_MAT_DEPTH(src->type); - - if( jacobian ) - { - assert( (jacobian->rows == 9 && jacobian->cols == 3) || - (jacobian->rows == 3 && jacobian->cols == 9) ); - } - - if( src->cols == 1 || src->rows == 1 ) - { - double r[3], theta; - CvMat _r = cvMat( src->rows, src->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(src->type)), r); - - assert( dst->rows == 3 && dst->cols == 3 ); - - cvConvert( src, &_r ); - - theta = sqrt(r[0]*r[0] + r[1]*r[1] + r[2]*r[2]); - if( theta < DBL_EPSILON ) - { - cvSetIdentity( dst ); - - if( jacobian ) - { - memset( J, 0, sizeof(J) ); - J[5] = J[15] = J[19] = 1; - J[7] = J[11] = J[21] = -1; - } - } - else - { - // omega = r/theta (~[w1, w2, w3]) - double itheta = 1./theta; - double w1 = r[0]*itheta, w2 = r[1]*itheta, w3 = r[2]*itheta; - double alpha = cos(theta); - double beta = sin(theta); - double gamma = 1 - alpha; - double omegav[] = - { - 0, -w3, w2, - w3, 0, -w1, - -w2, w1, 0 - }; - double A[] = - { - w1*w1, w1*w2, w1*w3, - w2*w1, w2*w2, w2*w3, - w3*w1, w3*w2, w3*w3 - }; - double R[9]; - CvMat _omegav = cvMat(3, 3, CV_64F, omegav); - CvMat matA = cvMat(3, 3, CV_64F, A); - CvMat matR = cvMat(3, 3, CV_64F, R); - - cvSetIdentity( &matR, cvRealScalar(alpha) ); - cvScaleAdd( &_omegav, cvRealScalar(beta), &matR, &matR ); - cvScaleAdd( &matA, cvRealScalar(gamma), &matR, &matR ); - cvConvert( &matR, dst ); - - if( jacobian ) - { - // m3 = [r, theta] - double dm3din[] = - { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, - w1, w2, w3 - }; - // m2 = [omega, theta] - double dm2dm3[] = - { - itheta, 0, 0, -w1*itheta, - 0, itheta, 0, -w2*itheta, - 0, 0, itheta, -w3*itheta, - 0, 0, 0, 1 - }; - double t0[9*4]; - double dm1dm2[21*4]; - double dRdm1[9*21]; - CvMat _dm3din = cvMat( 4, 3, CV_64FC1, dm3din ); - CvMat _dm2dm3 = cvMat( 4, 4, CV_64FC1, dm2dm3 ); - CvMat _dm1dm2 = cvMat( 21, 4, CV_64FC1, dm1dm2 ); - CvMat _dRdm1 = cvMat( 9, 21, CV_64FC1, dRdm1 ); - CvMat _dRdm1_part; - CvMat _t0 = cvMat( 9, 4, CV_64FC1, t0 ); - CvMat _t1 = cvMat( 9, 4, CV_64FC1, dRdm1 ); - - // m1 = [alpha, beta, gamma, omegav; A] - memset( dm1dm2, 0, sizeof(dm1dm2) ); - dm1dm2[3] = -beta; - dm1dm2[7] = alpha; - dm1dm2[11] = beta; - - // dm1dm2(4:12,1:3) = [0 0 0 0 0 1 0 -1 0; - // 0 0 -1 0 0 0 1 0 0; - // 0 1 0 -1 0 0 0 0 0]' - // ------------------- - // 0 0 0 0 0 0 0 0 0 - dm1dm2[12 + 6] = dm1dm2[12 + 20] = dm1dm2[12 + 25] = 1; - dm1dm2[12 + 9] = dm1dm2[12 + 14] = dm1dm2[12 + 28] = -1; - - double dm1dw[] = - { - 2*w1, w2, w3, w2, 0, 0, w3, 0, 0, - 0, w1, 0, w1, 2*w2, w3, 0, w3, 0, - 0, 0, w1, 0, 0, w2, w1, w2, 2*w3 - }; - - CvMat _dm1dw = cvMat( 3, 9, CV_64FC1, dm1dw ); - CvMat _dm1dm2_part; - - cvGetSubRect( &_dm1dm2, &_dm1dm2_part, cvRect(0,12,3,9) ); - cvTranspose( &_dm1dw, &_dm1dm2_part ); - - memset( dRdm1, 0, sizeof(dRdm1) ); - dRdm1[0*21] = dRdm1[4*21] = dRdm1[8*21] = 1; - - cvGetCol( &_dRdm1, &_dRdm1_part, 1 ); - cvTranspose( &_omegav, &_omegav ); - cvReshape( &_omegav, &_omegav, 1, 1 ); - cvTranspose( &_omegav, &_dRdm1_part ); - - cvGetCol( &_dRdm1, &_dRdm1_part, 2 ); - cvReshape( &matA, &matA, 1, 1 ); - cvTranspose( &matA, &_dRdm1_part ); - - cvGetSubRect( &_dRdm1, &_dRdm1_part, cvRect(3,0,9,9) ); - cvSetIdentity( &_dRdm1_part, cvScalarAll(beta) ); - - cvGetSubRect( &_dRdm1, &_dRdm1_part, cvRect(12,0,9,9) ); - cvSetIdentity( &_dRdm1_part, cvScalarAll(gamma) ); - - matJ = cvMat( 9, 3, CV_64FC1, J ); - - cvMatMul( &_dRdm1, &_dm1dm2, &_t0 ); - cvMatMul( &_t0, &_dm2dm3, &_t1 ); - cvMatMul( &_t1, &_dm3din, &matJ ); - - _t0 = cvMat( 3, 9, CV_64FC1, t0 ); - cvTranspose( &matJ, &_t0 ); - - for( i = 0; i < 3; i++ ) - { - _t1 = cvMat( 3, 3, CV_64FC1, t0 + i*9 ); - cvTranspose( &_t1, &_t1 ); - } - - cvTranspose( &_t0, &matJ ); - } - } - } - else if( src->cols == 3 && src->rows == 3 ) - { - double R[9], A[9], I[9], r[3], W[3], U[9], V[9]; - double tr, alpha, beta, theta; - CvMat matR = cvMat( 3, 3, CV_64F, R ); - CvMat matA = cvMat( 3, 3, CV_64F, A ); - CvMat matI = cvMat( 3, 3, CV_64F, I ); - CvMat _r = cvMat( dst->rows, dst->cols, CV_MAKETYPE(CV_64F, CV_MAT_CN(dst->type)), r ); - CvMat matW = cvMat( 1, 3, CV_64F, W ); - CvMat matU = cvMat( 3, 3, CV_64F, U ); - CvMat matV = cvMat( 3, 3, CV_64F, V ); - - cvConvert( src, &matR ); - cvSVD( &matR, &matW, &matU, &matV, CV_SVD_MODIFY_A + CV_SVD_U_T + CV_SVD_V_T ); - cvGEMM( &matU, &matV, 1, 0, 0, &matR, CV_GEMM_A_T ); - - cvMulTransposed( &matR, &matA, 0 ); - cvSetIdentity( &matI ); - - if( cvNorm( &matA, &matI, CV_C ) > 1e-3 || - fabs( cvDet(&matR) - 1 ) > 1e-3 ) - return 0; - - tr = (cvTrace(&matR).val[0] - 1.)*0.5; - tr = tr > 1. ? 1. : tr < -1. ? -1. : tr; - theta = acos(tr); - alpha = cos(theta); - beta = sin(theta); - - if( beta >= 1e-5 ) - { - double dtheta_dtr = -1./sqrt(1 - tr*tr); - double vth = 1/(2*beta); - - // om1 = [R(3,2) - R(2,3), R(1,3) - R(3,1), R(2,1) - R(1,2)]' - double om1[] = { R[7] - R[5], R[2] - R[6], R[3] - R[1] }; - // om = om1*vth - // r = om*theta - double d3 = vth*theta; - - r[0] = om1[0]*d3; r[1] = om1[1]*d3; r[2] = om1[2]*d3; - cvConvert( &_r, dst ); - - if( jacobian ) - { - // var1 = [vth;theta] - // var = [om1;var1] = [om1;vth;theta] - double dvth_dtheta = -vth*alpha/beta; - double d1 = 0.5*dvth_dtheta*dtheta_dtr; - double d2 = 0.5*dtheta_dtr; - // dvar1/dR = dvar1/dtheta*dtheta/dR = [dvth/dtheta; 1] * dtheta/dtr * dtr/dR - double dvardR[5*9] = - { - 0, 0, 0, 0, 0, 1, 0, -1, 0, - 0, 0, -1, 0, 0, 0, 1, 0, 0, - 0, 1, 0, -1, 0, 0, 0, 0, 0, - d1, 0, 0, 0, d1, 0, 0, 0, d1, - d2, 0, 0, 0, d2, 0, 0, 0, d2 - }; - // var2 = [om;theta] - double dvar2dvar[] = - { - vth, 0, 0, om1[0], 0, - 0, vth, 0, om1[1], 0, - 0, 0, vth, om1[2], 0, - 0, 0, 0, 0, 1 - }; - double domegadvar2[] = - { - theta, 0, 0, om1[0]*vth, - 0, theta, 0, om1[1]*vth, - 0, 0, theta, om1[2]*vth - }; - - CvMat _dvardR = cvMat( 5, 9, CV_64FC1, dvardR ); - CvMat _dvar2dvar = cvMat( 4, 5, CV_64FC1, dvar2dvar ); - CvMat _domegadvar2 = cvMat( 3, 4, CV_64FC1, domegadvar2 ); - double t0[3*5]; - CvMat _t0 = cvMat( 3, 5, CV_64FC1, t0 ); - - cvMatMul( &_domegadvar2, &_dvar2dvar, &_t0 ); - cvMatMul( &_t0, &_dvardR, &matJ ); - } - } - else if( tr > 0 ) - { - cvZero( dst ); - if( jacobian ) - { - memset( J, 0, sizeof(J) ); - J[5] = J[15] = J[19] = 0.5; - J[7] = J[11] = J[21] = -0.5; - } - } - else - { - r[0] = theta*sqrt((R[0] + 1)*0.5); - r[1] = theta*sqrt((R[4] + 1)*0.5)*(R[1] >= 0 ? 1 : -1); - r[2] = theta*sqrt((R[8] + 1)*0.5)*(R[2] >= 0 ? 1 : -1); - cvConvert( &_r, dst ); - - if( jacobian ) - memset( J, 0, sizeof(J) ); - } - - if( jacobian ) - { - for( i = 0; i < 3; i++ ) - { - CvMat t = cvMat( 3, 3, CV_64F, J + i*9 ); - cvTranspose( &t, &t ); - } - } - } - else - { - assert(0); - return 0; - } - - if( jacobian ) - { - if( depth == CV_32F ) - { - if( jacobian->rows == matJ.rows ) - cvConvert( &matJ, jacobian ); - else - { - _Jf = cvMat( matJ.rows, matJ.cols, CV_32FC1, Jf ); - cvConvert( &matJ, &_Jf ); - cvTranspose( &_Jf, jacobian ); - } - } - else if( jacobian->rows == matJ.rows ) - cvCopy( &matJ, jacobian ); - else - cvTranspose( &matJ, jacobian ); - } - - return 1; -} - - -void -cvTsConvertHomogeneous( const CvMat* src, CvMat* dst ) -{ - CvMat* src_buf = 0; - CvMat* dst_buf = 0; - CvMat* dst0 = dst; - int i, count, sdims, ddims; - int sstep1, sstep2, dstep1, dstep2; - double *s, *d; - - if( CV_MAT_DEPTH(src->type) != CV_64F ) - { - src_buf = cvCreateMat( src->rows, src->cols, CV_MAKETYPE(CV_64F, CV_MAT_CN(src->type)) ); - cvTsConvert( src, src_buf ); - src = src_buf; - } - - if( CV_MAT_DEPTH(dst->type) != CV_64F ) - { - dst_buf = cvCreateMat( dst->rows, dst->cols, CV_MAKETYPE(CV_64F, CV_MAT_CN(dst->type)) ); - dst = dst_buf; - } - - if( src->rows > src->cols ) - { - count = src->rows; - sdims = CV_MAT_CN(src->type)*src->cols; - sstep1 = src->step/sizeof(double); - sstep2 = 1; - } - else - { - count = src->cols; - sdims = CV_MAT_CN(src->type)*src->rows; - if( src->rows == 1 ) - { - sstep1 = sdims; - sstep2 = 1; - } - else - { - sstep1 = 1; - sstep2 = src->step/sizeof(double); - } - } - - if( dst->rows > dst->cols ) - { - assert( count == dst->rows ); - ddims = CV_MAT_CN(dst->type)*dst->cols; - dstep1 = dst->step/sizeof(double); - dstep2 = 1; - } - else - { - assert( count == dst->cols ); - ddims = CV_MAT_CN(dst->type)*dst->rows; - if( dst->rows == 1 ) - { - dstep1 = ddims; - dstep2 = 1; - } - else - { - dstep1 = 1; - dstep2 = dst->step/sizeof(double); - } - } - - s = src->data.db; - d = dst->data.db; - - if( sdims <= ddims ) - { - int wstep = dstep2*(ddims - 1); - - for( i = 0; i < count; i++, s += sstep1, d += dstep1 ) - { - double x = s[0]; - double y = s[sstep2]; - - d[wstep] = 1; - d[0] = x; - d[dstep2] = y; - - if( sdims >= 3 ) - { - d[dstep2*2] = s[sstep2*2]; - if( sdims == 4 ) - d[dstep2*3] = s[sstep2*3]; - } - } - } - else - { - int wstep = sstep2*(sdims - 1); - - for( i = 0; i < count; i++, s += sstep1, d += dstep1 ) - { - double w = s[wstep]; - double x = s[0]; - double y = s[sstep2]; - - w = w ? 1./w : 1; - - d[0] = x*w; - d[dstep2] = y*w; - - if( ddims == 3 ) - d[dstep2*2] = s[sstep2*2]*w; - } - } - - if( dst != dst0 ) - cvTsConvert( dst, dst0 ); - - cvReleaseMat( &src_buf ); - cvReleaseMat( &dst_buf ); -} - - -void -cvTsProjectPoints( const CvMat* _3d, const CvMat* Rt, const CvMat* A, - CvMat* _2d, CvRNG* rng, double sigma ) -{ - double p[12]; - CvMat P = cvMat( 3, 4, CV_64F, p ); - - int i, count = _3d->cols; - - CvMat* temp; - CvMat* noise = 0; - - cvMatMul( A, Rt, &P ); - - if( rng ) - { - if( sigma == 0 ) - rng = 0; - else - { - noise = cvCreateMat( 1, _3d->cols, CV_64FC2 ); - cvRandArr( rng, noise, CV_RAND_NORMAL, cvScalarAll(0), cvScalarAll(sigma) ); - } - } - - temp = cvCreateMat( 1, count, CV_64FC3 ); - - for( i = 0; i < count; i++ ) - { - const double* M = _3d->data.db + i*3; - double* m = temp->data.db + i*3; - double X = M[0], Y = M[1], Z = M[2]; - double u = p[0]*X + p[1]*Y + p[2]*Z + p[3]; - double v = p[4]*X + p[5]*Y + p[6]*Z + p[7]; - double s = p[8]*X + p[9]*Y + p[10]*Z + p[11]; - - if( noise ) - { - u += noise->data.db[i*2]*s; - v += noise->data.db[i*2+1]*s; - } - - m[0] = u; - m[1] = v; - m[2] = s; - } - - cvTsConvertHomogeneous( temp, _2d ); - cvReleaseMat( &noise ); - cvReleaseMat( &temp ); -} - - -/********************************** Rodrigues transform ********************************/ - -class CV_RodriguesTest : public CvArrTest -{ -public: - CV_RodriguesTest(); - -protected: - int read_params( CvFileStorage* fs ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - bool calc_jacobians; - bool test_cpp; -}; - - -CV_RodriguesTest::CV_RodriguesTest() - : CvArrTest( "_3d-rodrigues", "cvRodrigues2", "" ) -{ - test_array[INPUT].push(NULL); // rotation vector - test_array[OUTPUT].push(NULL); // rotation matrix - test_array[OUTPUT].push(NULL); // jacobian (J) - test_array[OUTPUT].push(NULL); // rotation vector (backward transform result) - test_array[OUTPUT].push(NULL); // inverse transform jacobian (J1) - test_array[OUTPUT].push(NULL); // J*J1 (or J1*J) == I(3x3) - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - element_wise_relative_error = false; - calc_jacobians = false; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; - test_cpp = false; -} - - -int CV_RodriguesTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_RodriguesTest::get_test_array_types_and_sizes( - int /*test_case_idx*/, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - int i, code; - - code = cvTsRandInt(rng) % 3; - types[INPUT][0] = CV_MAKETYPE(depth, 1); - - if( code == 0 ) - { - sizes[INPUT][0] = cvSize(1,1); - types[INPUT][0] = CV_MAKETYPE(depth, 3); - } - else if( code == 1 ) - sizes[INPUT][0] = cvSize(3,1); - else - sizes[INPUT][0] = cvSize(1,3); - - sizes[OUTPUT][0] = cvSize(3, 3); - types[OUTPUT][0] = CV_MAKETYPE(depth, 1); - - types[OUTPUT][1] = CV_MAKETYPE(depth, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][1] = cvSize(3,9); - else - sizes[OUTPUT][1] = cvSize(9,3); - - types[OUTPUT][2] = types[INPUT][0]; - sizes[OUTPUT][2] = sizes[INPUT][0]; - - types[OUTPUT][3] = types[OUTPUT][1]; - sizes[OUTPUT][3] = cvSize(sizes[OUTPUT][1].height, sizes[OUTPUT][1].width); - - types[OUTPUT][4] = types[OUTPUT][1]; - sizes[OUTPUT][4] = cvSize(3,3); - - calc_jacobians = cvTsRandInt(rng) % 3 != 0; - if( !calc_jacobians ) - sizes[OUTPUT][1] = sizes[OUTPUT][3] = sizes[OUTPUT][4] = cvSize(0,0); - - for( i = 0; i < 5; i++ ) - { - types[REF_OUTPUT][i] = types[OUTPUT][i]; - sizes[REF_OUTPUT][i] = sizes[OUTPUT][i]; - } - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -double CV_RodriguesTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int j ) -{ - return j == 4 ? 1e-2 : 1e-2; -} - - -void CV_RodriguesTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i == INPUT && j == 0 ) - { - double r[3], theta0, theta1, f; - CvMat _r = cvMat( arr->rows, arr->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(arr->type)), r ); - CvRNG* rng = ts->get_rng(); - - r[0] = cvTsRandReal(rng)*CV_PI*2; - r[1] = cvTsRandReal(rng)*CV_PI*2; - r[2] = cvTsRandReal(rng)*CV_PI*2; - - theta0 = sqrt(r[0]*r[0] + r[1]*r[1] + r[2]*r[2]); - theta1 = fmod(theta0, CV_PI*2); - - if( theta1 > CV_PI ) - theta1 = -(CV_PI*2 - theta1); - - f = theta1/(theta0 ? theta0 : 1); - r[0] *= f; - r[1] *= f; - r[2] *= f; - - cvTsConvert( &_r, arr ); - } - else - CvArrTest::fill_array( test_case_idx, i, j, arr ); -} - - -int CV_RodriguesTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - return code; -} - - -void CV_RodriguesTest::run_func() -{ - CvMat *v2m_jac = 0, *m2v_jac = 0; - - if( calc_jacobians ) - { - v2m_jac = &test_mat[OUTPUT][1]; - m2v_jac = &test_mat[OUTPUT][3]; - } - - if( !test_cpp ) - { - cvRodrigues2( &test_mat[INPUT][0], &test_mat[OUTPUT][0], v2m_jac ); - cvRodrigues2( &test_mat[OUTPUT][0], &test_mat[OUTPUT][2], m2v_jac ); - } - else - { - cv::Mat v(&test_mat[INPUT][0]), M(&test_mat[OUTPUT][0]), v2(&test_mat[OUTPUT][2]); - cv::Mat M0 = M, v2_0 = v2; - if( !calc_jacobians ) - { - cv::Rodrigues(v, M); - cv::Rodrigues(M, v2); - } - else - { - cv::Mat J1(&test_mat[OUTPUT][1]), J2(&test_mat[OUTPUT][3]); - cv::Mat J1_0 = J1, J2_0 = J2; - cv::Rodrigues(v, M, J1); - cv::Rodrigues(M, v2, J2); - if( J1.data != J1_0.data ) - { - if( J1.size() != J1_0.size() ) - J1 = J1.t(); - J1.convertTo(J1_0, J1_0.type()); - } - if( J2.data != J2_0.data ) - { - if( J2.size() != J2_0.size() ) - J2 = J2.t(); - J2.convertTo(J2_0, J2_0.type()); - } - } - if( M.data != M0.data ) - M.reshape(M0.channels(), M0.rows).convertTo(M0, M0.type()); - if( v2.data != v2_0.data ) - v2.reshape(v2_0.channels(), v2_0.rows).convertTo(v2_0, v2_0.type()); - } -} - - -void CV_RodriguesTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - const CvMat* vec = &test_mat[INPUT][0]; - CvMat* m = &test_mat[REF_OUTPUT][0]; - CvMat* vec2 = &test_mat[REF_OUTPUT][2]; - CvMat* v2m_jac = 0, *m2v_jac = 0; - double theta0, theta1; - - if( calc_jacobians ) - { - v2m_jac = &test_mat[REF_OUTPUT][1]; - m2v_jac = &test_mat[REF_OUTPUT][3]; - } - - - cvTsRodrigues( vec, m, v2m_jac ); - cvTsRodrigues( m, vec2, m2v_jac ); - cvTsCopy( vec, vec2 ); - - theta0 = cvNorm( vec2, 0, CV_L2 ); - theta1 = fmod( theta0, CV_PI*2 ); - - if( theta1 > CV_PI ) - theta1 = -(CV_PI*2 - theta1); - cvScale( vec2, vec2, theta1/(theta0 ? theta0 : 1) ); - - if( calc_jacobians ) - { - //cvInvert( v2m_jac, m2v_jac, CV_SVD ); - double nrm = cvNorm(&test_mat[REF_OUTPUT][3],0,CV_C); - if( FLT_EPSILON < nrm && nrm < 1000 ) - { - cvTsGEMM( &test_mat[OUTPUT][1], &test_mat[OUTPUT][3], - 1, 0, 0, &test_mat[OUTPUT][4], - v2m_jac->rows == 3 ? 0 : CV_GEMM_A_T + CV_GEMM_B_T ); - } - else - { - cvTsSetIdentity( &test_mat[OUTPUT][4], cvScalarAll(1.) ); - cvTsCopy( &test_mat[REF_OUTPUT][2], &test_mat[OUTPUT][2] ); - } - cvTsSetIdentity( &test_mat[REF_OUTPUT][4], cvScalarAll(1.) ); - } -} - - -CV_RodriguesTest rodrigues_test; - - -/********************************** fundamental matrix *********************************/ - -class CV_FundamentalMatTest : public CvArrTest -{ -public: - CV_FundamentalMatTest(); - -protected: - int read_params( CvFileStorage* fs ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int method; - int img_size; - int cube_size; - int dims; - int f_result; - double min_f, max_f; - double sigma; - bool test_cpp; -}; - - -CV_FundamentalMatTest::CV_FundamentalMatTest() - : CvArrTest( "_3d-fundam", "cvFindFundamentalMatrix", "" ) -{ - // input arrays: - // 0, 1 - arrays of 2d points that are passed to %func%. - // Can have different data type, layout, be stored in homogeneous coordinates or not. - // 2 - array of 3d points that are projected to both view planes - // 3 - [R|t] matrix for the second view plane (for the first one it is [I|0] - // 4, 5 - intrinsic matrices - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - element_wise_relative_error = false; - - method = 0; - img_size = 10; - cube_size = 10; - min_f = 1; - max_f = 3; - sigma = 0;//0.1; - f_result = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; - test_cpp = false; -} - - -int CV_FundamentalMatTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_FundamentalMatTest::get_test_array_types_and_sizes( int /*test_case_idx*/, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int pt_depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - double pt_count_exp = cvTsRandReal(rng)*6 + 1; - int pt_count = cvRound(exp(pt_count_exp)); - - dims = cvTsRandInt(rng) % 2 + 2; - method = 1 << (cvTsRandInt(rng) % 4); - - if( method == CV_FM_7POINT ) - pt_count = 7; - else - { - pt_count = MAX( pt_count, 8 + (method == CV_FM_8POINT) ); - if( pt_count >= 8 && cvTsRandInt(rng) % 2 ) - method |= CV_FM_8POINT; - } - - types[INPUT][0] = CV_MAKETYPE(pt_depth, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, dims); - else - { - sizes[INPUT][0] = cvSize(dims, pt_count); - if( cvTsRandInt(rng) % 2 ) - { - types[INPUT][0] = CV_MAKETYPE(pt_depth, dims); - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, 1); - else - sizes[INPUT][0] = cvSize(1, pt_count); - } - } - - sizes[INPUT][1] = sizes[INPUT][0]; - types[INPUT][1] = types[INPUT][0]; - - sizes[INPUT][2] = cvSize(pt_count, 1 ); - types[INPUT][2] = CV_64FC3; - - sizes[INPUT][3] = cvSize(4,3); - types[INPUT][3] = CV_64FC1; - - sizes[INPUT][4] = sizes[INPUT][5] = cvSize(3,3); - types[INPUT][4] = types[INPUT][5] = CV_MAKETYPE(CV_64F, 1); - - sizes[TEMP][0] = cvSize(3,3); - types[TEMP][0] = CV_64FC1; - sizes[TEMP][1] = cvSize(pt_count,1); - types[TEMP][1] = CV_8UC1; - - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(3,1); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = cvSize(pt_count,1); - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_8UC1; - - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -double CV_FundamentalMatTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 1e-2; -} - - -void CV_FundamentalMatTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - double t[12]; - CvMat T; - double* p = arr->data.db; - CvRNG* rng = ts->get_rng(); - - if( i != INPUT ) - { - CvArrTest::fill_array( test_case_idx, i, j, arr ); - return; - } - - switch( j ) - { - case 0: - case 1: - return; // fill them later in prepare_test_case - case 2: - for( i = 0; i < arr->cols*3; i += 3 ) - { - p[i] = cvTsRandReal(rng)*cube_size; - p[i+1] = cvTsRandReal(rng)*cube_size; - p[i+2] = cvTsRandReal(rng)*cube_size + cube_size; - } - break; - case 3: - { - double r[3]; - CvMat rot_vec = cvMat( 3, 1, CV_64F, r ); - CvMat rot_mat = cvMat( 3, 3, CV_64F ); - r[0] = cvTsRandReal(rng)*CV_PI*2; - r[1] = cvTsRandReal(rng)*CV_PI*2; - r[2] = cvTsRandReal(rng)*CV_PI*2; - - cvSetData( &rot_mat, t, 4*sizeof(t[0]) ); - cvTsRodrigues( &rot_vec, &rot_mat ); - t[3] = cvTsRandReal(rng)*cube_size; - t[7] = cvTsRandReal(rng)*cube_size; - t[11] = cvTsRandReal(rng)*cube_size; - T = cvMat( 3, 4, CV_64F, t ); - cvTsConvert( &T, arr ); - } - break; - case 4: - case 5: - memset( t, 0, sizeof(t) ); - t[0] = t[4] = cvTsRandReal(rng)*(max_f - min_f) + min_f; - t[2] = (img_size*0.5 + cvTsRandReal(rng)*4. - 2.)*t[0]; - t[5] = (img_size*0.5 + cvTsRandReal(rng)*4. - 2.)*t[4]; - t[8] = 1.; - T = cvMat( 3, 3, CV_64F, t ); - cvTsConvert( &T, arr ); - break; - } -} - - -int CV_FundamentalMatTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - const CvMat* _3d = &test_mat[INPUT][2]; - CvRNG* rng = ts->get_rng(); - double Idata[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 }; - CvMat I = cvMat( 3, 4, CV_64F, Idata ); - int k; - - for( k = 0; k < 2; k++ ) - { - const CvMat* Rt = k == 0 ? &I : &test_mat[INPUT][3]; - const CvMat* A = &test_mat[INPUT][k == 0 ? 4 : 5]; - CvMat* _2d = &test_mat[INPUT][k]; - - cvTsProjectPoints( _3d, Rt, A, _2d, rng, sigma ); - } - } - - return code; -} - - -void CV_FundamentalMatTest::run_func() -{ - //if(!test_cpp) - { - f_result = cvFindFundamentalMat( &test_mat[INPUT][0], &test_mat[INPUT][1], - &test_mat[TEMP][0], method, MAX(sigma*3, 0.01), 0, &test_mat[TEMP][1] ); - } - /*else - { - cv::findFundamentalMat(const Mat& points1, const Mat& points2, - vector& mask, int method=FM_RANSAC, - double param1=3., double param2=0.99 ); - - CV_EXPORTS Mat findFundamentalMat( const Mat& points1, const Mat& points2, - int method=FM_RANSAC, - double param1=3., double param2=0.99 ); - }*/ - -} - - -void CV_FundamentalMatTest::prepare_to_validation( int test_case_idx ) -{ - const CvMat* Rt = &test_mat[INPUT][3]; - const CvMat* A1 = &test_mat[INPUT][4]; - const CvMat* A2 = &test_mat[INPUT][5]; - double f0[9]; - CvMat F0 = cvMat( 3, 3, CV_64FC1, f0 ); - - double _invA1[9], _invA2[9], temp[9]; - CvMat invA1 = cvMat( 3, 3, CV_64F, _invA1 ); - CvMat invA2 = cvMat( 3, 3, CV_64F, _invA2 ); - CvMat R = cvMat( 3, 3, CV_64F ); - CvMat T = cvMat( 3, 3, CV_64F, temp ); - - cvSetData( &R, Rt->data.db, Rt->step ); // R = Rt(:,1:3) - - // F = (A2^-T)*[t]_x*R*(A1^-1) - cvInvert( A1, &invA1, CV_SVD ); - cvInvert( A2, &invA2, CV_SVD ); - - { - double tx = ((double*)(Rt->data.ptr))[3]; - double ty = ((double*)(Rt->data.ptr + Rt->step))[3]; - double tz = ((double*)(Rt->data.ptr + Rt->step*2))[3]; - - double _t_x[] = { 0, -tz, ty, tz, 0, -tx, -ty, tx, 0 }; - CvMat t_x = cvMat( 3, 3, CV_64F, _t_x ); - - cvGEMM( &invA2, &t_x, 1, 0, 0, &T, CV_GEMM_A_T ); - cvMatMul( &R, &invA1, &invA2 ); - cvMatMul( &T, &invA2, &F0 ); - cvScale( &F0, &F0, f0[8] ); - } - - double f[9]; - CvMat F = cvMat(3, 3, CV_64F, f); - uchar* status = test_mat[TEMP][1].data.ptr; - double err_level = get_success_error_level( test_case_idx, OUTPUT, 1 ); - uchar* mtfm1 = test_mat[REF_OUTPUT][1].data.ptr; - uchar* mtfm2 = test_mat[OUTPUT][1].data.ptr; - double* f_prop1 = test_mat[REF_OUTPUT][0].data.db; - double* f_prop2 = test_mat[OUTPUT][0].data.db; - - int i, pt_count = test_mat[INPUT][2].cols; - CvMat* p1 = cvCreateMat( 1, pt_count, CV_64FC2 ); - CvMat* p2 = cvCreateMat( 1, pt_count, CV_64FC2 ); - - cvTsConvertHomogeneous( &test_mat[INPUT][0], p1 ); - cvTsConvertHomogeneous( &test_mat[INPUT][1], p2 ); - - cvTsConvert( &test_mat[TEMP][0], &F ); - - if( method <= CV_FM_8POINT ) - memset( status, 1, pt_count ); - - for( i = 0; i < pt_count; i++ ) - { - double x1 = p1->data.db[i*2]; - double y1 = p1->data.db[i*2+1]; - double x2 = p2->data.db[i*2]; - double y2 = p2->data.db[i*2+1]; - double n1 = 1./sqrt(x1*x1 + y1*y1 + 1); - double n2 = 1./sqrt(x2*x2 + y2*y2 + 1); - double t0 = fabs(f0[0]*x2*x1 + f0[1]*x2*y1 + f0[2]*x2 + - f0[3]*y2*x1 + f0[4]*y2*y1 + f0[5]*y2 + - f0[6]*x1 + f0[7]*y1 + f0[8])*n1*n2; - double t = fabs(f[0]*x2*x1 + f[1]*x2*y1 + f[2]*x2 + - f[3]*y2*x1 + f[4]*y2*y1 + f[5]*y2 + - f[6]*x1 + f[7]*y1 + f[8])*n1*n2; - mtfm1[i] = 1; - mtfm2[i] = !status[i] || t0 > err_level || t < err_level; - } - - f_prop1[0] = 1; - f_prop1[1] = 1; - f_prop1[2] = 0; - - f_prop2[0] = f_result != 0; - f_prop2[1] = f[8]; - f_prop2[2] = cvDet( &F ); - - cvReleaseMat( &p1 ); - cvReleaseMat( &p2 ); -} - - -CV_FundamentalMatTest fmatrix_test; - - -/********************************** convert homogeneous *********************************/ - -class CV_ConvertHomogeneousTest : public CvArrTest -{ -public: - CV_ConvertHomogeneousTest(); - -protected: - int read_params( CvFileStorage* fs ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int dims1, dims2; - int pt_count; -}; - - -CV_ConvertHomogeneousTest::CV_ConvertHomogeneousTest() - : CvArrTest( "_3d-cvt-homogen", "cvConvertPointsHomogeniuos", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - element_wise_relative_error = false; - - pt_count = dims1 = dims2 = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_ConvertHomogeneousTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_ConvertHomogeneousTest::get_test_array_types_and_sizes( int /*test_case_idx*/, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int pt_depth1 = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - int pt_depth2 = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - double pt_count_exp = cvTsRandReal(rng)*6 + 1; - int t; - - pt_count = cvRound(exp(pt_count_exp)); - pt_count = MAX( pt_count, 5 ); - - dims1 = 2 + (cvTsRandInt(rng) % 3); - dims2 = 2 + (cvTsRandInt(rng) % 3); - - if( dims1 == dims2 + 2 ) - dims1--; - else if( dims1 == dims2 - 2 ) - dims1++; - - if( cvTsRandInt(rng) % 2 ) - CV_SWAP( dims1, dims2, t ); - - types[INPUT][0] = CV_MAKETYPE(pt_depth1, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, dims1); - else - { - sizes[INPUT][0] = cvSize(dims1, pt_count); - if( cvTsRandInt(rng) % 2 ) - { - types[INPUT][0] = CV_MAKETYPE(pt_depth1, dims1); - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, 1); - else - sizes[INPUT][0] = cvSize(1, pt_count); - } - } - - types[OUTPUT][0] = CV_MAKETYPE(pt_depth2, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][0] = cvSize(pt_count, dims2); - else - { - sizes[OUTPUT][0] = cvSize(dims2, pt_count); - if( cvTsRandInt(rng) % 2 ) - { - types[OUTPUT][0] = CV_MAKETYPE(pt_depth2, dims2); - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][0] = cvSize(pt_count, 1); - else - sizes[OUTPUT][0] = cvSize(1, pt_count); - } - } - - types[REF_OUTPUT][0] = types[OUTPUT][0]; - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; -} - - -double CV_ConvertHomogeneousTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 1e-5; -} - - -void CV_ConvertHomogeneousTest::fill_array( int /*test_case_idx*/, int /*i*/, int /*j*/, CvMat* arr ) -{ - CvMat* temp = cvCreateMat( 1, pt_count, CV_MAKETYPE(CV_64FC1,dims1) ); - CvRNG* rng = ts->get_rng(); - CvScalar low = cvScalarAll(0), high = cvScalarAll(10); - - if( dims1 > dims2 ) - low.val[dims1-1] = 1.; - - cvRandArr( rng, temp, CV_RAND_UNI, low, high ); - cvTsConvertHomogeneous( temp, arr ); - cvReleaseMat( &temp ); -} - - -void CV_ConvertHomogeneousTest::run_func() -{ - cvConvertPointsHomogeneous( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ); -} - - -void CV_ConvertHomogeneousTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsConvertHomogeneous( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0] ); -} - - -CV_ConvertHomogeneousTest cvt_homogen_test; - - -/************************** compute corresponding epipolar lines ************************/ - -class CV_ComputeEpilinesTest : public CvArrTest -{ -public: - CV_ComputeEpilinesTest(); - -protected: - int read_params( CvFileStorage* fs ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int which_image; - int dims; - int pt_count; -}; - - -CV_ComputeEpilinesTest::CV_ComputeEpilinesTest() - : CvArrTest( "_3d-epilines", "cvComputeCorrespondingEpilines", "" ) -{ - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - element_wise_relative_error = false; - - pt_count = dims = which_image = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_ComputeEpilinesTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_ComputeEpilinesTest::get_test_array_types_and_sizes( int /*test_case_idx*/, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int fm_depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - int pt_depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - int ln_depth = cvTsRandInt(rng) % 2 == 0 ? CV_32F : CV_64F; - double pt_count_exp = cvTsRandReal(rng)*6 + 1; - - which_image = 1 + (cvTsRandInt(rng) % 2); - - pt_count = cvRound(exp(pt_count_exp)); - pt_count = MAX( pt_count, 5 ); - - dims = 2 + (cvTsRandInt(rng) % 2); - - types[INPUT][0] = CV_MAKETYPE(pt_depth, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, dims); - else - { - sizes[INPUT][0] = cvSize(dims, pt_count); - if( cvTsRandInt(rng) % 2 ) - { - types[INPUT][0] = CV_MAKETYPE(pt_depth, dims); - if( cvTsRandInt(rng) % 2 ) - sizes[INPUT][0] = cvSize(pt_count, 1); - else - sizes[INPUT][0] = cvSize(1, pt_count); - } - } - - types[INPUT][1] = CV_MAKETYPE(fm_depth, 1); - sizes[INPUT][1] = cvSize(3, 3); - - types[OUTPUT][0] = CV_MAKETYPE(ln_depth, 1); - - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][0] = cvSize(pt_count, 3); - else - { - sizes[OUTPUT][0] = cvSize(3, pt_count); - if( cvTsRandInt(rng) % 2 ) - { - types[OUTPUT][0] = CV_MAKETYPE(ln_depth, 3); - if( cvTsRandInt(rng) % 2 ) - sizes[OUTPUT][0] = cvSize(pt_count, 1); - else - sizes[OUTPUT][0] = cvSize(1, pt_count); - } - } - - types[REF_OUTPUT][0] = types[OUTPUT][0]; - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; -} - - -double CV_ComputeEpilinesTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 1e-5; -} - - -void CV_ComputeEpilinesTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - CvRNG* rng = ts->get_rng(); - - if( i == INPUT && j == 0 ) - { - CvMat* temp = cvCreateMat( 1, pt_count, CV_MAKETYPE(CV_64FC1,dims) ); - cvRandArr( rng, temp, CV_RAND_UNI, cvScalar(0,0,1), cvScalarAll(10) ); - cvTsConvertHomogeneous( temp, arr ); - cvReleaseMat( &temp ); - } - else if( i == INPUT && j == 1 ) - cvRandArr( rng, arr, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(10) ); - else - CvArrTest::fill_array( test_case_idx, i, j, arr ); -} - - -void CV_ComputeEpilinesTest::run_func() -{ - cvComputeCorrespondEpilines( &test_mat[INPUT][0], which_image, - &test_mat[INPUT][1], &test_mat[OUTPUT][0] ); -} - - -void CV_ComputeEpilinesTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* pt = cvCreateMat( 1, pt_count, CV_MAKETYPE(CV_64F, 3) ); - CvMat* lines = cvCreateMat( 1, pt_count, CV_MAKETYPE(CV_64F, 3) ); - double f[9]; - CvMat F = cvMat( 3, 3, CV_64F, f ); - int i; - - cvTsConvertHomogeneous( &test_mat[INPUT][0], pt ); - cvTsConvert( &test_mat[INPUT][1], &F ); - if( which_image == 2 ) - cvTranspose( &F, &F ); - - for( i = 0; i < pt_count; i++ ) - { - double* p = pt->data.db + i*3; - double* l = lines->data.db + i*3; - double t0 = f[0]*p[0] + f[1]*p[1] + f[2]*p[2]; - double t1 = f[3]*p[0] + f[4]*p[1] + f[5]*p[2]; - double t2 = f[6]*p[0] + f[7]*p[1] + f[8]*p[2]; - double d = sqrt(t0*t0 + t1*t1); - d = d ? 1./d : 1.; - l[0] = t0*d; l[1] = t1*d; l[2] = t2*d; - } - - cvTsConvertHomogeneous( lines, &test_mat[REF_OUTPUT][0] ); - cvReleaseMat( &pt ); - cvReleaseMat( &lines ); -} - - -CV_ComputeEpilinesTest epilines_test; - - -/* End of file. */ diff --git a/tests/cv/src/ahistograms.cpp b/tests/cv/src/ahistograms.cpp deleted file mode 100644 index 0daeb5a..0000000 --- a/tests/cv/src/ahistograms.cpp +++ /dev/null @@ -1,1883 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_BaseHistTest : public CvTest -{ -public: - enum { MAX_HIST = 12 }; - - CV_BaseHistTest( const char* test_name, const char* test_funcs ); - ~CV_BaseHistTest(); - void clear(); - int write_default_params(CvFileStorage* fs); - -protected: - int read_params( CvFileStorage* fs ); - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - virtual void init_hist( int test_case_idx, int i ); - - virtual void get_hist_params( int test_case_idx ); - virtual float** get_hist_ranges( int test_case_idx ); - - int max_log_size; - int max_cdims; - int cdims; - int dims[CV_MAX_DIM]; - int dims_sum[CV_MAX_DIM+1]; - int total_size; - int hist_type; - int hist_count; - int uniform; - int gen_random_hist; - double gen_hist_max_val, gen_hist_sparse_nz_ratio; - - int init_ranges; - int img_type; - int img_max_log_size; - double low, high, range_delta; - CvSize img_size; - - CvHistogram* hist[MAX_HIST]; - float* _ranges; - float* ranges[CV_MAX_DIM]; - bool test_cpp; -}; - - -CV_BaseHistTest::CV_BaseHistTest( const char* test_name, const char* test_funcs ): - CvTest( test_name, test_funcs ) -{ - int i; - - test_case_count = 100; - max_log_size = 20; - img_max_log_size = 8; - max_cdims = 6; - _ranges = 0; - hist_count = 1; - init_ranges = 0; - gen_random_hist = 0; - gen_hist_max_val = 100; - - for( i = 0; i < MAX_HIST; i++ ) - hist[i] = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - test_cpp = false; -} - - -CV_BaseHistTest::~CV_BaseHistTest() -{ - clear(); -} - - -void CV_BaseHistTest::clear() -{ - int i; - CvTest::clear(); - for( i = 0; i < MAX_HIST; i++ ) - cvReleaseHist( &hist[i] ); - delete[] _ranges; - _ranges = 0; -} - - -int CV_BaseHistTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "max_log_size", max_log_size ); - write_param( fs, "max_log_array_size", img_max_log_size ); - write_param( fs, "max_dims", max_cdims ); - } - return 0; -} - - -int CV_BaseHistTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "struct_count" ), test_case_count ); - max_log_size = cvReadInt( find_param( fs, "max_log_size" ), max_log_size ); - max_log_size = cvTsClipInt( max_log_size, 1, 20 ); - img_max_log_size = cvReadInt( find_param( fs, "max_log_array_size" ), img_max_log_size ); - img_max_log_size = cvTsClipInt( img_max_log_size, 1, 9 ); - - max_cdims = cvReadInt( find_param( fs, "max_cdims" ), max_cdims ); - max_cdims = cvTsClipInt( max_cdims, 1, 6 ); - - return 0; -} - - -void CV_BaseHistTest::get_hist_params( int /*test_case_idx*/ ) -{ - CvRNG* rng = ts->get_rng(); - int i, max_dim_size, max_ni_dim_size = 31; - double hist_size; - - cdims = cvTsRandInt(rng) % max_cdims + 1; - hist_size = exp(cvTsRandReal(rng)*max_log_size*CV_LOG2); - max_dim_size = cvRound(pow(hist_size,1./cdims)); - total_size = 1; - uniform = cvTsRandInt(rng) % 2; - hist_type = cvTsRandInt(rng) % 2 ? CV_HIST_SPARSE : CV_HIST_ARRAY; - - for( i = 0; i < cdims; i++ ) - { - dims[i] = cvTsRandInt(rng) % (max_dim_size + 2) + 2; - if( !uniform ) - dims[i] = MIN(dims[i], max_ni_dim_size); - total_size *= dims[i]; - } - - img_type = cvTsRandInt(rng) % 2 ? CV_32F : CV_8U; - img_size.width = cvRound( exp(cvRandReal(rng) * img_max_log_size*CV_LOG2) ); - img_size.height = cvRound( exp(cvRandReal(rng) * img_max_log_size*CV_LOG2) ); - - low = cvTsMinVal(img_type); - high = cvTsMaxVal(img_type); - - range_delta = (cvTsRandInt(rng) % 2)*(high-low)*0.05; -} - - -float** CV_BaseHistTest::get_hist_ranges( int /*test_case_idx*/ ) -{ - double _low = low + range_delta, _high = high - range_delta; - - if( init_ranges ) - { - int i; - dims_sum[0] = 0; - for( i = 0; i < cdims; i++ ) - dims_sum[i+1] = dims_sum[i] + dims[i] + 1; - - if( uniform ) - { - _ranges = new float[cdims*2]; - for( i = cdims-1; i >= 0; i-- ) - { - _ranges[i*2] = (float)_low; - _ranges[i*2+1] = (float)_high; - ranges[i] = _ranges + i*2; - } - } - else - { - _ranges = new float[dims_sum[cdims]]; - - for( i = 0; i < cdims; i++ ) - { - int j, n = dims[i], ofs = dims_sum[i]; - // generate logarithmic scale - double delta, q, val; - for( j = 0; j < 10; j++ ) - { - q = 1. + (j+1)*0.1; - if( (pow(q,(double)n)-1)/(q-1.) >= _high-_low ) - break; - } - - if( j == 0 ) - { - delta = (_high-_low)/n; - q = 1.; - } - else - { - q = 1 + j*0.1; - delta = cvFloor((_high-_low)*(q-1)/(pow(q,(double)n) - 1)); - delta = MAX(delta, 1.); - } - val = _low; - - for( j = 0; j <= n; j++ ) - { - _ranges[j+ofs] = (float)MIN(val,_high); - val += delta; - delta *= q; - } - ranges[i] = _ranges + ofs; - } - } - return ranges; - } - - return 0; -} - - -void CV_BaseHistTest::init_hist( int /*test_case_idx*/, int hist_i ) -{ - if( gen_random_hist ) - { - CvRNG* rng = ts->get_rng(); - CvArr* h = hist[hist_i]->bins; - - if( hist_type == CV_HIST_ARRAY ) - { - cvRandArr( rng, h, CV_RAND_UNI, - cvScalarAll(0), cvScalarAll(gen_hist_max_val) ); - } - else - { - int i, j, total_size = 1, nz_count; - int idx[CV_MAX_DIM]; - for( i = 0; i < cdims; i++ ) - total_size *= dims[i]; - - nz_count = cvTsRandInt(rng) % MAX( total_size/4, 100 ); - nz_count = MIN( nz_count, total_size ); - - // a zero number of non-zero elements should be allowed - for( i = 0; i < nz_count; i++ ) - { - for( j = 0; j < cdims; j++ ) - idx[j] = cvTsRandInt(rng) % dims[j]; - cvSetRealND( h, idx, cvTsRandReal(rng)*gen_hist_max_val ); - } - } - } -} - - -int CV_BaseHistTest::prepare_test_case( int test_case_idx ) -{ - int i; - float** r; - - clear(); - - CvTest::prepare_test_case( test_case_idx ); - get_hist_params( test_case_idx ); - r = get_hist_ranges( test_case_idx ); - - for( i = 0; i < hist_count; i++ ) - { - hist[i] = cvCreateHist( cdims, dims, hist_type, r, uniform ); - init_hist( test_case_idx, i ); - } - test_cpp = (cvTsRandInt(ts->get_rng()) % 2) != 0; - - return 1; -} - - -void CV_BaseHistTest::run_func(void) -{ -} - - -int CV_BaseHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - return 0; -} - - -CV_BaseHistTest hist_basetest( "hist", "" ); - - - -////////////// testing operation for reading/writing individual histogram bins ////////////// - -class CV_QueryHistTest : public CV_BaseHistTest -{ -public: - CV_QueryHistTest(); - ~CV_QueryHistTest(); - void clear(); - -protected: - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void init_hist( int test_case_idx, int i ); - - CvMat* indices; - CvMat* values; - CvMat* values0; -}; - - - -CV_QueryHistTest::CV_QueryHistTest() : CV_BaseHistTest( "hist-query", - "cvGetReal1D, cvGetReal2D, cvGetReal3D, cvGetRealND, " - "cvPtr1D, cvPtr2D, cvPtr3D, cvPtrND, " - "cvSetReal1D, cvSetReal2D, cvSetReal3D, cvSetRealND" ) -{ - hist_count = 1; - indices = 0; - values = 0; - values0 = 0; -} - - -CV_QueryHistTest::~CV_QueryHistTest() -{ - clear(); -} - - -void CV_QueryHistTest::clear() -{ - cvReleaseMat( &indices ); - cvReleaseMat( &values ); - cvReleaseMat( &values0 ); - CV_BaseHistTest::clear(); -} - - -void CV_QueryHistTest::init_hist( int /*test_case_idx*/, int i ) -{ - if( hist_type == CV_HIST_ARRAY ) - cvZero( hist[i]->bins ); -} - - -int CV_QueryHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - int i, j, iters; - float default_value = 0.f; - CvRNG* rng = ts->get_rng(); - CvMat* bit_mask = 0; - int* idx; - - iters = (cvTsRandInt(rng) % MAX(total_size/10,100)) + 1; - iters = MIN( iters, total_size*9/10 + 1 ); - - indices = cvCreateMat( 1, iters*cdims, CV_32S ); - values = cvCreateMat( 1, iters, CV_32F ); - values0 = cvCreateMat( 1, iters, CV_32F ); - idx = indices->data.i; - - //printf( "total_size = %d, cdims = %d, iters = %d\n", total_size, cdims, iters ); - - bit_mask = cvCreateMat( 1, (total_size + 7)/8, CV_8U ); - cvZero( bit_mask ); - - #define GET_BIT(n) (bit_mask->data.ptr[(n)/8] & (1 << ((n)&7))) - #define SET_BIT(n) bit_mask->data.ptr[(n)/8] |= (1 << ((n)&7)) - - // set random histogram bins' values to the linear indices of the bins - for( i = 0; i < iters; i++ ) - { - int lin_idx = 0; - for( j = 0; j < cdims; j++ ) - { - int t = cvTsRandInt(rng) % dims[j]; - idx[i*cdims + j] = t; - lin_idx = lin_idx*dims[j] + t; - } - - if( cvTsRandInt(rng) % 8 || GET_BIT(lin_idx) ) - { - values0->data.fl[i] = (float)(lin_idx+1); - SET_BIT(lin_idx); - } - else - // some histogram bins will not be initialized intentionally, - // they should be equal to the default value - values0->data.fl[i] = default_value; - } - - // do the second pass to make values0 consistent with bit_mask - for( i = 0; i < iters; i++ ) - { - int lin_idx = 0; - for( j = 0; j < cdims; j++ ) - lin_idx = lin_idx*dims[j] + idx[i*cdims + j]; - - if( GET_BIT(lin_idx) ) - values0->data.fl[i] = (float)(lin_idx+1); - } - - cvReleaseMat( &bit_mask ); - } - - return code; -} - - -void CV_QueryHistTest::run_func(void) -{ - int i, iters = values->cols; - CvArr* h = hist[0]->bins; - const int* idx = indices->data.i; - float* val = values->data.fl; - float default_value = 0.f; - - // stage 1: write bins - if( cdims == 1 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0->data.fl[i]; - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal1D( h, idx[i], v0 ); - else - *(float*)cvPtr1D( h, idx[i] ) = v0; - } - else - cvSetRealND( h, idx+i, v0 ); - } - else if( cdims == 2 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0->data.fl[i]; - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal2D( h, idx[i*2], idx[i*2+1], v0 ); - else - *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ) = v0; - } - else - cvSetRealND( h, idx+i*2, v0 ); - } - else if( cdims == 3 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0->data.fl[i]; - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2], v0 ); - else - *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ) = v0; - } - else - cvSetRealND( h, idx+i*3, v0 ); - } - else - for( i = 0; i < iters; i++ ) - { - float v0 = values0->data.fl[i]; - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - cvSetRealND( h, idx+i*cdims, v0 ); - else - *(float*)cvPtrND( h, idx+i*cdims ) = v0; - } - - // stage 2: read bins - if( cdims == 1 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr1D( h, idx[i] ); - else - val[i] = (float)cvGetReal1D( h, idx[i] ); - } - else if( cdims == 2 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ); - else - val[i] = (float)cvGetReal2D( h, idx[i*2], idx[i*2+1] ); - } - else if( cdims == 3 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ); - else - val[i] = (float)cvGetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ); - } - else - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtrND( h, idx+i*cdims ); - else - val[i] = (float)cvGetRealND( h, idx+i*cdims ); - } -} - - -int CV_QueryHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - int i, j, iters = values->cols; - - for( i = 0; i < iters; i++ ) - { - float v = values->data.fl[i], v0 = values0->data.fl[i]; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( CvTS::LOG, "The bin #%d has invalid value\n", i ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - else if( fabs(v - v0) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "The bin #%d = %g, while it should be %g\n", i, v, v0 ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - { - ts->printf( CvTS::LOG, "The bin index = (" ); - for( j = 0; j < cdims; j++ ) - ts->printf( CvTS::LOG, "%d%s", indices->data.i[i*cdims + j], - j < cdims-1 ? ", " : ")\n" ); - break; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_QueryHistTest hist_query_test; - - -////////////// cvGetMinMaxHistValue ////////////// - -class CV_MinMaxHistTest : public CV_BaseHistTest -{ -public: - CV_MinMaxHistTest(); - -protected: - void run_func(void); - void init_hist(int, int); - int validate_test_results( int test_case_idx ); - int min_idx[CV_MAX_DIM], max_idx[CV_MAX_DIM]; - float min_val, max_val; - int min_idx0[CV_MAX_DIM], max_idx0[CV_MAX_DIM]; - float min_val0, max_val0; -}; - - - -CV_MinMaxHistTest::CV_MinMaxHistTest() : - CV_BaseHistTest( "hist-minmax", "cvGetMinMaxHistValue" ) -{ - hist_count = 1; - gen_random_hist = 1; -} - - -void CV_MinMaxHistTest::init_hist(int test_case_idx, int hist_i) -{ - int i, eq = 1; - CvRNG* rng = ts->get_rng(); - CV_BaseHistTest::init_hist( test_case_idx, hist_i ); - - for(;;) - { - for( i = 0; i < cdims; i++ ) - { - min_idx0[i] = cvTsRandInt(rng) % dims[i]; - max_idx0[i] = cvTsRandInt(rng) % dims[i]; - eq &= min_idx0[i] == max_idx0[i]; - } - if( !eq || total_size == 1 ) - break; - } - - min_val0 = (float)(-cvTsRandReal(rng)*10 - FLT_EPSILON); - max_val0 = (float)(cvTsRandReal(rng)*10 + FLT_EPSILON + gen_hist_max_val); - - if( total_size == 1 ) - min_val0 = max_val0; - - cvSetRealND( hist[0]->bins, min_idx0, min_val0 ); - cvSetRealND( hist[0]->bins, max_idx0, max_val0 ); -} - - -void CV_MinMaxHistTest::run_func(void) -{ - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h((CvSparseMat*)hist[0]->bins); - double _min_val = 0, _max_val = 0; - cv::minMaxLoc(h, &_min_val, &_max_val, min_idx, max_idx ); - min_val = (float)_min_val; - max_val = (float)_max_val; - } - else - cvGetMinMaxHistValue( hist[0], &min_val, &max_val, min_idx, max_idx ); -} - - -int CV_MinMaxHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - - if( cvIsNaN(min_val) || cvIsInf(min_val) || - cvIsNaN(max_val) || cvIsInf(max_val) ) - { - ts->printf( CvTS::LOG, - "The extrema histogram bin values are invalid (min = %g, max = %g)\n", min_val, max_val ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - else if( fabs(min_val - min_val0) > FLT_EPSILON || - fabs(max_val - max_val0) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, - "The extrema histogram bin values are incorrect: (min = %g, should be = %g), (max = %g, should be = %g)\n", - min_val, min_val0, max_val, max_val0 ); - code = CvTS::FAIL_BAD_ACCURACY; - } - else - { - int i; - for( i = 0; i < cdims; i++ ) - { - if( min_idx[i] != min_idx0[i] || max_idx[i] != max_idx0[i] ) - { - ts->printf( CvTS::LOG, - "The %d-th coordinates of extrema histogram bin values are incorrect: " - "(min = %d, should be = %d), (max = %d, should be = %d)\n", - i, min_idx[i], min_idx0[i], max_idx[i], max_idx0[i] ); - code = CvTS::FAIL_BAD_ACCURACY; - } - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_MinMaxHistTest hist_minmax_test; - - - -////////////// cvNormalizeHist ////////////// - -class CV_NormHistTest : public CV_BaseHistTest -{ -public: - CV_NormHistTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - double factor; -}; - - - -CV_NormHistTest::CV_NormHistTest() : - CV_BaseHistTest( "hist-normalize", "cvNormalizeHist" ) -{ - hist_count = 1; - gen_random_hist = 1; - factor = 0; -} - - -int CV_NormHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - CvRNG* rng = ts->get_rng(); - factor = cvTsRandReal(rng)*10 + 0.1; - if( hist_type == CV_HIST_SPARSE && - ((CvSparseMat*)hist[0]->bins)->heap->active_count == 0 ) - factor = 0; - } - - return code; -} - - -void CV_NormHistTest::run_func(void) -{ - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h((CvSparseMat*)hist[0]->bins); - cv::normalize(h, h, factor, CV_L1); - cvReleaseSparseMat((CvSparseMat**)&hist[0]->bins); - hist[0]->bins = (CvSparseMat*)h; - } - else - cvNormalizeHist( hist[0], factor ); -} - - -int CV_NormHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - double sum = 0; - - if( hist_type == CV_HIST_ARRAY ) - { - int i; - const float* ptr = (float*)cvPtr1D( hist[0]->bins, 0 ); - - for( i = 0; i < total_size; i++ ) - sum += ptr[i]; - } - else - { - CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins; - CvSparseMatIterator iterator; - CvSparseNode *node; - - for( node = cvInitSparseMatIterator( sparse, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - sum += *(float*)CV_NODE_VAL(sparse,node); - } - } - - if( cvIsNaN(sum) || cvIsInf(sum) ) - { - ts->printf( CvTS::LOG, - "The normalized histogram has invalid sum =%g\n", sum ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - else if( fabs(sum - factor) > FLT_EPSILON*10*fabs(factor) ) - { - ts->printf( CvTS::LOG, - "The normalized histogram has incorrect sum =%g, while it should be =%g\n", sum, factor ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_NormHistTest hist_norm_test; - - - -////////////// cvThreshHist ////////////// - -class CV_ThreshHistTest : public CV_BaseHistTest -{ -public: - CV_ThreshHistTest(); - ~CV_ThreshHistTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvMat* indices; - CvMat* values; - int orig_nz_count; - - double threshold; -}; - - - -CV_ThreshHistTest::CV_ThreshHistTest() : - CV_BaseHistTest( "hist-threshold", "cvThreshHist" ) -{ - hist_count = 1; - gen_random_hist = 1; - threshold = 0; - indices = values = 0; -} - - -CV_ThreshHistTest::~CV_ThreshHistTest() -{ - clear(); -} - - -void CV_ThreshHistTest::clear() -{ - cvReleaseMat( &indices ); - cvReleaseMat( &values ); - CV_BaseHistTest::clear(); -} - - -int CV_ThreshHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - CvRNG* rng = ts->get_rng(); - threshold = cvTsRandReal(rng)*gen_hist_max_val; - - if( hist_type == CV_HIST_ARRAY ) - { - orig_nz_count = total_size; - - values = cvCreateMat( 1, total_size, CV_32F ); - memcpy( values->data.fl, cvPtr1D( hist[0]->bins, 0 ), total_size*sizeof(float) ); - } - else - { - CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins; - CvSparseMatIterator iterator; - CvSparseNode* node; - int i, k; - - orig_nz_count = sparse->heap->active_count; - - values = cvCreateMat( 1, orig_nz_count+1, CV_32F ); - indices = cvCreateMat( 1, (orig_nz_count+1)*cdims, CV_32S ); - - for( node = cvInitSparseMatIterator( sparse, &iterator ), i = 0; - node != 0; node = cvGetNextSparseNode( &iterator ), i++ ) - { - const int* idx = CV_NODE_IDX(sparse,node); - - OPENCV_ASSERT( i < orig_nz_count, "CV_ThreshHistTest::prepare_test_case", "Buffer overflow" ); - - values->data.fl[i] = *(float*)CV_NODE_VAL(sparse,node); - for( k = 0; k < cdims; k++ ) - indices->data.i[i*cdims + k] = idx[k]; - } - - OPENCV_ASSERT( i == orig_nz_count, "Unmatched buffer size", - "CV_ThreshHistTest::prepare_test_case" ); - } - } - - return code; -} - - -void CV_ThreshHistTest::run_func(void) -{ - cvThreshHist( hist[0], threshold ); -} - - -int CV_ThreshHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - int i; - float* ptr0 = values->data.fl; - float* ptr = 0; - CvSparseMat* sparse = 0; - - if( hist_type == CV_HIST_ARRAY ) - ptr = (float*)cvPtr1D( hist[0]->bins, 0 ); - else - sparse = (CvSparseMat*)hist[0]->bins; - - if( code > 0 ) - { - for( i = 0; i < orig_nz_count; i++ ) - { - float v0 = ptr0[i], v; - - if( hist_type == CV_HIST_ARRAY ) - v = ptr[i]; - else - { - v = (float)cvGetRealND( sparse, indices->data.i + i*cdims ); - cvClearND( sparse, indices->data.i + i*cdims ); - } - - if( v0 <= threshold ) v0 = 0.f; - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( CvTS::LOG, "The %d-th bin is invalid (=%g)\n", i, v ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > FLT_EPSILON*10*fabs(v0) ) - { - ts->printf( CvTS::LOG, "The %d-th bin is incorrect (=%g, should be =%g)\n", i, v, v0 ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - } - } - } - - if( code > 0 && hist_type == CV_HIST_SPARSE ) - { - if( sparse->heap->active_count > 0 ) - { - ts->printf( CvTS::LOG, - "There some extra histogram bins in the sparse histogram after the thresholding\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_ThreshHistTest hist_thresh_test; - - -////////////// cvCompareHist ////////////// - -class CV_CompareHistTest : public CV_BaseHistTest -{ -public: - enum { MAX_METHOD = 4 }; - - CV_CompareHistTest(); -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - double result[MAX_METHOD+1]; -}; - - - -CV_CompareHistTest::CV_CompareHistTest() : - CV_BaseHistTest( "hist-compare", "cvCompareHist" ) -{ - hist_count = 2; - gen_random_hist = 1; -} - - -int CV_CompareHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - return code; -} - - -void CV_CompareHistTest::run_func(void) -{ - int k; - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h0((CvSparseMat*)hist[0]->bins); - cv::SparseMat h1((CvSparseMat*)hist[1]->bins); - for( k = 0; k < MAX_METHOD; k++ ) - result[k] = cv::compareHist(h0, h1, k); - } - else - for( k = 0; k < MAX_METHOD; k++ ) - result[k] = cvCompareHist( hist[0], hist[1], k ); -} - - -int CV_CompareHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - int i; - double result0[MAX_METHOD+1]; - double s0 = 0, s1 = 0, sq0 = 0, sq1 = 0, t; - - for( i = 0; i < MAX_METHOD; i++ ) - result0[i] = 0; - - if( hist_type == CV_HIST_ARRAY ) - { - float* ptr0 = (float*)cvPtr1D( hist[0]->bins, 0 ); - float* ptr1 = (float*)cvPtr1D( hist[1]->bins, 0 ); - - for( i = 0; i < total_size; i++ ) - { - double v0 = ptr0[i], v1 = ptr1[i]; - result0[CV_COMP_CORREL] += v0*v1; - result0[CV_COMP_INTERSECT] += MIN(v0,v1); - if( fabs(v0 + v1) > DBL_EPSILON ) - result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/(v0 + v1); - s0 += v0; - s1 += v1; - sq0 += v0*v0; - sq1 += v1*v1; - result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1); - } - } - else - { - CvSparseMat* sparse0 = (CvSparseMat*)hist[0]->bins; - CvSparseMat* sparse1 = (CvSparseMat*)hist[1]->bins; - CvSparseMatIterator iterator; - CvSparseNode* node; - - for( node = cvInitSparseMatIterator( sparse0, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator ) ) - { - const int* idx = CV_NODE_IDX(sparse0, node); - double v0 = *(float*)CV_NODE_VAL(sparse0, node); - double v1 = (float)cvGetRealND(sparse1, idx); - - result0[CV_COMP_CORREL] += v0*v1; - result0[CV_COMP_INTERSECT] += MIN(v0,v1); - if( fabs(v0 + v1) > DBL_EPSILON ) - result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/(v0 + v1); - s0 += v0; - sq0 += v0*v0; - result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1); - } - - for( node = cvInitSparseMatIterator( sparse1, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator ) ) - { - const int* idx = CV_NODE_IDX(sparse1, node); - double v1 = *(float*)CV_NODE_VAL(sparse1, node); - double v0 = (float)cvGetRealND(sparse0, idx); - - if( fabs(v0) < DBL_EPSILON ) - result0[CV_COMP_CHISQR] += v1; - s1 += v1; - sq1 += v1*v1; - } - } - - t = (sq0 - s0*s0/total_size)*(sq1 - s1*s1/total_size); - result0[CV_COMP_CORREL] = fabs(t) > DBL_EPSILON ? - (result0[CV_COMP_CORREL] - s0*s1/total_size)/sqrt(t) : 1; - - s1 *= s0; - s0 = result0[CV_COMP_BHATTACHARYYA]; - s0 = 1. - s0*(s1 > FLT_EPSILON ? 1./sqrt(s1) : 1.); - result0[CV_COMP_BHATTACHARYYA] = sqrt(MAX(s0,0.)); - - for( i = 0; i < MAX_METHOD; i++ ) - { - double v = result[i], v0 = result0[i]; - const char* method_name = - i == CV_COMP_CHISQR ? "Chi-Square" : - i == CV_COMP_CORREL ? "Correlation" : - i == CV_COMP_INTERSECT ? "Intersection" : - i == CV_COMP_BHATTACHARYYA ? "Bhattacharyya" : "Unknown"; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( CvTS::LOG, "The comparison result using the method #%d (%s) is invalid (=%g)\n", - i, method_name, v ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > FLT_EPSILON*10*MAX(fabs(v0),0.1) ) - { - ts->printf( CvTS::LOG, "The comparison result using the method #%d (%s)\n\tis inaccurate (=%g, should be =%g)\n", - i, method_name, v, v0 ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_CompareHistTest hist_compare_test; - - - -////////////// cvCalcHist ////////////// - -class CV_CalcHistTest : public CV_BaseHistTest -{ -public: - CV_CalcHistTest(); - ~CV_CalcHistTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - IplImage* images[CV_MAX_DIM+1]; - int channels[CV_MAX_DIM+1]; -}; - - - -CV_CalcHistTest::CV_CalcHistTest() : - CV_BaseHistTest( "hist-calc", "cvCalcHist" ) -{ - int i; - - hist_count = 2; - gen_random_hist = 0; - init_ranges = 1; - - for( i = 0; i <= CV_MAX_DIM; i++ ) - { - images[i] = 0; - channels[i] = 0; - } -} - - -CV_CalcHistTest::~CV_CalcHistTest() -{ - clear(); -} - - -void CV_CalcHistTest::clear() -{ - int i; - - for( i = 0; i <= CV_MAX_DIM; i++ ) - cvReleaseImage( &images[i] ); - - CV_BaseHistTest::clear(); -} - - -int CV_CalcHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - CvRNG* rng = ts->get_rng(); - int i; - - for( i = 0; i <= CV_MAX_DIM; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvTsRandInt(rng) % 3 + 1; - images[i] = cvCreateImage( img_size, - img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch ); - channels[i] = cvTsRandInt(rng) % nch; - - cvRandArr( rng, images[i], CV_RAND_UNI, - cvScalarAll(low), cvScalarAll(high) ); - } - else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 ) - { - // create mask - images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 ); - // make ~25% pixels in the mask non-zero - cvRandArr( rng, images[i], CV_RAND_UNI, - cvScalarAll(-2), cvScalarAll(2) ); - } - } - } - - return code; -} - - -void CV_CalcHistTest::run_func(void) -{ - cvCalcHist( images, hist[0], 0, images[CV_MAX_DIM] ); -} - - -static void -cvTsCalcHist( IplImage** _images, CvHistogram* hist, IplImage* _mask, int* channels ) -{ - int x, y, k, cdims; - union - { - float* fl; - uchar* ptr; - } - plane[CV_MAX_DIM]; - int nch[CV_MAX_DIM]; - int dims[CV_MAX_DIM]; - int uniform = CV_IS_UNIFORM_HIST(hist); - CvSize img_size = cvGetSize(_images[0]); - CvMat images[CV_MAX_DIM], mask = cvMat(1,1,CV_8U); - int img_depth = _images[0]->depth; - - cdims = cvGetDims( hist->bins, dims ); - - cvZero( hist->bins ); - - for( k = 0; k < cdims; k++ ) - { - cvGetMat( _images[k], &images[k] ); - nch[k] = _images[k]->nChannels; - } - - if( _mask ) - cvGetMat( _mask, &mask ); - - for( y = 0; y < img_size.height; y++ ) - { - const uchar* mptr = _mask ? &CV_MAT_ELEM(mask, uchar, y, 0 ) : 0; - - if( img_depth == IPL_DEPTH_8U ) - for( k = 0; k < cdims; k++ ) - plane[k].ptr = &CV_MAT_ELEM(images[k], uchar, y, 0 ) + channels[k]; - else - for( k = 0; k < cdims; k++ ) - plane[k].fl = &CV_MAT_ELEM(images[k], float, y, 0 ) + channels[k]; - - for( x = 0; x < img_size.width; x++ ) - { - float val[CV_MAX_DIM]; - int idx[CV_MAX_DIM]; - - if( mptr && !mptr[x] ) - continue; - if( img_depth == IPL_DEPTH_8U ) - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].ptr[x*nch[k]]; - else - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].fl[x*nch[k]]; - - idx[cdims-1] = -1; - - if( uniform ) - { - for( k = 0; k < cdims; k++ ) - { - double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1]; - idx[k] = cvFloor((v - lo)*dims[k]/(hi - lo)); - if( idx[k] < 0 || idx[k] >= dims[k] ) - break; - } - } - else - { - for( k = 0; k < cdims; k++ ) - { - float v = val[k]; - float* t = hist->thresh2[k]; - int j, n = dims[k]; - - for( j = 0; j <= n; j++ ) - if( v < t[j] ) - break; - if( j <= 0 || j > n ) - break; - idx[k] = j-1; - } - } - - if( k < cdims ) - continue; - - (*(float*)cvPtrND( hist->bins, idx ))++; - } - } -} - - -int CV_CalcHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - double diff; - cvTsCalcHist( images, hist[1], images[CV_MAX_DIM], channels ); - diff = cvCompareHist( hist[0], hist[1], CV_COMP_CHISQR ); - if( diff > DBL_EPSILON ) - { - ts->printf( CvTS::LOG, "The histogram does not match to the reference one\n" ); - code = CvTS::FAIL_BAD_ACCURACY; - - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_CalcHistTest hist_calc_test; - - - -////////////// cvCalcBackProject ////////////// - -class CV_CalcBackProjectTest : public CV_BaseHistTest -{ -public: - CV_CalcBackProjectTest(); - ~CV_CalcBackProjectTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - IplImage* images[CV_MAX_DIM+3]; - int channels[CV_MAX_DIM+3]; -}; - - - -CV_CalcBackProjectTest::CV_CalcBackProjectTest() : - CV_BaseHistTest( "hist-backproj", "cvCalcBackProject" ) -{ - int i; - - hist_count = 1; - gen_random_hist = 0; - init_ranges = 1; - - for( i = 0; i < CV_MAX_DIM+3; i++ ) - { - images[i] = 0; - channels[i] = 0; - } -} - - -CV_CalcBackProjectTest::~CV_CalcBackProjectTest() -{ - clear(); -} - - -void CV_CalcBackProjectTest::clear() -{ - int i; - - for( i = 0; i < CV_MAX_DIM+3; i++ ) - cvReleaseImage( &images[i] ); - - CV_BaseHistTest::clear(); -} - - -int CV_CalcBackProjectTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - CvRNG* rng = ts->get_rng(); - int i, j, n, img_len = img_size.width*img_size.height; - - for( i = 0; i < CV_MAX_DIM + 3; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvTsRandInt(rng) % 3 + 1; - images[i] = cvCreateImage( img_size, - img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch ); - channels[i] = cvTsRandInt(rng) % nch; - - cvRandArr( rng, images[i], CV_RAND_UNI, - cvScalarAll(low), cvScalarAll(high) ); - } - else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 ) - { - // create mask - images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 ); - // make ~25% pixels in the mask non-zero - cvRandArr( rng, images[i], CV_RAND_UNI, - cvScalarAll(-2), cvScalarAll(2) ); - } - else if( i > CV_MAX_DIM ) - { - images[i] = cvCreateImage( img_size, images[0]->depth, 1 ); - } - } - - cvTsCalcHist( images, hist[0], images[CV_MAX_DIM], channels ); - - // now modify the images a bit to add some zeros go to the backprojection - n = cvTsRandInt(rng) % (img_len/20+1); - for( i = 0; i < cdims; i++ ) - { - char* data = images[i]->imageData; - for( j = 0; j < n; j++ ) - { - int idx = cvTsRandInt(rng) % img_len; - double val = cvTsRandReal(rng)*(high - low) + low; - - if( img_type == CV_8U ) - ((uchar*)data)[idx] = (uchar)cvRound(val); - else - ((float*)data)[idx] = (float)val; - } - } - } - - return code; -} - - -void CV_CalcBackProjectTest::run_func(void) -{ - cvCalcBackProject( images, images[CV_MAX_DIM+1], hist[0] ); -} - - -static void -cvTsCalcBackProject( IplImage** images, IplImage* dst, CvHistogram* hist, int* channels ) -{ - int x, y, k, cdims; - union - { - float* fl; - uchar* ptr; - } - plane[CV_MAX_DIM]; - int nch[CV_MAX_DIM]; - int dims[CV_MAX_DIM]; - int uniform = CV_IS_UNIFORM_HIST(hist); - CvSize img_size = cvGetSize(images[0]); - int img_depth = images[0]->depth; - - cdims = cvGetDims( hist->bins, dims ); - - for( k = 0; k < cdims; k++ ) - nch[k] = images[k]->nChannels; - - for( y = 0; y < img_size.height; y++ ) - { - if( img_depth == IPL_DEPTH_8U ) - for( k = 0; k < cdims; k++ ) - plane[k].ptr = &CV_IMAGE_ELEM(images[k], uchar, y, 0 ) + channels[k]; - else - for( k = 0; k < cdims; k++ ) - plane[k].fl = &CV_IMAGE_ELEM(images[k], float, y, 0 ) + channels[k]; - - for( x = 0; x < img_size.width; x++ ) - { - float val[CV_MAX_DIM]; - float bin_val = 0; - int idx[CV_MAX_DIM]; - - if( img_depth == IPL_DEPTH_8U ) - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].ptr[x*nch[k]]; - else - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].fl[x*nch[k]]; - idx[cdims-1] = -1; - - if( uniform ) - { - for( k = 0; k < cdims; k++ ) - { - double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1]; - idx[k] = cvFloor((v - lo)*dims[k]/(hi - lo)); - if( idx[k] < 0 || idx[k] >= dims[k] ) - break; - } - } - else - { - for( k = 0; k < cdims; k++ ) - { - float v = val[k]; - float* t = hist->thresh2[k]; - int j, n = dims[k]; - - for( j = 0; j <= n; j++ ) - if( v < t[j] ) - break; - if( j <= 0 || j > n ) - break; - idx[k] = j-1; - } - } - - if( k == cdims ) - bin_val = (float)cvGetRealND( hist->bins, idx ); - - if( img_depth == IPL_DEPTH_8U ) - { - int t = cvRound(bin_val); - CV_IMAGE_ELEM( dst, uchar, y, x ) = CV_CAST_8U(t); - } - else - CV_IMAGE_ELEM( dst, float, y, x ) = bin_val; - } - } -} - - -int CV_CalcBackProjectTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - - cvTsCalcBackProject( images, images[CV_MAX_DIM+2], hist[0], channels ); - code = cvTsCmpEps2( ts, images[CV_MAX_DIM+1], images[CV_MAX_DIM+2], 0, true, - "Back project image" ); - - if( code < 0 ) - ts->set_failed_test_info( code ); - - return code; -} - - -CV_CalcBackProjectTest hist_backproj_test; - - -////////////// cvCalcBackProjectPatch ////////////// - -class CV_CalcBackProjectPatchTest : public CV_BaseHistTest -{ -public: - CV_CalcBackProjectPatchTest(); - ~CV_CalcBackProjectPatchTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - IplImage* images[CV_MAX_DIM+2]; - int channels[CV_MAX_DIM+2]; - - CvSize patch_size; - double factor; - int method; -}; - - - -CV_CalcBackProjectPatchTest::CV_CalcBackProjectPatchTest() : - CV_BaseHistTest( "hist-backprojpatch", "cvCalcBackProjectPatch" ) -{ - int i; - - hist_count = 1; - gen_random_hist = 0; - init_ranges = 1; - img_max_log_size = 6; - - for( i = 0; i < CV_MAX_DIM+2; i++ ) - { - images[i] = 0; - channels[i] = 0; - } -} - - -CV_CalcBackProjectPatchTest::~CV_CalcBackProjectPatchTest() -{ - clear(); -} - - -void CV_CalcBackProjectPatchTest::clear() -{ - int i; - - for( i = 0; i < CV_MAX_DIM+2; i++ ) - cvReleaseImage( &images[i] ); - - CV_BaseHistTest::clear(); -} - - -int CV_CalcBackProjectPatchTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - CvRNG* rng = ts->get_rng(); - int i, j, n, img_len = img_size.width*img_size.height; - - patch_size.width = cvTsRandInt(rng) % img_size.width + 1; - patch_size.height = cvTsRandInt(rng) % img_size.height + 1; - patch_size.width = MIN( patch_size.width, 30 ); - patch_size.height = MIN( patch_size.height, 30 ); - - factor = 1.; - method = cvTsRandInt(rng) % CV_CompareHistTest::MAX_METHOD; - - for( i = 0; i < CV_MAX_DIM + 2; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvTsRandInt(rng) % 3 + 1; - images[i] = cvCreateImage( img_size, - img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch ); - channels[i] = cvTsRandInt(rng) % nch; - - cvRandArr( rng, images[i], CV_RAND_UNI, - cvScalarAll(low), cvScalarAll(high) ); - } - else if( i >= CV_MAX_DIM ) - { - images[i] = cvCreateImage( - cvSize(img_size.width - patch_size.width + 1, - img_size.height - patch_size.height + 1), - IPL_DEPTH_32F, 1 ); - } - } - - cvTsCalcHist( images, hist[0], 0, channels ); - cvNormalizeHist( hist[0], factor ); - - // now modify the images a bit - n = cvTsRandInt(rng) % (img_len/10+1); - for( i = 0; i < cdims; i++ ) - { - char* data = images[i]->imageData; - for( j = 0; j < n; j++ ) - { - int idx = cvTsRandInt(rng) % img_len; - double val = cvTsRandReal(rng)*(high - low) + low; - - if( img_type == CV_8U ) - ((uchar*)data)[idx] = (uchar)cvRound(val); - else - ((float*)data)[idx] = (float)val; - } - } - } - - return code; -} - - -void CV_CalcBackProjectPatchTest::run_func(void) -{ - cvCalcBackProjectPatch( images, images[CV_MAX_DIM], patch_size, hist[0], method, factor ); -} - - -static void -cvTsCalcBackProjectPatch( IplImage** images, IplImage* dst, CvSize patch_size, - CvHistogram* hist, int method, - double factor, int* channels ) -{ - CvHistogram* model = 0; - - IplImage imgstub[CV_MAX_DIM], *img[CV_MAX_DIM]; - IplROI roi; - int i, dims; - int x, y; - CvSize size = cvGetSize(dst); - - dims = cvGetDims( hist->bins ); - cvCopyHist( hist, &model ); - cvNormalizeHist( hist, factor ); - cvZero( dst ); - - for( i = 0; i < dims; i++ ) - { - CvMat stub, *mat; - mat = cvGetMat( images[i], &stub, 0, 0 ); - img[i] = cvGetImage( mat, &imgstub[i] ); - img[i]->roi = &roi; - } - - roi.coi = 0; - - for( y = 0; y < size.height; y++ ) - { - for( x = 0; x < size.width; x++ ) - { - double result; - - roi.xOffset = x; - roi.yOffset = y; - roi.width = patch_size.width; - roi.height = patch_size.height; - - cvTsCalcHist( img, model, 0, channels ); - cvNormalizeHist( model, factor ); - result = cvCompareHist( model, hist, method ); - CV_IMAGE_ELEM( dst, float, y, x ) = (float)result; - } - } - - cvReleaseHist( &model ); -} - - -int CV_CalcBackProjectPatchTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - double err_level = 5e-3; - - cvTsCalcBackProjectPatch( images, images[CV_MAX_DIM+1], - patch_size, hist[0], method, factor, channels ); - - code = cvTsCmpEps2( ts, images[CV_MAX_DIM], images[CV_MAX_DIM+1], err_level, true, - "BackProjectPatch result" ); - - if( code < 0 ) - ts->set_failed_test_info( code ); - - return code; -} - - -CV_CalcBackProjectPatchTest hist_backprojpatch_test; - - -////////////// cvCalcBayesianProb ////////////// - -class CV_BayesianProbTest : public CV_BaseHistTest -{ -public: - enum { MAX_METHOD = 4 }; - - CV_BayesianProbTest(); -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - void init_hist( int test_case_idx, int i ); - void get_hist_params( int test_case_idx ); -}; - - - -CV_BayesianProbTest::CV_BayesianProbTest() : - CV_BaseHistTest( "hist-bayesianprob", "cvBayesianProb" ) -{ - hist_count = CV_MAX_DIM; - gen_random_hist = 1; -} - - -void CV_BayesianProbTest::get_hist_params( int test_case_idx ) -{ - CV_BaseHistTest::get_hist_params( test_case_idx ); - hist_type = CV_HIST_ARRAY; -} - - -void CV_BayesianProbTest::init_hist( int test_case_idx, int hist_i ) -{ - if( hist_i < hist_count/2 ) - CV_BaseHistTest::init_hist( test_case_idx, hist_i ); -} - - -int CV_BayesianProbTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - - hist_count = (cvTsRandInt(rng) % (MAX_HIST/2-1) + 2)*2; - hist_count = MIN( hist_count, MAX_HIST ); - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - return code; -} - - -void CV_BayesianProbTest::run_func(void) -{ - cvCalcBayesianProb( hist, hist_count/2, hist + hist_count/2 ); -} - - -int CV_BayesianProbTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - int i, j, n = hist_count/2; - double s[CV_MAX_DIM]; - const double err_level = 1e-5; - - for( i = 0; i < total_size; i++ ) - { - double sum = 0; - for( j = 0; j < n; j++ ) - { - double v = hist[j]->mat.data.fl[i]; - sum += v; - s[j] = v; - } - sum = sum > DBL_EPSILON ? 1./sum : 0; - - for( j = 0; j < n; j++ ) - { - double v0 = s[j]*sum; - double v = hist[j+n]->mat.data.fl[i]; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( CvTS::LOG, - "The element #%d in the destination histogram #%d is invalid (=%g)\n", - i, j, v ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > err_level*fabs(v0) ) - { - ts->printf( CvTS::LOG, - "The element #%d in the destination histogram #%d is inaccurate (=%g, should be =%g)\n", - i, j, v, v0 ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - } - } - if( j < n ) - break; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_BayesianProbTest hist_bayesianprob_test; - -/* End Of File */ diff --git a/tests/cv/src/ahmmobs.cpp b/tests/cv/src/ahmmobs.cpp deleted file mode 100644 index 804a687..0000000 --- a/tests/cv/src/ahmmobs.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 /* avoid this while a substitution for IPL DCT is not ready */ - -#include -#include -#include -#include - -static char* funcs[] = -{ - "cvImgToObs_DCT" -}; - -static char *test_desc[] = -{ - "Comparing against IPL DCT" -}; - -/* actual parameters */ -static int min_img_size, max_img_size; -static int max_dct_size; -static int base_iters; - -static int init_hmm_obs_params = 0; - -static const int img8u_range = 256; - -static void read_hmm_obs_params( void ) -{ - if( !init_hmm_obs_params ) - { - /* read tests params */ - trsiRead( &min_img_size, "10", "Minimal width or height of image" ); - trsiRead( &max_img_size, "300", "Maximal width or height of image" ); - trsiRead( &max_dct_size, "24", "Maximum DCT size" ); - trsiRead( &base_iters, "100", "Base number of iterations" ); - - init_hmm_obs_params = 1; - } -} - - -static CvSize hmm_obs_dct_get_size( IplImage* img, CvSize dctSize, CvSize delta ) -{ - CvSize result; - CvRect roi = cvGetImageROI( img ); - - result.width = (roi.width - dctSize.width + delta.width) / delta.width; - result.height = (roi.height - dctSize.height + delta.height) / delta.height; - - return result; -} - - -static void hmm_obs_dct_etalon( IplImage* img, char* obs, CvSize dctSize, - CvSize obsSize, CvSize delta ) -{ - IplImage *src = cvCreateImage( dctSize, IPL_DEPTH_8U, 1 ); - IplImage *dst = cvCreateImage( dctSize, IPL_DEPTH_32F, 1 ); - - CvSize result = hmm_obs_dct_get_size( img, dctSize, delta ); - - int x, y, j; - int obs_step = obsSize.width*sizeof(float); - - result.width *= delta.width; - result.height *= delta.height; - - for( y = 0; y < result.height; y += delta.height ) - for( x = 0; x < result.width; x += delta.width ) - { - cvSetImageROI( img, cvRect( x, y, dctSize.width, dctSize.height )); - cvCopy( img, src ); - iplDCT2D( src, dst, IPL_DCT_Forward ); - for( j = 0; j < obsSize.height; j++ ) - { - memcpy( obs, dst->imageData + dst->widthStep*j, obs_step ); - obs += obs_step; - } - } - - cvReleaseImage( &src ); - cvReleaseImage( &dst ); -} - - - -/* ///////////////////// moments_test ///////////////////////// */ -static int hmm_dct_test( void ) -{ - const double success_error_level = 1.1; - - int seed = atsGetSeed(); - int code = TRS_OK; - const int max_obs_size = 8; - - /* position where the maximum error occured */ - int i, merr_iter = 0; - - /* test parameters */ - double max_err = 0.; - - IplImage *img = 0; - IplImage *obs = 0; - IplImage *obs2 = 0; - AtsRandState rng_state; - CvSize obs_size; - - atsRandInit( &rng_state, 0, img8u_range, seed ); - - read_hmm_obs_params(); - - img = cvCreateImage( cvSize( max_img_size, max_img_size ), IPL_DEPTH_8U, 1 ); - obs_size.height = max_img_size; - obs_size.width = obs_size.height*64; - obs = cvCreateImage( obs_size, IPL_DEPTH_32F, 1 ); - obs2 = cvCreateImage( obs_size, IPL_DEPTH_32F, 1 ); - - for( i = 0; i < base_iters; i++ ) - { - CvSize size; - CvSize dctSize, obsSize, delta, result; - double err = 0; - - size.width = atsRandPlain32s( &rng_state ) % - (max_img_size - min_img_size + 1) + min_img_size; - size.height = atsRandPlain32s( &rng_state ) % - (max_img_size - min_img_size + 1) + min_img_size; - - dctSize.width = atsRandPlain32s( &rng_state ) % (max_dct_size - 1) + 2; - if( dctSize.width > size.width ) - dctSize.width = size.width; - dctSize.height = atsRandPlain32s( &rng_state ) % (max_dct_size - 1) + 2; - if( dctSize.height > size.height ) - dctSize.height = size.height; - - obsSize.width = atsRandPlain32s( &rng_state ) % max_obs_size + 1; - if( obsSize.width > dctSize.width ) - obsSize.width = dctSize.width; - obsSize.height = atsRandPlain32s( &rng_state ) % max_obs_size + 1; - if( obsSize.height > dctSize.height ) - obsSize.height = dctSize.height; - - delta.width = atsRandPlain32s( &rng_state ) % dctSize.width + 1; - delta.height = atsRandPlain32s( &rng_state ) % dctSize.height + 1; - - cvSetImageROI( img, cvRect( 0, 0, size.width, size.height )); - - result = hmm_obs_dct_get_size( img, dctSize, delta ); - - atsFillRandomImageEx( img, &rng_state ); - - OPENCV_CALL( cvImgToObs_DCT( img, (float*)(obs->imageData), dctSize, obsSize, delta )); - - hmm_obs_dct_etalon( img, obs2->imageData, dctSize, obsSize, delta ); - - obs->width = obs2->width = result.width*obsSize.width*obsSize.height; - obs->height = obs2->height = result.height; - obs->widthStep = obs2->widthStep = obs->width*sizeof(float); - - assert( obs->roi == 0 && obs2->roi == 0 ); - - err = cvNorm( obs, obs2, CV_C ); - - obs->width = obs2->width = max_img_size; - obs->height = obs2->height = max_img_size; - obs->widthStep = obs2->widthStep = obs->width*sizeof(float); - - if( err > max_err ) - { - merr_iter = i; - max_err = err; - if( max_err > success_error_level ) - goto test_exit; - } - } - -test_exit: - - cvReleaseImage( &img ); - cvReleaseImage( &obs ); - cvReleaseImage( &obs2 ); - - if( code == TRS_OK ) - { - trsWrite( ATS_LST, "Max err is %g at iter = %d, seed = %08x", - max_err, merr_iter, seed ); - - return max_err <= success_error_level ? - trsResult( TRS_OK, "No errors" ) : - trsResult( TRS_FAIL, "Bad accuracy" ); - } - /*else - { - trsWrite( ATS_LST, "Fatal error at iter = %d, seed = %08x", i, seed ); - return trsResult( TRS_FAIL, "Function returns error code" ); - }*/ -} - - -void InitAImageToHMMObs( void ) -{ - /* Register test functions */ - - trsReg( funcs[0], test_desc[0], atsAlgoClass, hmm_dct_test ); - -} /* InitAMoments */ - -#endif - -/* End of file. */ diff --git a/tests/cv/src/ahoughtransform.cpp b/tests/cv/src/ahoughtransform.cpp deleted file mode 100644 index 67fdc2a..0000000 --- a/tests/cv/src/ahoughtransform.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#include -#include -#include - -#define HT_STANDARD (size_t)1 -#define HT_PP (size_t)2 -#define HT_MD (size_t)3 - -static char* func_names[] = {"cvHoughTransform", "cvHoughTransformP", "cvHoughTransformSDiv"}; -static char* test_desc[] = { "Run the hough transform function"}; - -int test_dt(void* arg); -int read_image_dims(void); -int read_gen_type(void); - -int test_ht(void* arg) -{ - int nlines = 10; - int* lines = new int[4*nlines]; - float* flines = new float[2*nlines]; - float rho = 10.0f, theta = 0.1f; - int srn = 10, stn = 10; - int threshold = 10; - int lineLength = 10, lineGap = 2; - int w = 100; /* width and height of the rect */ - int h = 100; - int type = (int)(size_t)arg; - IplImage* image; /* Source and destination images */ - image = cvCreateImage( cvSize(w, h), 8, 1 ); - cvZero(image); - - if( image == NULL ) - { - delete lines; - delete flines; - return trsResult(TRS_FAIL, "Not enough memory to perform the test"); - } - - switch(type) - { - case HT_STANDARD: - /* Run the distance transformation function */ - cvHoughLines(image, rho, theta, threshold, flines, nlines); - break; - - case HT_PP: - cvHoughLinesP(image, rho, theta, threshold, lineLength, lineGap, lines, nlines); - break; - - case HT_MD: - cvHoughLinesSDiv(image, rho, srn, theta, stn, threshold, flines, nlines); - break; - - default: - cvReleaseImage(& image); - delete lines; - delete flines; - trsResult(TRS_FAIL, "No such function"); - } - cvReleaseImage( &image ); - delete lines; - delete flines; - if(cvGetErrStatus() < 0) - { - return trsResult(TRS_FAIL, "Function returned 'bad argument'"); - } - else - { - return trsResult(TRS_OK, "No errors"); - } -} - -void InitAHoughLines(void) -{ - /* Registering test functions */ - trsRegArg(func_names[0], test_desc[0], atsAlgoClass, test_ht, HT_STANDARD); - trsRegArg(func_names[1], test_desc[0], atsAlgoClass, test_ht, HT_PP); - trsRegArg(func_names[2], test_desc[0], atsAlgoClass, test_ht, HT_MD); - -} /* InitADistanceTransform*/ - -#endif - diff --git a/tests/cv/src/aimage.cpp b/tests/cv/src/aimage.cpp deleted file mode 100644 index ac0e44d..0000000 --- a/tests/cv/src/aimage.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#define DEPTH_8U 0 - -/* Testing parameters */ -static char test_desc[] = "Image Creation & access"; -static char func_name[] = "cvCreateImage cvCreateImageHeader cvSetImageROI cvGetImageROI " - "cvSetImageCOI cvCreateImageData cvReleaseImageData " - "cvSetImageData cvCloneImage cvCopyImage cvInitImageHeader"; - -static int depths[] = { IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, - IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F, 0}; -static int channels[] = {1, 2, 3, 4, 0}; - -static char* imageData = (char*)cvAlloc(10000); - -const int align = 4; - -static int foaImage( void ) -{ - CvSize size = cvSize(320, 200); - int i, j; - int Errors = 0; - //Creating new image with different channels & depths - for( i = 0; depths[i] != 0; i++ ) // cycle for depths - for(j = 0; channels[j] != 0; j++) // cycle for channels - { - if( depths[i] == IPL_DEPTH_1U && channels[j] != 1 ) // skip for IPL_DEPTH_1U - continue; // all non 1 channels - IplImage* image = cvCreateImage( size, depths[i], channels[j] ); - if( image->width != size.width || image->height != size.height ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCreateImage: Size mismatch: act %d x %d exp %d x %d\n", - image->width, image->height, size.width, size.height ); - Errors++; - } - if( size.width * (depths[i] & IPL_DEPTH_MASK) / 8 > image->widthStep || - (image->widthStep & 3) ) - { - trsWrite( ATS_CON | ATS_LST, "cvCreateImage: Wrong widthStep: act %d\n", - image->widthStep ); - Errors++; - } - - cvReleaseImage( &image ); - } - trsWrite( ATS_CON, "cvCreateImage: ... done\n" ); - - //Creating new image header with different channels & depths - for( i = 0; depths[i] != 0; i++ ) // cycle for depths - for(j = 0; channels[j] != 0; j++) // cycle for channels - { - if( depths[i] == IPL_DEPTH_1U && channels[j] != 1 ) // skip for IPL_DEPTH_1U - continue; // all non 1 channels - if( depths[i] == (int)IPL_DEPTH_8S ) - continue; - IplImage* image = cvCreateImageHeader( size, depths[i], channels[j] ); - if( image->width != size.width || image->height != size.height ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCreateImageHeader: Size mismatch: act %d x %d exp %d x %d\n", - image->width, image->height, size.width, size.height ); - Errors++; - } - if( size.width * (depths[i] & IPL_DEPTH_MASK) / 8 > image->widthStep || - (image->widthStep & 3) ) - { - trsWrite( ATS_CON | ATS_LST, "cvCreateImageHeader: Wrong widthStep: act %d\n", - image->widthStep ); - Errors++; - } - if( image->imageData ) - { - trsWrite( ATS_CON | ATS_LST, "cvCreateImageHeader: imageData created :(\n" ); - Errors++; - } - - cvSetImageROI( image, cvRect(1, 1, size.width - 1, size.height - 1) ); - if( image->roi->coi ) - { - trsWrite( ATS_CON | ATS_LST, "cvSetImageROI: coi non zero\n" ); - Errors++; - } - - CvRect rect = cvGetImageROI( image ); - if( rect.x != 1 || rect.y != 1 || - rect.width != size.width - 1 || rect.height != size.height - 1 ) - { - trsWrite( ATS_CON | ATS_LST, - "cvGetImageROI: wrong rect: act %d x %d x %d x %d " - "exp %d x %d x %d x %d\n", - rect.x, rect.y, rect.width, rect.height, - 1, 1, size.width - 1, size.height - 1 ); - Errors++; - } - - cvSetImageCOI( image, 1 ); - if( image->roi->coi != 1 ) - { - trsWrite( ATS_CON | ATS_LST, "cvSetImageCOI: soi non 1\n" ); - Errors++; - } - if( image->roi->xOffset != 1 || image->roi->yOffset != 1 || - image->roi->width != size.width - 1 || - image->roi->height != size.height - 1) - { - trsWrite( ATS_CON | ATS_LST, - "cvCreateImageHeader: Size mismatch: act %d x %d x %d x %d" - "exp %d x %d x %d x %d\n", - image->roi->xOffset, image->roi->yOffset, - image->roi->width, image->roi->height, - 1, 1, size.width - 1, size.height - 1 ); - Errors++; - } - - cvCreateImageData( image ); - if( !image->imageData ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCreateImageData: Wow :)... where is imageData ?....\n" ); - Errors++; - } - - cvReleaseImageData( image ); - if( image->imageData ) - { - trsWrite( ATS_CON | ATS_LST, "cvReleaseImageData: imageData non zero :(\n" ); - Errors++; - } - - cvSetImageData( image, imageData, size.width * channels[j] * 8 ); // magic width step :) - if( image->imageData != imageData ) - { - trsWrite( ATS_CON | ATS_LST, - "cvSetImageData: wrong pointer to imageData: act %x, exp %x\n", - image->imageData, imageData ); - Errors++; - } - if( image->widthStep != size.width * channels[j] * 8 ) - { - trsWrite( ATS_CON | ATS_LST, "cvSetImageData: wrong imageStep: act %d, exp %d\n", - image->widthStep, size.width * channels[j] * 8 ); - Errors++; - } - - cvReleaseImageHeader( &image ); - } - trsWrite( ATS_CON, "cvCreateImageHeader: ... done\n" ); - trsWrite( ATS_CON, "cvSetImageROI: ... done\n" ); - trsWrite( ATS_CON, "cvGetImageROI: ... done\n" ); - trsWrite( ATS_CON, "cvSetImageCOI: ... done\n" ); - trsWrite( ATS_CON, "cvCreateImageData: ... done\n" ); - trsWrite( ATS_CON, "cvReleaseImageData: ... done\n" ); - trsWrite( ATS_CON, "cvSetImageData: ... done\n" ); - - for( i = 0; depths[i] != 0; i++ ) // cycle for depths - for(j = 0; channels[j] != 0; j++) // cycle for channels - { - if( depths[i] == IPL_DEPTH_1U && channels[j] != 1 ) // skip for IPL_DEPTH_1U - continue; // all non 1 channels - if( depths[i] == (int)IPL_DEPTH_8S ) - continue; - IplImage* src = cvCreateImage( size, depths[i], channels[j] ); - //IplImage* dst = cvCreateImage( size, depths[i], channels[j] ); - IplImage* dst = 0; - IplImage* clone = 0; - - cvSetImageROI( src, cvRect(1, 1, size.width - 1, size.height - 1) ); - - for( int k = 0; k < src->widthStep * src->height; k++ ) - src->imageData[k] = (char)k; - - //cvCopy/*Image*/( src, dst ); - dst = cvCloneImage( src ); - clone = dst; - - if( clone->width != dst->width || clone->height != dst->height ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCopyImage/cvCloneImage: wrong destination size:" - "%d x %d <> %d %d\n", - clone->width, clone->height, dst->width, dst->height ); - Errors++; - } - if( clone->widthStep != src->widthStep ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCloneImage: wrong width step: act %d exp %d\n", - clone->widthStep, src->widthStep ); - Errors++; - } - if( !clone->roi ) - { - trsWrite( ATS_CON | ATS_LST, "cvCloneImage: roi was lost\n" ); - Errors++; - } - else - { - if( clone->roi->xOffset != 1 || clone->roi->yOffset != 1 || - clone->roi->width != size.width - 1 || - clone->roi->height != size.height - 1 ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCloneImage: Size mismatch: act %d x %d x %d x %d" - "exp %d x %d x %d x %d\n", - clone->roi->xOffset, clone->roi->yOffset, - clone->roi->width, clone->roi->height, - 1, 1, size.width - 1, size.height - 1 ); - Errors++; - } - - } - if( depths[i] == IPL_DEPTH_32F ) - { - src->depth = IPL_DEPTH_32S; - dst->depth = IPL_DEPTH_32S; - } - else if( depths[i] == IPL_DEPTH_64F ) - { - src->depth = IPL_DEPTH_32S; - dst->depth = IPL_DEPTH_32S; - - src->width *= 2; - dst->width *= 2; - } - - if( cvNorm( src, dst, CV_L1 ) ) - { - trsWrite( ATS_CON | ATS_LST, "cvCopyImage: wrong destination image\n" ); - Errors++; - } - /*if( cvNorm( src, clone, CV_L1 ) ) - { - trsWrite( ATS_CON | ATS_LST, "cvCloneImage: wrong destination image\n" ); - Errors++; - }*/ - - cvReleaseImage( &src ); - cvReleaseImage( &clone ); - } - trsWrite( ATS_CON, "cvCloneImage: ... done\n" ); - //trsWrite( ATS_CON, "cvCopyImage: ... done\n" ); - - //Init new image header with different channels & depths - for( i = 0; depths[i] != 0; i++ ) // cycle for depths - for(j = 0; channels[j] != 0; j++) // cycle for channels - { - if( depths[i] == IPL_DEPTH_1U && channels[j] != 1 ) // skip for IPL_DEPTH_1U - continue; // all non 1 channels - IplImage image; - cvInitImageHeader( &image, size, depths[i], channels[j], IPL_ORIGIN_TL, align ); - if( image.width != size.width || image.height != size.height ) - { - trsWrite( ATS_CON | ATS_LST, - "cvInitImageHeader: Size mismatch: act %d x %d exp %d x %d\n", - image.width, image.height, size.width, size.height ); - Errors++; - } - if( ((size.width * channels[j] * (depths[i] & IPL_DEPTH_MASK) / 8 + align - 1) & - ~(align - 1)) != image.widthStep ) - { - trsWrite( ATS_CON | ATS_LST, - "cvCreateImageHeader: Wrong widthStep: act %d exp: %d\n", - image.widthStep, - (size.width * (depths[i] & IPL_DEPTH_MASK) / 8 + align - 1) & - ~(align - 1) ); - Errors++; - } - if( image.imageData ) - { - trsWrite( ATS_CON | ATS_LST, "cvCreateImageHeader: imageData created :(\n" ); - Errors++; - } - } - trsWrite( ATS_CON, "cvInitImageHeader: ... done\n" ); - - if( !Errors ) - return trsResult( TRS_OK, "Ok" ); - else - return trsResult( TRS_FAIL, "%d errors" ); -} - - - -void InitAImage() -{ - /* Register test function */ - trsReg( func_name, test_desc, atsAlgoClass, foaImage ); -} /* InitACanny */ - -#endif diff --git a/tests/cv/src/aimgwarp.cpp b/tests/cv/src/aimgwarp.cpp deleted file mode 100644 index b83a8c5..0000000 --- a/tests/cv/src/aimgwarp.cpp +++ /dev/null @@ -1,2052 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const int imgwarp_depths[] = { CV_8U, CV_16U, CV_32F, -1 }; -static const int imgwarp_channels[] = { 1, 3, 4, -1 }; -static const CvSize imgwarp_sizes[] = {{320, 240}, {1024,768}, {-1,-1}}; - -static const double imgwarp_resize_coeffs[] = { 0.5, 0.333, 2, 2.9 }; -static const char* imgwarp_resize_methods[] = { "nearest", "linear", "cubic", "area", 0 }; -static const char* imgwarp_resize_param_names[] = { "method", "coeff", "size", "channels", "depth", 0 }; - -static const double imgwarp_affine_rotate_scale[][4] = { {0.5,0.5,30.,1.4}, {0.5,0.5,-130,0.4}, {-1,-1,-1,-1} }; -static const char* imgwarp_affine_param_names[] = { "rotate_scale", "size", "channels", "depth", 0 }; - -static const double imgwarp_perspective_shift_vtx[][8] = { {0.03,0.01,0.04,0.02,0.01,0.01,0.01,0.02}, {-1} }; -static const char* imgwarp_perspective_param_names[] = { "shift_vtx", "size", "channels", "depth", 0 }; - -class CV_ImgWarpBaseTestImpl : public CvArrTest -{ -public: - CV_ImgWarpBaseTestImpl( const char* test_name, const char* test_funcs, bool warp_matrix ); - -protected: - int read_params( CvFileStorage* fs ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - int interpolation; - int max_interpolation; - double spatial_scale_zoom, spatial_scale_decimate; -}; - - -CV_ImgWarpBaseTestImpl::CV_ImgWarpBaseTestImpl( const char* test_name, const char* test_funcs, bool warp_matrix ) - : CvArrTest( test_name, test_funcs, "" ) -{ - test_array[INPUT].push(NULL); - if( warp_matrix ) - test_array[INPUT].push(NULL); - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - max_interpolation = 5; - interpolation = 0; - element_wise_relative_error = false; - spatial_scale_zoom = 0.01; - spatial_scale_decimate = 0.005; - - size_list = whole_size_list = imgwarp_sizes; - depth_list = imgwarp_depths; - cn_list = imgwarp_channels; - default_timing_param_names = 0; -} - - -int CV_ImgWarpBaseTestImpl::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - return code; -} - - -void CV_ImgWarpBaseTestImpl::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( CV_MAT_DEPTH(type) == CV_32F ) - { - *low = cvScalarAll(-10.); - *high = cvScalarAll(10); - } -} - - -void CV_ImgWarpBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 3; - int cn = cvTsRandInt(rng) % 3 + 1; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : CV_32F; - cn += cn == 2; - - types[INPUT][0] = types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(depth, cn); - if( test_array[INPUT].size() > 1 ) - types[INPUT][1] = cvTsRandInt(rng) & 1 ? CV_32FC1 : CV_64FC1; - - interpolation = cvTsRandInt(rng) % max_interpolation; -} - - -void CV_ImgWarpBaseTestImpl::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i != INPUT || j != 0 ) - CvArrTest::fill_array( test_case_idx, i, j, arr ); -} - -int CV_ImgWarpBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - CvMat* img = &test_mat[INPUT][0]; - int i, j, cols = img->cols; - int type = CV_MAT_TYPE(img->type), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); - double scale = depth == CV_16U ? 1000. : 255.*0.5; - double space_scale = spatial_scale_decimate; - float* buffer; - - if( code <= 0 ) - return code; - - if( test_mat[INPUT_OUTPUT][0].cols >= img->cols && - test_mat[INPUT_OUTPUT][0].rows >= img->rows ) - space_scale = spatial_scale_zoom; - - buffer = (float*)cvAlloc( img->cols*cn*sizeof(buffer[0]) ); - - for( i = 0; i < img->rows; i++ ) - { - uchar* ptr = img->data.ptr + i*img->step; - switch( cn ) - { - case 1: - for( j = 0; j < cols; j++ ) - buffer[j] = (float)((sin((i+1)*space_scale)*sin((j+1)*space_scale)+1.)*scale); - break; - case 2: - for( j = 0; j < cols; j++ ) - { - buffer[j*2] = (float)((sin((i+1)*space_scale)+1.)*scale); - buffer[j*2+1] = (float)((sin((i+j)*space_scale)+1.)*scale); - } - break; - case 3: - for( j = 0; j < cols; j++ ) - { - buffer[j*3] = (float)((sin((i+1)*space_scale)+1.)*scale); - buffer[j*3+1] = (float)((sin(j*space_scale)+1.)*scale); - buffer[j*3+2] = (float)((sin((i+j)*space_scale)+1.)*scale); - } - break; - case 4: - for( j = 0; j < cols; j++ ) - { - buffer[j*4] = (float)((sin((i+1)*space_scale)+1.)*scale); - buffer[j*4+1] = (float)((sin(j*space_scale)+1.)*scale); - buffer[j*4+2] = (float)((sin((i+j)*space_scale)+1.)*scale); - buffer[j*4+3] = (float)((sin((i-j)*space_scale)+1.)*scale); - } - break; - default: - assert(0); - } - - /*switch( depth ) - { - case CV_8U: - for( j = 0; j < cols*cn; j++ ) - ptr[j] = (uchar)cvRound(buffer[j]); - break; - case CV_16U: - for( j = 0; j < cols*cn; j++ ) - ((ushort*)ptr)[j] = (ushort)cvRound(buffer[j]); - break; - case CV_32F: - for( j = 0; j < cols*cn; j++ ) - ((float*)ptr)[j] = (float)buffer[j]; - break; - default: - assert(0); - }*/ - cv::Mat src(1, cols*cn, CV_32F, buffer); - cv::Mat dst(1, cols*cn, depth, ptr); - src.convertTo(dst, dst.type()); - } - - cvFree( &buffer ); - - return code; -} - -CV_ImgWarpBaseTestImpl imgwarp_base( "warp", "", false ); - - -class CV_ImgWarpBaseTest : public CV_ImgWarpBaseTestImpl -{ -public: - CV_ImgWarpBaseTest( const char* test_name, const char* test_funcs, bool warp_matrix ); -}; - - -CV_ImgWarpBaseTest::CV_ImgWarpBaseTest( const char* test_name, const char* test_funcs, bool warp_matrix ) - : CV_ImgWarpBaseTestImpl( test_name, test_funcs, warp_matrix ) -{ - size_list = whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -///////////////////////// - -class CV_ResizeTest : public CV_ImgWarpBaseTest -{ -public: - CV_ResizeTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_ResizeTest::CV_ResizeTest() - : CV_ImgWarpBaseTest( "warp-resize", "cvResize", false ) -{ - default_timing_param_names = imgwarp_resize_param_names; -} - - -int CV_ResizeTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_real_list( fs, "coeff", imgwarp_resize_coeffs, CV_DIM(imgwarp_resize_coeffs) ); - write_string_list( fs, "method", imgwarp_resize_methods ); - } - - return code; -} - - -void CV_ResizeTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize sz; - - sz.width = (cvTsRandInt(rng) % sizes[INPUT][0].width) + 1; - sz.height = (cvTsRandInt(rng) % sizes[INPUT][0].height) + 1; - - if( cvTsRandInt(rng) & 1 ) - { - int xfactor = cvTsRandInt(rng) % 10 + 1; - int yfactor = cvTsRandInt(rng) % 10 + 1; - - if( cvTsRandInt(rng) & 1 ) - yfactor = xfactor; - - sz.width = sizes[INPUT][0].width / xfactor; - sz.width = MAX(sz.width,1); - sz.height = sizes[INPUT][0].height / yfactor; - sz.height = MAX(sz.height,1); - sizes[INPUT][0].width = sz.width * xfactor; - sizes[INPUT][0].height = sz.height * yfactor; - } - - if( cvTsRandInt(rng) & 1 ) - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sz; - else - { - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sizes[INPUT][0]; - sizes[INPUT][0] = sz; - } - if( interpolation == 4 && - (MIN(sizes[INPUT][0].width,sizes[INPUT_OUTPUT][0].width) < 4 || - MIN(sizes[INPUT][0].height,sizes[INPUT_OUTPUT][0].height) < 4)) - interpolation = 2; -} - - -void CV_ResizeTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* method_str = cvReadString( find_timing_param( "method" ), "linear" ); - double coeff = cvReadReal( find_timing_param( "coeff" ), 1. ); - CvSize size = sizes[INPUT][0]; - - size.width = cvRound(size.width*coeff); - size.height = cvRound(size.height*coeff); - sizes[INPUT_OUTPUT][0] = whole_sizes[INPUT_OUTPUT][0] = size; - - interpolation = strcmp( method_str, "nearest" ) == 0 ? CV_INTER_NN : - strcmp( method_str, "linear" ) == 0 ? CV_INTER_LINEAR : - strcmp( method_str, "cubic" ) == 0 ? CV_INTER_CUBIC : CV_INTER_AREA; -} - - -void CV_ResizeTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "coeff=%.3f,", cvReadReal( find_timing_param( "coeff" ), 1. ) ); - ptr += strlen(ptr); - sprintf( ptr, "method=%s,", cvReadString( find_timing_param( "method" ), "linear" ) ); - ptr += strlen(ptr); - params_left -= 2; - - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_ResizeTest::run_func() -{ - cvResize( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], interpolation ); -} - - -double CV_ResizeTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 1e-1; -} - - -void CV_ResizeTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - int i, j, k; - CvMat* x_idx = cvCreateMat( 1, dst->cols, CV_32SC1 ); - CvMat* y_idx = cvCreateMat( 1, dst->rows, CV_32SC1 ); - int* x_tab = x_idx->data.i; - int elem_size = CV_ELEM_SIZE(src->type); - int drows = dst->rows, dcols = dst->cols; - - if( interpolation == CV_INTER_NN ) - { - for( j = 0; j < dcols; j++ ) - { - int t = (j*src->cols*2 + MIN(src->cols,dcols) - 1)/(dcols*2); - t -= t >= src->cols; - x_idx->data.i[j] = t*elem_size; - } - - for( j = 0; j < drows; j++ ) - { - int t = (j*src->rows*2 + MIN(src->rows,drows) - 1)/(drows*2); - t -= t >= src->rows; - y_idx->data.i[j] = t; - } - } - else - { - double scale_x = (double)src->cols/dcols; - double scale_y = (double)src->rows/drows; - - for( j = 0; j < dcols; j++ ) - { - double f = ((j+0.5)*scale_x - 0.5); - i = cvRound(f); - x_idx->data.i[j] = (i < 0 ? 0 : i >= src->cols ? src->cols - 1 : i)*elem_size; - } - - for( j = 0; j < drows; j++ ) - { - double f = ((j+0.5)*scale_y - 0.5); - i = cvRound(f); - y_idx->data.i[j] = i < 0 ? 0 : i >= src->rows ? src->rows - 1 : i; - } - } - - for( i = 0; i < drows; i++ ) - { - uchar* dptr = dst->data.ptr + dst->step*i; - const uchar* sptr0 = src->data.ptr + src->step*y_idx->data.i[i]; - - for( j = 0; j < dcols; j++, dptr += elem_size ) - { - const uchar* sptr = sptr0 + x_tab[j]; - for( k = 0; k < elem_size; k++ ) - dptr[k] = sptr[k]; - } - } - - cvReleaseMat( &x_idx ); - cvReleaseMat( &y_idx ); -} - -CV_ResizeTest warp_resize_test; - - -///////////////////////// - -void cvTsRemap( const CvMat* src, CvMat* dst, - const CvMat* mapx, const CvMat* mapy, - CvMat* mask, int interpolation=CV_INTER_LINEAR ) -{ - int x, y, k; - int drows = dst->rows, dcols = dst->cols; - int srows = src->rows, scols = src->cols; - uchar* sptr0 = src->data.ptr; - int depth = CV_MAT_DEPTH(src->type), cn = CV_MAT_CN(src->type); - int elem_size = CV_ELEM_SIZE(src->type); - int step = src->step / CV_ELEM_SIZE(depth); - int delta; - - if( interpolation != CV_INTER_CUBIC ) - { - delta = 0; - scols -= 1; srows -= 1; - } - else - { - delta = 1; - scols = MAX(scols - 3, 0); - srows = MAX(srows - 3, 0); - } - - int scols1 = MAX(scols - 2, 0); - int srows1 = MAX(srows - 2, 0); - - if( mask ) - cvTsZero(mask); - - for( y = 0; y < drows; y++ ) - { - uchar* dptr = dst->data.ptr + dst->step*y; - const float* mx = (const float*)(mapx->data.ptr + mapx->step*y); - const float* my = (const float*)(mapy->data.ptr + mapy->step*y); - uchar* m = mask ? mask->data.ptr + mask->step*y : 0; - - for( x = 0; x < dcols; x++, dptr += elem_size ) - { - float xs = mx[x]; - float ys = my[x]; - int ixs = cvFloor(xs); - int iys = cvFloor(ys); - - if( (unsigned)(ixs - delta - 1) >= (unsigned)scols1 || - (unsigned)(iys - delta - 1) >= (unsigned)srows1 ) - { - if( m ) - m[x] = 1; - if( (unsigned)(ixs - delta) >= (unsigned)scols || - (unsigned)(iys - delta) >= (unsigned)srows ) - continue; - } - - xs -= ixs; - ys -= iys; - - switch( depth ) - { - case CV_8U: - { - const uchar* sptr = sptr0 + iys*step + ixs*cn; - for( k = 0; k < cn; k++ ) - { - float v00 = sptr[k]; - float v01 = sptr[cn + k]; - float v10 = sptr[step + k]; - float v11 = sptr[step + cn + k]; - - v00 = v00 + xs*(v01 - v00); - v10 = v10 + xs*(v11 - v10); - v00 = v00 + ys*(v10 - v00); - dptr[k] = (uchar)cvRound(v00); - } - } - break; - case CV_16U: - { - const ushort* sptr = (const ushort*)sptr0 + iys*step + ixs*cn; - for( k = 0; k < cn; k++ ) - { - float v00 = sptr[k]; - float v01 = sptr[cn + k]; - float v10 = sptr[step + k]; - float v11 = sptr[step + cn + k]; - - v00 = v00 + xs*(v01 - v00); - v10 = v10 + xs*(v11 - v10); - v00 = v00 + ys*(v10 - v00); - ((ushort*)dptr)[k] = (ushort)cvRound(v00); - } - } - break; - case CV_32F: - { - const float* sptr = (const float*)sptr0 + iys*step + ixs*cn; - for( k = 0; k < cn; k++ ) - { - float v00 = sptr[k]; - float v01 = sptr[cn + k]; - float v10 = sptr[step + k]; - float v11 = sptr[step + cn + k]; - - v00 = v00 + xs*(v01 - v00); - v10 = v10 + xs*(v11 - v10); - v00 = v00 + ys*(v10 - v00); - ((float*)dptr)[k] = (float)v00; - } - } - break; - default: - assert(0); - } - } - } -} - -///////////////////////// - -class CV_WarpAffineTest : public CV_ImgWarpBaseTest -{ -public: - CV_WarpAffineTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_WarpAffineTest::CV_WarpAffineTest() - : CV_ImgWarpBaseTest( "warp-affine", "cvWarpAffine", true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - spatial_scale_decimate = spatial_scale_zoom; - - default_timing_param_names = imgwarp_affine_param_names; -} - - -int CV_WarpAffineTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "rotate_scale", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; imgwarp_affine_rotate_scale[i][0] >= 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteRawData( fs, imgwarp_affine_rotate_scale[i], 4, "d" ); - cvEndWriteStruct(fs); - } - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_WarpAffineTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize sz = sizes[INPUT][0]; - // run for the second time to get output of a different size - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sz; - sizes[INPUT][1] = cvSize( 3, 2 ); - sizes[TEMP][0] = sizes[TEMP][1] = sizes[INPUT_OUTPUT][0]; - types[TEMP][0] = types[TEMP][1] = CV_32FC1; -} - - -void CV_WarpAffineTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - - sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,2); - sizes[TEMP][0] = whole_sizes[TEMP][0] = - sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); - types[INPUT][1] = CV_64FC1; - - interpolation = CV_INTER_LINEAR; -} - - -void CV_WarpAffineTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - double coeffs[4]; - const CvFileNode* node = find_timing_param( "rotate_scale" ); - assert( node && CV_NODE_IS_SEQ(node->tag) ); - cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); - - sprintf( ptr, "fx=%.2f,fy=%.2f,angle=%.1fdeg,scale=%.1f,", coeffs[0], coeffs[1], coeffs[2], coeffs[3] ); - ptr += strlen(ptr); - params_left -= 4; - - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_WarpAffineTest::run_func() -{ - cvWarpAffine( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - &test_mat[INPUT][1], interpolation ); -} - - -double CV_WarpAffineTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_WarpAffineTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const CvMat* src = &test_mat[INPUT][0]; - const CvMat* dst = &test_mat[INPUT_OUTPUT][0]; - CvMat* mat = &test_mat[INPUT][1]; - CvPoint2D32f center; - double scale, angle; - - if( code <= 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - double buf[6]; - CvMat tmp = cvMat( 2, 3, mat->type, buf ); - - center.x = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->cols); - center.y = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->rows); - angle = cvTsRandReal(rng)*360; - scale = ((double)dst->rows/src->rows + (double)dst->cols/src->cols)*0.5; - cv2DRotationMatrix( center, angle, scale, mat ); - cvRandArr( rng, &tmp, CV_RAND_NORMAL, cvScalarAll(1.), cvScalarAll(0.01) ); - cvMaxS( &tmp, 0.9, &tmp ); - cvMinS( &tmp, 1.1, &tmp ); - cvMul( &tmp, mat, mat, 1. ); - } - else - { - double coeffs[4]; - const CvFileNode* node = find_timing_param( "rotate_scale" ); - - assert( node && CV_NODE_IS_SEQ(node->tag) ); - cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); - - center.x = (float)(coeffs[0]*src->cols); - center.y = (float)(coeffs[1]*src->rows); - angle = coeffs[2]; - scale = coeffs[3]; - cv2DRotationMatrix( center, angle, scale, mat ); - } - - return code; -} - - -void CV_WarpAffineTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; - CvMat* mapx = &test_mat[TEMP][0]; - CvMat* mapy = &test_mat[TEMP][1]; - int x, y; - double m[6], tm[6]; - CvMat srcAb = cvMat(2, 3, CV_64FC1, tm ), A, b, invA, invAb, dstAb = cvMat( 2, 3, CV_64FC1, m ); - - //cvInvert( &tM, &M, CV_LU ); - // [R|t] -> [R^-1 | -(R^-1)*t] - cvTsConvert( &test_mat[INPUT][1], &srcAb ); - cvGetCols( &srcAb, &A, 0, 2 ); - cvGetCol( &srcAb, &b, 2 ); - cvGetCols( &dstAb, &invA, 0, 2 ); - cvGetCol( &dstAb, &invAb, 2 ); - cvInvert( &A, &invA, CV_SVD ); - cvGEMM( &invA, &b, -1, 0, 0, &invAb ); - - for( y = 0; y < dst->rows; y++ ) - { - float* mx = (float*)(mapx->data.ptr + y*mapx->step); - float* my = (float*)(mapy->data.ptr + y*mapy->step); - - for( x = 0; x < dst->cols; x++ ) - { - mx[x] = (float)(x*m[0] + y*m[1] + m[2]); - my[x] = (float)(x*m[3] + y*m[4] + m[5]); - } - } - - CvMat* mask = cvCreateMat( dst->rows, dst->cols, CV_8U ); - cvTsRemap( src, dst, mapx, mapy, mask ); - cvTsZero( dst, mask ); - cvTsZero( dst0, mask ); - cvReleaseMat( &mask ); -} - - -CV_WarpAffineTest warp_affine_test; - - - -///////////////////////// - -class CV_WarpPerspectiveTest : public CV_ImgWarpBaseTest -{ -public: - CV_WarpPerspectiveTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_WarpPerspectiveTest::CV_WarpPerspectiveTest() - : CV_ImgWarpBaseTest( "warp-perspective", "cvWarpPerspective", true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - spatial_scale_decimate = spatial_scale_zoom; - default_timing_param_names = imgwarp_perspective_param_names; -} - - -int CV_WarpPerspectiveTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "shift_vtx", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; imgwarp_perspective_shift_vtx[i][0] >= 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteRawData( fs, imgwarp_perspective_shift_vtx[i], 8, "d" ); - cvEndWriteStruct(fs); - } - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_WarpPerspectiveTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize sz = sizes[INPUT][0]; - // run for the second time to get output of a different size - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sz; - sizes[INPUT][1] = cvSize( 3, 3 ); - - sizes[TEMP][0] = sizes[TEMP][1] = sizes[INPUT_OUTPUT][0]; - types[TEMP][0] = types[TEMP][1] = CV_32FC1; -} - - -void CV_WarpPerspectiveTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - - sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,3); - sizes[TEMP][0] = whole_sizes[TEMP][0] = - sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); - types[INPUT][1] = CV_64FC1; - - interpolation = CV_INTER_LINEAR; -} - - -void CV_WarpPerspectiveTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_WarpPerspectiveTest::run_func() -{ - cvWarpPerspective( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - &test_mat[INPUT][1], interpolation ); -} - - -double CV_WarpPerspectiveTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_WarpPerspectiveTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const CvMat* src = &test_mat[INPUT][0]; - const CvMat* dst = &test_mat[INPUT_OUTPUT][0]; - CvMat* mat = &test_mat[INPUT][1]; - CvPoint2D32f s[4], d[4]; - int i; - - if( code <= 0 ) - return code; - - s[0] = cvPoint2D32f(0,0); - d[0] = cvPoint2D32f(0,0); - s[1] = cvPoint2D32f(src->cols-1,0); - d[1] = cvPoint2D32f(dst->cols-1,0); - s[2] = cvPoint2D32f(src->cols-1,src->rows-1); - d[2] = cvPoint2D32f(dst->cols-1,dst->rows-1); - s[3] = cvPoint2D32f(0,src->rows-1); - d[3] = cvPoint2D32f(0,dst->rows-1); - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - float buf[16]; - CvMat tmp = cvMat( 1, 16, CV_32FC1, buf ); - - cvRandArr( rng, &tmp, CV_RAND_NORMAL, cvScalarAll(0.), cvScalarAll(0.1) ); - - for( i = 0; i < 4; i++ ) - { - s[i].x += buf[i*4]*src->cols/2; - s[i].y += buf[i*4+1]*src->rows/2; - d[i].x += buf[i*4+2]*dst->cols/2; - d[i].y += buf[i*4+3]*dst->rows/2; - } - } - else - { - double coeffs[8]; - const CvFileNode* node = find_timing_param( "shift_vtx" ); - - assert( node && CV_NODE_IS_SEQ(node->tag) ); - cvReadRawData( ts->get_file_storage(), node, coeffs, "8d" ); - - for( i = 0; i < 4; i++ ) - { - d[i].x += (float)(coeffs[i*2]*src->cols*(i == 0 || i == 3 ? 1 : -1)); - d[i].y += (float)(coeffs[i*2+1]*src->rows*(i == 0 || i == 1 ? 1 : -1)); - } - } - - cvWarpPerspectiveQMatrix( s, d, mat ); - return code; -} - - -void CV_WarpPerspectiveTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; - CvMat* mapx = &test_mat[TEMP][0]; - CvMat* mapy = &test_mat[TEMP][1]; - int x, y; - double m[9], tm[9]; - CvMat srcM = cvMat(3, 3, CV_64FC1, tm ), dstM = cvMat( 3, 3, CV_64FC1, m ); - - //cvInvert( &tM, &M, CV_LU ); - // [R|t] -> [R^-1 | -(R^-1)*t] - cvTsConvert( &test_mat[INPUT][1], &srcM ); - cvInvert( &srcM, &dstM, CV_SVD ); - - for( y = 0; y < dst->rows; y++ ) - { - float* mx = (float*)(mapx->data.ptr + y*mapx->step); - float* my = (float*)(mapy->data.ptr + y*mapy->step); - - for( x = 0; x < dst->cols; x++ ) - { - double xs = x*m[0] + y*m[1] + m[2]; - double ys = x*m[3] + y*m[4] + m[5]; - double ds = x*m[6] + y*m[7] + m[8]; - - ds = ds ? 1./ds : 0; - xs *= ds; - ys *= ds; - - mx[x] = (float)xs; - my[x] = (float)ys; - } - } - - CvMat* mask = cvCreateMat( dst->rows, dst->cols, CV_8U ); - cvTsRemap( src, dst, mapx, mapy, mask ); - cvTsZero( dst, mask ); - cvTsZero( dst0, mask ); - cvReleaseMat( &mask ); -} - - -CV_WarpPerspectiveTest warp_perspective_test; - - - -///////////////////////// - -void cvTsInitUndistortMap( const CvMat* _a0, const CvMat* _k0, CvMat* _mapx, CvMat* _mapy ) -{ - CvMat* mapx = cvCreateMat(_mapx->rows,_mapx->cols,CV_32F); - CvMat* mapy = cvCreateMat(_mapx->rows,_mapx->cols,CV_32F); - - int u, v; - double a[9], k[5]={0,0,0,0,0}; - CvMat _a = cvMat(3, 3, CV_64F, a); - CvMat _k = cvMat(_k0->rows,_k0->cols, - CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); - double fx, fy, cx, cy, ifx, ify, cxn, cyn; - - cvTsConvert( _a0, &_a ); - cvTsConvert( _k0, &_k ); - fx = a[0]; fy = a[4]; cx = a[2]; cy = a[5]; - ifx = 1./fx; ify = 1./fy; - cxn = cx;//(mapy->cols - 1)*0.5; - cyn = cy;//(mapy->rows - 1)*0.5; - - for( v = 0; v < mapy->rows; v++ ) - { - float* mx = (float*)(mapx->data.ptr + v*mapx->step); - float* my = (float*)(mapy->data.ptr + v*mapy->step); - - for( u = 0; u < mapy->cols; u++ ) - { - double x = (u - cxn)*ifx; - double y = (v - cyn)*ify; - double x2 = x*x, y2 = y*y; - double r2 = x2 + y2; - double cdist = 1 + (k[0] + (k[1] + k[4]*r2)*r2)*r2; - double x1 = x*cdist + k[2]*2*x*y + k[3]*(r2 + 2*x2); - double y1 = y*cdist + k[3]*2*x*y + k[2]*(r2 + 2*y2); - - my[u] = (float)(y1*fy + cy); - mx[u] = (float)(x1*fx + cx); - } - } - - if (_mapy) - { - cvCopy(mapy,_mapy); - cvCopy(mapx,_mapx); - } - else - { - for (int i=0;irows;i++) - { - float* _mx = (float*)(_mapx->data.ptr + _mapx->step*i); - float* _my = (float*)(_mapx->data.ptr + _mapx->step*i); - for (int j=0;jcols;j++) - { - _mx[2*j] = mapx->data.fl[j+i*mapx->cols]; - _my[2*j+1] = mapy->data.fl[j+i*mapy->cols]; - } - } - } - cvReleaseMat(&mapx); - cvReleaseMat(&mapy); -} - - -static double remap_undistort_params[] = { 0.5, 0.5, 0.5, 0.5, 0.01, -0.01, 0.001, -0.001 }; - -class CV_RemapTest : public CV_ImgWarpBaseTest -{ -public: - CV_RemapTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_RemapTest::CV_RemapTest() - : CV_ImgWarpBaseTest( "warp-remap", "cvRemap", false ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - - spatial_scale_decimate = spatial_scale_zoom; - //default_timing_param_names = imgwarp_perspective_param_names; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_RemapTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; i < 8; i++ ) - cvWriteReal( fs, 0, remap_undistort_params[i] ); - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_RemapTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[INPUT][1] = types[INPUT][2] = CV_32FC1; - interpolation = CV_INTER_LINEAR; -} - - -void CV_RemapTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i != INPUT ) - CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); -} - -void CV_RemapTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT][1] = types[INPUT][2] = CV_32FC1; - interpolation = CV_INTER_LINEAR; -} - - -void CV_RemapTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_RemapTest::run_func() -{ - cvRemap( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - test_array[INPUT][1], test_array[INPUT][2], interpolation ); -} - - -double CV_RemapTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_RemapTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const CvMat* src = &test_mat[INPUT][0]; - double a[9] = {0,0,0,0,0,0,0,0,1}, k[4]; - CvMat _a = cvMat( 3, 3, CV_64F, a ); - CvMat _k = cvMat( 4, 1, CV_64F, k ); - double sz = MAX(src->rows, src->cols); - - if( code <= 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; - a[2] = (src->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[5] = (src->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); - a[4] = aspect_ratio*a[0]; - k[0] = cvTsRandReal(rng)*0.06 - 0.03; - k[1] = cvTsRandReal(rng)*0.06 - 0.03; - if( k[0]*k[1] > 0 ) - k[1] = -k[1]; - k[2] = cvTsRandReal(rng)*0.004 - 0.002; - k[3] = cvTsRandReal(rng)*0.004 - 0.002; - } - else - { - int i; - a[2] = (src->cols - 1)*remap_undistort_params[0]; - a[5] = (src->rows - 1)*remap_undistort_params[1]; - a[0] = sz/remap_undistort_params[2]; - a[4] = sz/remap_undistort_params[3]; - for( i = 0; i < 4; i++ ) - k[i] = remap_undistort_params[i+4]; - } - - cvTsInitUndistortMap( &_a, &_k, &test_mat[INPUT][1], &test_mat[INPUT][2] ); - return code; -} - - -void CV_RemapTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; - CvMat* mask = cvCreateMat( dst->rows, dst->cols, CV_8U ); - cvTsRemap( &test_mat[INPUT][0], dst, - &test_mat[INPUT][1], &test_mat[INPUT][2], - mask, interpolation ); - cvTsZero( dst, mask ); - cvTsZero( dst0, mask ); - cvReleaseMat( &mask ); -} - - -CV_RemapTest remap_test; - - -////////////////////////////// undistort ///////////////////////////////// - -class CV_UndistortTest : public CV_ImgWarpBaseTest -{ -public: - CV_UndistortTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - -private: - bool useCPlus; - cv::Mat input0; - cv::Mat input1; - cv::Mat input2; - cv::Mat input_new_cam; - cv::Mat input_output; - - bool zero_new_cam; - bool zero_distortion; -}; - - -CV_UndistortTest::CV_UndistortTest() - : CV_ImgWarpBaseTest( "warp-undistort", "cvUndistort2", false ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - - spatial_scale_decimate = spatial_scale_zoom; - //default_timing_param_names = imgwarp_perspective_param_names; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_UndistortTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; i < 8; i++ ) - cvWriteReal( fs, 0, remap_undistort_params[i] ); - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_UndistortTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int type = types[INPUT][0]; - type = CV_MAKETYPE( CV_8U, CV_MAT_CN(type) ); - types[INPUT][0] = types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = type; - types[INPUT][1] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][2] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - sizes[INPUT][1] = cvSize(3,3); - sizes[INPUT][2] = cvTsRandInt(rng)%2 ? cvSize(4,1) : cvSize(1,4); - types[INPUT][3] = types[INPUT][1]; - sizes[INPUT][3] = sizes[INPUT][1]; - interpolation = CV_INTER_LINEAR; -} - - -void CV_UndistortTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i != INPUT ) - CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); -} - -void CV_UndistortTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT][1] = types[INPUT][2] = CV_32FC1; - interpolation = CV_INTER_LINEAR; -} - - -void CV_UndistortTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_UndistortTest::run_func() -{ - if (!useCPlus) - { - cvUndistort2( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - &test_mat[INPUT][1], &test_mat[INPUT][2] ); - } - else - { - if (zero_distortion) - { - cv::undistort(input0,input_output,input1,cv::Mat()); - } - else - { - cv::undistort(input0,input_output,input1,input2); - } - } -} - - -double CV_UndistortTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_UndistortTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - - const CvMat* src = &test_mat[INPUT][0]; - double k[4], a[9] = {0,0,0,0,0,0,0,0,1}; - double sz = MAX(src->rows, src->cols); - - double new_cam[9] = {0,0,0,0,0,0,0,0,1}; - CvMat _new_cam = cvMat(test_mat[INPUT][3].rows,test_mat[INPUT][3].cols,CV_64F,new_cam); - CvMat* _new_cam0 = &test_mat[INPUT][3]; - - CvMat* _a0 = &test_mat[INPUT][1], *_k0 = &test_mat[INPUT][2]; - CvMat _a = cvMat(3,3,CV_64F,a); - CvMat _k = cvMat(_k0->rows,_k0->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); - - if( code <= 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; - a[2] = (src->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[5] = (src->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); - a[4] = aspect_ratio*a[0]; - k[0] = cvTsRandReal(rng)*0.06 - 0.03; - k[1] = cvTsRandReal(rng)*0.06 - 0.03; - if( k[0]*k[1] > 0 ) - k[1] = -k[1]; - if( cvTsRandInt(rng)%4 != 0 ) - { - k[2] = cvTsRandReal(rng)*0.004 - 0.002; - k[3] = cvTsRandReal(rng)*0.004 - 0.002; - } - else - k[2] = k[3] = 0; - - new_cam[0] = a[0] + (cvTsRandReal(rng) - (double)0.5)*0.2*a[0]; //10% - new_cam[4] = a[4] + (cvTsRandReal(rng) - (double)0.5)*0.2*a[4]; //10% - new_cam[2] = a[2] + (cvTsRandReal(rng) - (double)0.5)*0.3*test_mat[INPUT][0].rows; //15% - new_cam[5] = a[5] + (cvTsRandReal(rng) - (double)0.5)*0.3*test_mat[INPUT][0].cols; //15% - } - else - { - int i; - a[2] = (src->cols - 1)*remap_undistort_params[0]; - a[5] = (src->rows - 1)*remap_undistort_params[1]; - a[0] = sz/remap_undistort_params[2]; - a[4] = sz/remap_undistort_params[3]; - for( i = 0; i < 4; i++ ) - k[i] = remap_undistort_params[i+4]; - } - - cvTsConvert( &_a, _a0 ); - - - zero_distortion = (cvRandInt(rng)%2) == 0 ? false : true; - cvTsConvert( &_k, _k0 ); - - zero_new_cam = (cvRandInt(rng)%2) == 0 ? false : true; - cvTsConvert( &_new_cam, _new_cam0 ); - - - //Testing C++ code - useCPlus = ((cvTsRandInt(rng) % 2)!=0); - if (useCPlus) - { - input0 = &test_mat[INPUT][0]; - input1 = &test_mat[INPUT][1]; - input2 = &test_mat[INPUT][2]; - input_new_cam = &test_mat[INPUT][3]; - } - - return code; -} - - -void CV_UndistortTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - if (useCPlus) - { - CvMat result = input_output; - CvMat* test_input_output = &test_mat[INPUT_OUTPUT][0]; - cvTsConvert(&result,test_input_output); - } - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* dst0 = &test_mat[INPUT_OUTPUT][0]; - CvMat* mapx = cvCreateMat( dst->rows, dst->cols, CV_32FC1 ); - CvMat* mapy = cvCreateMat( dst->rows, dst->cols, CV_32FC1 ); - cvTsInitUndistortMap( &test_mat[INPUT][1], &test_mat[INPUT][2], - mapx, mapy ); - CvMat* mask = cvCreateMat( dst->rows, dst->cols, CV_8U ); - cvTsRemap( src, dst, mapx, mapy, mask, interpolation ); - cvTsZero( dst, mask ); - cvTsZero( dst0, mask ); - - cvReleaseMat( &mapx ); - cvReleaseMat( &mapy ); - cvReleaseMat( &mask ); -} - - -CV_UndistortTest undistort_test; - - - -class CV_UndistortMapTest : public CvArrTest -{ -public: - CV_UndistortMapTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -private: - bool dualChannel; -}; - - -CV_UndistortMapTest::CV_UndistortMapTest() - : CvArrTest( "warp-undistort-map", "cvInitUndistortMap", "" ) -{ - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - element_wise_relative_error = false; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_UndistortMapTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "params", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; i < 8; i++ ) - cvWriteReal( fs, 0, remap_undistort_params[i] ); - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_UndistortMapTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - - - - CvSize sz = sizes[OUTPUT][0]; - types[INPUT][0] = types[INPUT][1] = depth; - dualChannel = cvTsRandInt(rng)%2 == 0; - types[OUTPUT][0] = types[OUTPUT][1] = - types[REF_OUTPUT][0] = types[REF_OUTPUT][1] = dualChannel ? CV_32FC2 : CV_32F; - sizes[INPUT][0] = cvSize(3,3); - sizes[INPUT][1] = cvTsRandInt(rng)%2 ? cvSize(4,1) : cvSize(1,4); - - sz.width = MAX(sz.width,16); - sz.height = MAX(sz.height,16); - sizes[OUTPUT][0] = sizes[OUTPUT][1] = - sizes[REF_OUTPUT][0] = sizes[REF_OUTPUT][1] = sz; -} - - -void CV_UndistortMapTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i != INPUT ) - CvArrTest::fill_array( test_case_idx, i, j, arr ); -} - -void CV_UndistortMapTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); -} - - -void CV_UndistortMapTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_UndistortMapTest::run_func() -{ - if (!dualChannel ) - cvInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], - test_array[OUTPUT][0], test_array[OUTPUT][1] ); - else - cvInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], - test_array[OUTPUT][0], 0 ); - -} - - -double CV_UndistortMapTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 1e-3; -} - - -int CV_UndistortMapTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CvArrTest::prepare_test_case( test_case_idx ); - const CvMat* mapx = &test_mat[OUTPUT][0]; - double k[4], a[9] = {0,0,0,0,0,0,0,0,1}; - double sz = MAX(mapx->rows, mapx->cols); - CvMat* _a0 = &test_mat[INPUT][0], *_k0 = &test_mat[INPUT][1]; - CvMat _a = cvMat(3,3,CV_64F,a); - CvMat _k = cvMat(_k0->rows,_k0->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(_k0->type)),k); - - if( code <= 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; - a[2] = (mapx->cols - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[5] = (mapx->rows - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); - a[4] = aspect_ratio*a[0]; - k[0] = cvTsRandReal(rng)*0.06 - 0.03; - k[1] = cvTsRandReal(rng)*0.06 - 0.03; - if( k[0]*k[1] > 0 ) - k[1] = -k[1]; - k[2] = cvTsRandReal(rng)*0.004 - 0.002; - k[3] = cvTsRandReal(rng)*0.004 - 0.002; - } - else - { - int i; - a[2] = (mapx->cols - 1)*remap_undistort_params[0]; - a[5] = (mapx->rows - 1)*remap_undistort_params[1]; - a[0] = sz/remap_undistort_params[2]; - a[4] = sz/remap_undistort_params[3]; - for( i = 0; i < 4; i++ ) - k[i] = remap_undistort_params[i+4]; - } - - cvTsConvert( &_a, _a0 ); - cvTsConvert( &_k, _k0 ); - - if (dualChannel) - { - cvZero(&test_mat[REF_OUTPUT][1]); - cvZero(&test_mat[OUTPUT][1]); - } - - return code; -} - - -void CV_UndistortMapTest::prepare_to_validation( int ) -{ - if (!dualChannel ) - cvTsInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], - &test_mat[REF_OUTPUT][0], &test_mat[REF_OUTPUT][1] ); - else - cvTsInitUndistortMap( &test_mat[INPUT][0], &test_mat[INPUT][1], - &test_mat[REF_OUTPUT][0], 0 ); -} - - -CV_UndistortMapTest undistortmap_test; - - - -////////////////////////////// GetRectSubPix ///////////////////////////////// - -static const CvSize rectsubpix_sizes[] = {{11, 11}, {21,21}, {41,41},{-1,-1}}; - -static void -cvTsGetQuadrangeSubPix( const CvMat* src, CvMat* dst, double* a ) -{ - int y, x, k, cn; - int sstep = src->step / sizeof(float); - int scols = src->cols, srows = src->rows; - - assert( CV_MAT_DEPTH(src->type) == CV_32F && - CV_ARE_TYPES_EQ(src, dst)); - - cn = CV_MAT_CN(dst->type); - - for( y = 0; y < dst->rows; y++ ) - for( x = 0; x < dst->cols; x++ ) - { - float* d = (float*)(dst->data.ptr + y*dst->step) + x*cn; - float sx = (float)(a[0]*x + a[1]*y + a[2]); - float sy = (float)(a[3]*x + a[4]*y + a[5]); - int ix = cvFloor(sx), iy = cvFloor(sy); - int dx = cn, dy = sstep; - const float* s; - sx -= ix; sy -= iy; - - if( (unsigned)ix >= (unsigned)(scols-1) ) - ix = ix < 0 ? 0 : scols - 1, sx = 0, dx = 0; - if( (unsigned)iy >= (unsigned)(srows-1) ) - iy = iy < 0 ? 0 : srows - 1, sy = 0, dy = 0; - - s = src->data.fl + sstep*iy + ix*cn; - for( k = 0; k < cn; k++, s++ ) - { - float t0 = s[0] + sx*(s[dx] - s[0]); - float t1 = s[dy] + sx*(s[dy + dx] - s[dy]); - d[k] = t0 + sy*(t1 - t0); - } - } -} - - -class CV_GetRectSubPixTest : public CV_ImgWarpBaseTest -{ -public: - CV_GetRectSubPixTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - CvPoint2D32f center; - bool test_cpp; -}; - - -CV_GetRectSubPixTest::CV_GetRectSubPixTest() - : CV_ImgWarpBaseTest( "warp-subpix-rect", "cvGetRectSubPix", false ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - spatial_scale_decimate = spatial_scale_zoom; - //default_timing_param_names = imgwarp_perspective_param_names; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; - test_cpp = false; -} - - -int CV_GetRectSubPixTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "rect_size", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; rectsubpix_sizes[i].width > 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteInt( fs, 0, rectsubpix_sizes[i].width ); - cvWriteInt( fs, 0, rectsubpix_sizes[i].height ); - cvEndWriteStruct(fs); - } - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_GetRectSubPixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int src_depth = cvTsRandInt(rng) % 2, dst_depth; - int cn = cvTsRandInt(rng) % 2 ? 3 : 1; - CvSize src_size, dst_size; - - dst_depth = src_depth = src_depth == 0 ? CV_8U : CV_32F; - if( src_depth < CV_32F && cvTsRandInt(rng) % 2 ) - dst_depth = CV_32F; - - types[INPUT][0] = CV_MAKETYPE(src_depth,cn); - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(dst_depth,cn); - - src_size = sizes[INPUT][0]; - dst_size.width = cvRound(sqrt(cvTsRandReal(rng)*src_size.width) + 1); - dst_size.height = cvRound(sqrt(cvTsRandReal(rng)*src_size.height) + 1); - dst_size.width = MIN(dst_size.width,src_size.width); - dst_size.height = MIN(dst_size.width,src_size.height); - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = dst_size; - - center.x = (float)(cvTsRandReal(rng)*src_size.width); - center.y = (float)(cvTsRandReal(rng)*src_size.height); - interpolation = CV_INTER_LINEAR; - - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -void CV_GetRectSubPixTest::fill_array( int test_case_idx, int i, int j, CvMat* arr ) -{ - if( i != INPUT ) - CV_ImgWarpBaseTestImpl::fill_array( test_case_idx, i, j, arr ); -} - -void CV_GetRectSubPixTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - interpolation = CV_INTER_LINEAR; -} - - -void CV_GetRectSubPixTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_GetRectSubPixTest::run_func() -{ - if(!test_cpp) - cvGetRectSubPix( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], center ); - else - { - cv::Mat _out = cv::cvarrToMat(test_array[INPUT_OUTPUT][0]); - cv::getRectSubPix( cv::cvarrToMat(test_array[INPUT][0]), _out.size(), center, _out, _out.type()); - } -} - - -double CV_GetRectSubPixTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int in_depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - int out_depth = CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type); - - return in_depth >= CV_32F ? 1e-3 : out_depth >= CV_32F ? 1e-2 : 1; -} - - -int CV_GetRectSubPixTest::prepare_test_case( int test_case_idx ) -{ - return CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); -} - - -void CV_GetRectSubPixTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src0 = &test_mat[INPUT][0]; - CvMat* dst0 = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* src = src0, *dst = dst0; - int ftype = CV_MAKETYPE(CV_32F,CV_MAT_CN(src0->type)); - double a[] = { 1, 0, center.x - dst->cols*0.5 + 0.5, - 0, 1, center.y - dst->rows*0.5 + 0.5 }; - if( CV_MAT_DEPTH(src->type) != CV_32F ) - { - src = cvCreateMat( src0->rows, src0->cols, ftype ); - cvTsConvert( src0, src ); - } - - if( CV_MAT_DEPTH(dst->type) != CV_32F ) - dst = cvCreateMat( dst0->rows, dst0->cols, ftype ); - - cvTsGetQuadrangeSubPix( src, dst, a ); - - if( dst != dst0 ) - { - cvTsConvert( dst, dst0 ); - cvReleaseMat( &dst ); - } - if( src != src0 ) - cvReleaseMat( &src ); -} - - -CV_GetRectSubPixTest subpix_rect_test; - - -class CV_GetQuadSubPixTest : public CV_ImgWarpBaseTest -{ -public: - CV_GetQuadSubPixTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); -}; - - -CV_GetQuadSubPixTest::CV_GetQuadSubPixTest() - : CV_ImgWarpBaseTest( "warp-subpix-quad", "cvGetQuadSubPix", true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - spatial_scale_decimate = spatial_scale_zoom; - //default_timing_param_names = imgwarp_affine_param_names; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - default_timing_param_names = 0; -} - - -int CV_GetQuadSubPixTest::write_default_params( CvFileStorage* fs ) -{ - int code = CV_ImgWarpBaseTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "rotate_scale", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; imgwarp_affine_rotate_scale[i][0] >= 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteRawData( fs, imgwarp_affine_rotate_scale[i], 4, "d" ); - cvEndWriteStruct(fs); - } - cvEndWriteStruct(fs); - } - - return code; -} - - -void CV_GetQuadSubPixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - int min_size = 4; - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize sz = sizes[INPUT][0], dsz; - CvRNG* rng = ts->get_rng(); - int msz, src_depth = cvTsRandInt(rng) % 2, dst_depth; - int cn = cvTsRandInt(rng) % 2 ? 3 : 1; - - dst_depth = src_depth = src_depth == 0 ? CV_8U : CV_32F; - if( src_depth < CV_32F && cvTsRandInt(rng) % 2 ) - dst_depth = CV_32F; - - types[INPUT][0] = CV_MAKETYPE(src_depth,cn); - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(dst_depth,cn); - - sz.width = MAX(sz.width,min_size); - sz.height = MAX(sz.height,min_size); - sizes[INPUT][0] = sz; - msz = MIN( sz.width, sz.height ); - - dsz.width = cvRound(sqrt(cvTsRandReal(rng)*msz) + 1); - dsz.height = cvRound(sqrt(cvTsRandReal(rng)*msz) + 1); - dsz.width = MIN(dsz.width,msz); - dsz.height = MIN(dsz.width,msz); - dsz.width = MAX(dsz.width,min_size); - dsz.height = MAX(dsz.height,min_size); - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = dsz; - sizes[INPUT][1] = cvSize( 3, 2 ); -} - - -void CV_GetQuadSubPixTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_ImgWarpBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - - sizes[INPUT][1] = whole_sizes[INPUT][1] = cvSize(3,2); - sizes[TEMP][0] = whole_sizes[TEMP][0] = - sizes[TEMP][1] = whole_sizes[TEMP][1] = cvSize(0,0); - types[INPUT][1] = CV_64FC1; - - interpolation = CV_INTER_LINEAR; -} - - -void CV_GetQuadSubPixTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - double coeffs[4]; - const CvFileNode* node = find_timing_param( "rotate_scale" ); - assert( node && CV_NODE_IS_SEQ(node->tag) ); - cvReadRawData( ts->get_file_storage(), node, coeffs, "4d" ); - - sprintf( ptr, "fx=%.2f,fy=%.2f,angle=%.1fdeg,scale=%.1f,", coeffs[0], coeffs[1], coeffs[2], coeffs[3] ); - ptr += strlen(ptr); - params_left -= 4; - - CV_ImgWarpBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CV_GetQuadSubPixTest::run_func() -{ - cvGetQuadrangleSubPix( test_array[INPUT][0], - test_array[INPUT_OUTPUT][0], &test_mat[INPUT][1] ); -} - - -double CV_GetQuadSubPixTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int in_depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - //int out_depth = CV_MAT_DEPTH(test_mat[INPUT_OUTPUT][0].type); - - return in_depth >= CV_32F ? 1e-2 : 4; -} - - -int CV_GetQuadSubPixTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const CvMat* src = &test_mat[INPUT][0]; - CvMat* mat = &test_mat[INPUT][1]; - CvPoint2D32f center; - double scale, angle; - - if( code <= 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - double a[6]; - CvMat A = cvMat( 2, 3, CV_64FC1, a ); - - center.x = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->cols); - center.y = (float)((cvTsRandReal(rng)*1.2 - 0.1)*src->rows); - angle = cvTsRandReal(rng)*360; - scale = cvTsRandReal(rng)*0.2 + 0.9; - - // y = Ax + b -> x = A^-1(y - b) = A^-1*y - A^-1*b - scale = 1./scale; - angle = angle*(CV_PI/180.); - a[0] = a[4] = cos(angle)*scale; - a[1] = sin(angle)*scale; - a[3] = -a[1]; - a[2] = center.x - a[0]*center.x - a[1]*center.y; - a[5] = center.y - a[3]*center.x - a[4]*center.y; - cvTsConvert( &A, mat ); - } - - return code; -} - - -void CV_GetQuadSubPixTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src0 = &test_mat[INPUT][0]; - CvMat* dst0 = &test_mat[REF_INPUT_OUTPUT][0]; - CvMat* src = src0, *dst = dst0; - int ftype = CV_MAKETYPE(CV_32F,CV_MAT_CN(src0->type)); - double a[6], dx = (dst0->cols - 1)*0.5, dy = (dst0->rows - 1)*0.5; - CvMat A = cvMat( 2, 3, CV_64F, a ); - - if( CV_MAT_DEPTH(src->type) != CV_32F ) - { - src = cvCreateMat( src0->rows, src0->cols, ftype ); - cvTsConvert( src0, src ); - } - - if( CV_MAT_DEPTH(dst->type) != CV_32F ) - dst = cvCreateMat( dst0->rows, dst0->cols, ftype ); - - cvTsConvert( &test_mat[INPUT][1], &A ); - a[2] -= a[0]*dx + a[1]*dy; - a[5] -= a[3]*dx + a[4]*dy; - cvTsGetQuadrangeSubPix( src, dst, a ); - - if( dst != dst0 ) - { - cvTsConvert( dst, dst0 ); - cvReleaseMat( &dst ); - } - - if( src != src0 ) - cvReleaseMat( &src ); -} - - -CV_GetQuadSubPixTest warp_subpix_quad_test; - -/* End of file. */ diff --git a/tests/cv/src/akalman.cpp b/tests/cv/src/akalman.cpp deleted file mode 100644 index ac2e58d..0000000 --- a/tests/cv/src/akalman.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_KalmanTest : public CvTest -{ -public: - CV_KalmanTest(); -protected: - void run(int); -}; - - -CV_KalmanTest::CV_KalmanTest(): - CvTest( "kalman", "cvKalmanPredict, cvKalmanCorrect" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_KalmanTest::run( int ) -{ - int code = CvTS::OK; - const int Dim = 7; - const int Steps = 100; - const double max_init = 1; - const double max_noise = 0.1; - - const double EPSILON = 1.000; - CvRNG* rng = ts->get_rng(); - CvKalman* Kalm; - int i, j; - - CvMat* Sample = cvCreateMat(Dim,1,CV_32F); - CvMat* Temp = cvCreateMat(Dim,1,CV_32F); - - Kalm = cvCreateKalman(Dim, Dim); - CvMat Dyn = cvMat(Dim,Dim,CV_32F,Kalm->DynamMatr); - CvMat Mes = cvMat(Dim,Dim,CV_32F,Kalm->MeasurementMatr); - CvMat PNC = cvMat(Dim,Dim,CV_32F,Kalm->PNCovariance); - CvMat MNC = cvMat(Dim,Dim,CV_32F,Kalm->MNCovariance); - CvMat PriErr = cvMat(Dim,Dim,CV_32F,Kalm->PriorErrorCovariance); - CvMat PostErr = cvMat(Dim,Dim,CV_32F,Kalm->PosterErrorCovariance); - CvMat PriState = cvMat(Dim,1,CV_32F,Kalm->PriorState); - CvMat PostState = cvMat(Dim,1,CV_32F,Kalm->PosterState); - cvSetIdentity(&PNC); - cvSetIdentity(&PriErr); - cvSetIdentity(&PostErr); - cvSetZero(&MNC); - cvSetZero(&PriState); - cvSetZero(&PostState); - cvSetIdentity(&Mes); - cvSetIdentity(&Dyn); - cvRandArr(rng, Sample, CV_RAND_UNI, cvScalarAll(-max_init), cvScalarAll(max_init)); - cvKalmanCorrect(Kalm, Sample); - for(i = 0; idata.fl[k]; - } - Temp->data.fl[j]= (float)(t+(cvTsRandReal(rng)*2-1)*max_noise); - } - cvCopy( Temp, Sample ); - cvKalmanCorrect(Kalm,Temp); - } - - code = cvTsCmpEps2( ts, Sample, Kalm->state_post, EPSILON, false, "The final estimated state" ); - - cvReleaseMat(&Sample); - cvReleaseMat(&Temp); - cvReleaseKalman(&Kalm); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_KalmanTest kalman_test; - - -/* End of file. */ diff --git a/tests/cv/src/akmeans.cpp b/tests/cv/src/akmeans.cpp deleted file mode 100644 index c64e592..0000000 --- a/tests/cv/src/akmeans.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -/* Testing parameters */ -static char test_desc[] = "KMeans clustering"; -static char* func_name[] = -{ - "cvKMeans" -}; - -//based on Ara Nefian's implementation -float distance(float* vector_1, float *vector_2, int VecSize) -{ - int i; - float dist; - - dist = 0.0; - for (i = 0; i < VecSize; i++) - { - //printf ("%f, %f\n", vector_1[i], vector_2[i]); - dist = dist + (vector_1[i] - vector_2[i])*(vector_1[i] - vector_2[i]); - } - return dist; -} - -//returns number of made iterations -int _real_kmeans( int numClusters, float **sample, int numSamples, - int VecSize, int* a_class, double eps, int iter ) - -{ - int i, k, n; - int *counter; - float minDist; - float *dist; - float **curr_cluster; - float **prev_cluster; - - float error; - - //printf("* numSamples = %d, numClusters = %d, VecSize = %d\n", numSamples, numClusters, VecSize); - - //memory allocation - dist = new float[numClusters]; - counter = new int[numClusters]; - - //allocate memory for curr_cluster and prev_cluster - curr_cluster = new float*[numClusters]; - prev_cluster = new float*[numClusters]; - for (k = 0; k < numClusters; k++){ - curr_cluster[k] = new float[VecSize]; - prev_cluster[k] = new float[VecSize]; - } - - //pick initial cluster centers - for (k = 0; k < numClusters; k++) - { - for (n = 0; n < VecSize; n++) - { - curr_cluster[k][n] = sample[k*(numSamples/numClusters)][n]; - prev_cluster[k][n] = sample[k*(numSamples/numClusters)][n]; - } - } - - - int NumIter = 0; - error = FLT_MAX; - while ((error > eps) && (NumIter < iter)) - { - NumIter++; - //printf("NumIter = %d, error = %lf, \n", NumIter, error); - - //assign samples to clusters - for (i = 0; i < numSamples; i++) - { - for (k = 0; k < numClusters; k++) - { - dist[k] = distance(sample[i], curr_cluster[k], VecSize); - } - minDist = dist[0]; - a_class[i] = 0; - for (k = 1; k < numClusters; k++) - { - if (dist[k] < minDist) - { - minDist = dist[k]; - a_class[i] = k; - } - } - } - - //reset clusters and counters - for (k = 0; k < numClusters; k++){ - counter[k] = 0; - for (n = 0; n < VecSize; n++){ - curr_cluster[k][n] = 0.0; - } - } - for (i = 0; i < numSamples; i++){ - for (n = 0; n < VecSize; n++){ - curr_cluster[a_class[i]][n] = curr_cluster[a_class[i]][n] + sample[i][n]; - } - counter[a_class[i]]++; - } - - for (k = 0; k < numClusters; k++){ - for (n = 0; n < VecSize; n++){ - curr_cluster[k][n] = curr_cluster[k][n]/(float)counter[k]; - } - } - - error = 0.0; - for (k = 0; k < numClusters; k++){ - for (n = 0; n < VecSize; n++){ - error = error + (curr_cluster[k][n] - prev_cluster[k][n])*(curr_cluster[k][n] - prev_cluster[k][n]); - } - } - //error = error/(double)(numClusters*VecSize); - - //copy curr_clusters to prev_clusters - for (k = 0; k < numClusters; k++){ - for (n =0; n < VecSize; n++){ - prev_cluster[k][n] = curr_cluster[k][n]; - } - } - - } - - //deallocate memory for curr_cluster and prev_cluster - for (k = 0; k < numClusters; k++){ - delete curr_cluster[k]; - delete prev_cluster[k]; - } - delete curr_cluster; - delete prev_cluster; - - delete counter; - delete dist; - return NumIter; - -} - -static int fmaKMeans(void) -{ - CvTermCriteria crit; - float** vectors; - int* output; - int* etalon_output; - - int lErrors = 0; - int lNumVect = 0; - int lVectSize = 0; - int lNumClust = 0; - int lMaxNumIter = 0; - float flEpsilon = 0; - - int i,j; - static int read_param = 0; - - /* Initialization global parameters */ - if( !read_param ) - { - read_param = 1; - /* Read test-parameters */ - trsiRead( &lNumVect, "1000", "Number of vectors" ); - trsiRead( &lVectSize, "10", "Number of vectors" ); - trsiRead( &lNumClust, "20", "Number of clusters" ); - trsiRead( &lMaxNumIter,"100","Maximal number of iterations"); - trssRead( &flEpsilon, "0.5", "Accuracy" ); - } - - crit = cvTermCriteria( CV_TERMCRIT_EPS|CV_TERMCRIT_ITER, lMaxNumIter, flEpsilon ); - - //allocate vectors - vectors = (float**)cvAlloc( lNumVect * sizeof(float*) ); - for( i = 0; i < lNumVect; i++ ) - { - vectors[i] = (float*)cvAlloc( lVectSize * sizeof( float ) ); - } - - output = (int*)cvAlloc( lNumVect * sizeof(int) ); - etalon_output = (int*)cvAlloc( lNumVect * sizeof(int) ); - - //fill input vectors - for( i = 0; i < lNumVect; i++ ) - { - ats1flInitRandom( -2000, 2000, vectors[i], lVectSize ); - } - - /* run etalon kmeans */ - /* actually it is the simpliest realization of kmeans */ - - int ni = _real_kmeans( lNumClust, vectors, lNumVect, lVectSize, etalon_output, crit.epsilon, crit.max_iter ); - - trsWrite( ATS_CON, "%d iterations done\n", ni ); - - /* Run OpenCV function */ -#define _KMEANS_TIME 0 - -#if _KMEANS_TIME - //timing section - trsTimerStart(0); - __int64 tics = atsGetTickCount(); -#endif - - cvKMeans( lNumClust, vectors, lNumVect, lVectSize, - crit, output ); - -#if _KMEANS_TIME - tics = atsGetTickCount() - tics; - trsTimerStop(0); - //output result - //double dbUsecs =ATS_TICS_TO_USECS((double)tics); - trsWrite( ATS_CON, "Tics per iteration %d\n", tics/ni ); - -#endif - - //compare results - for( j = 0; j < lNumVect; j++ ) - { - if ( output[j] != etalon_output[j] ) - { - lErrors++; - } - } - - //free memory - for( i = 0; i < lNumVect; i++ ) - { - cvFree( &(vectors[i]) ); - } - cvFree(&vectors); - cvFree(&output); - cvFree(&etalon_output); - - if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" ); - else return trsResult( TRS_FAIL, "Detected %d errors", lErrors ); - -} - - - -void InitAKMeans() -{ - /* Register test function */ - trsReg( func_name[0], test_desc, atsAlgoClass, fmaKMeans ); - -} /* InitAKMeans */ - -#endif diff --git a/tests/cv/src/amatchcontourtrees.cpp b/tests/cv/src/amatchcontourtrees.cpp deleted file mode 100644 index a93ae24..0000000 --- a/tests/cv/src/amatchcontourtrees.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 -/*#include "conio.h" */ - -static char cTestName[] = "Matching Contour trees"; -static char cTestClass[] = "Algorithm"; -static char cFuncName[] = "cvMatchContourTrees"; - -static int aMatchContourTrees(void) -{ - CvSeqBlock contour_blk1, contour_blk2; - CvContour contour_h1, contour_h2; - CvContourTree *tree1, *tree2; - CvMemStorage *storage; /* storage for contour and tree writing */ - int block_size = 10000; - - CvRandState state; - double lower, upper; - int seed; - float fr; - int type_seq; - int method; - int nPoints1 = 12, nPoints2 = 12; - int xc,yc,a1 = 10, b1 = 20, a2 = 10, b2 =20, fi = 0; - int xmin,ymin,xmax,ymax; - double error_test,rezult, eps_rez = 0.8; - double pi = 3.1415926; - double threshold = 1.e-7; - double threshold2 = 5.; - int i; - int code = TRS_OK; - - int width=256,height=256; - CvPoint *cp1,*cp2; - -/* read tests params */ - - if (!trsiRead(&nPoints1,"20","Number of points first contour")) - return TRS_UNDEF; - if (!trsiRead(&nPoints2,"20","Number of points second contour")) - return TRS_UNDEF; - - if(nPoints1>0&&nPoints2>0) - { - if (!trsiRead(&a1,"10","first radius of the first elipse")) - return TRS_UNDEF; - if (!trsiRead(&b1,"20","second radius of the first elipse")) - return TRS_UNDEF; - if (!trsiRead(&a2,"15","first radius of the second elipse")) - return TRS_UNDEF; - if (!trsiRead(&b2,"30","second radius of the second elipse")) - return TRS_UNDEF; - if (!trsiRead(&fi,"0","second radius of the second elipse")) - return TRS_UNDEF; - - if (!trsdRead(&upper,"3","noise amplidude")) - return TRS_UNDEF; - - xc = (int)(width/2.); - yc = (int)(height/2.); - xmin = width; - ymin = height; - xmax = 0; - ymax = 0; - - cp1 = (CvPoint*) trsmAlloc(nPoints1*sizeof(CvPoint)); - cp2 = (CvPoint*) trsmAlloc(nPoints2*sizeof(CvPoint)); - - for(i=0;i cp1[i].x) xmin = cp1[i].x; - if(xmax< cp1[i].x) xmax = cp1[i].x; - if(ymin> cp1[i].y) ymin = cp1[i].y; - if(ymax< cp1[i].y) ymax = cp1[i].y; - } - - if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; - - lower = -upper; -/* upper = 3;*/ - seed = 345753; - cvRandInit(&state, (float)lower,(float)upper, seed ); - for(i=0;i cp2[i].x) xmin = cp2[i].x; - if(xmax< cp2[i].x) xmax = cp2[i].x; - if(ymin> cp2[i].y) ymin = cp2[i].y; - if(ymax< cp2[i].y) ymax = cp2[i].y; - } - if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; - -/* contours initialazing */ - type_seq = CV_SEQ_POLYGON; - cvMakeSeqHeaderForArray( type_seq, sizeof(CvContour), sizeof(CvPoint), - (char*)cp1, nPoints1, (CvSeq*)&contour_h1, &contour_blk1); - - cvMakeSeqHeaderForArray( type_seq, sizeof(CvContour), sizeof(CvPoint), - (char*)cp2, nPoints2, (CvSeq*)&contour_h2, &contour_blk2); - -/* contour trees created*/ - storage = cvCreateMemStorage( block_size ); - - tree1 = cvCreateContourTree ((CvSeq*)&contour_h1, storage, threshold); - tree2 = cvCreateContourTree ((CvSeq*)&contour_h2, storage, threshold); - - -/* countours matchig */ - error_test = 0.; - method = 1; - - rezult = cvMatchContourTrees (tree1, tree2, (CvContourTreesMatchMethod)method,threshold2); - error_test+=rezult; - - if(error_test > eps_rez ) code = TRS_FAIL; - else code = TRS_OK; - - trsWrite( ATS_CON | ATS_LST | ATS_SUM, "contours matching error_test =%f \n", - error_test); - - cvReleaseMemStorage ( &storage ); - - trsFree (cp2); - trsFree (cp1); - - } - - -/* _getch(); */ - return code; -} - -void InitAMatchContourTrees( void ) -{ -/* Test Registartion */ - trsReg(cFuncName,cTestName,cTestClass,aMatchContourTrees); - -} /* InitAMatchContourTrees */ - -/* End of file. */ - -#endif diff --git a/tests/cv/src/amoments.cpp b/tests/cv/src/amoments.cpp deleted file mode 100644 index b2834c4..0000000 --- a/tests/cv/src/amoments.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ -#include "cvtest.h" - -static const char* moments_param_names[] = { "size", "depth", 0 }; -static const int moments_depths[] = { CV_8U, CV_32F, -1 }; - -static const CvSize moments_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize moments_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; - -// image moments -class CV_MomentsTest : public CvArrTest -{ -public: - CV_MomentsTest(); - -protected: - - enum { MOMENT_COUNT = 25 }; - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - int coi; - bool is_binary; -}; - - -CV_MomentsTest::CV_MomentsTest() - : CvArrTest( "moments-raster", "cvMoments, cvGetNormalizedCentralMoment", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - coi = -1; - is_binary = false; - //element_wise_relative_error = false; - - default_timing_param_names = moments_param_names; - depth_list = moments_depths; - size_list = moments_sizes; - whole_size_list = moments_whole_sizes; - - cn_list = 0; -} - - -void CV_MomentsTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - int depth = CV_MAT_DEPTH(type); - - if( depth == CV_16U ) - { - *low = cvScalarAll(0); - *high = cvScalarAll(1000); - } - else if( depth == CV_16S ) - { - *low = cvScalarAll(-1000); - *high = cvScalarAll(1000); - } - else if( depth == CV_32F ) - { - *low = cvScalarAll(-1); - *high = cvScalarAll(1); - } -} - - -void CV_MomentsTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int cn = cvTsRandInt(rng) % 4 + 1; - int depth = cvTsRandInt(rng) % 4; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - if( cn == 2 ) - cn = 1; - - types[INPUT][0] = CV_MAKETYPE(depth, cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(MOMENT_COUNT,1); - - is_binary = cvTsRandInt(rng) % 2 != 0; - coi = 0; - cvmat_allowed = true; - if( cn > 1 ) - { - coi = cvTsRandInt(rng) % cn; - cvmat_allowed = false; - } -} - - -void CV_MomentsTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = whole_sizes[OUTPUT][0] = cvSize(MOMENT_COUNT,1); -} - - -double CV_MomentsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth != CV_32F ? FLT_EPSILON*10 : FLT_EPSILON*100; -} - - - -int CV_MomentsTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - int cn = CV_MAT_CN(test_mat[INPUT][0].type); - if( cn > 1 ) - cvSetImageCOI( (IplImage*)test_array[INPUT][0], coi + 1 ); - } - - return code; -} - - -void CV_MomentsTest::run_func() -{ - CvMoments* m = (CvMoments*)test_mat[OUTPUT][0].data.db; - double* others = (double*)(m + 1); - cvMoments( test_array[INPUT][0], m, is_binary ); - others[0] = cvGetNormalizedCentralMoment( m, 2, 0 ); - others[1] = cvGetNormalizedCentralMoment( m, 1, 1 ); - others[2] = cvGetNormalizedCentralMoment( m, 0, 2 ); - others[3] = cvGetNormalizedCentralMoment( m, 3, 0 ); - others[4] = cvGetNormalizedCentralMoment( m, 2, 1 ); - others[5] = cvGetNormalizedCentralMoment( m, 1, 2 ); - others[6] = cvGetNormalizedCentralMoment( m, 0, 3 ); -} - - -void CV_MomentsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMoments m; - double* mdata = test_mat[REF_OUTPUT][0].data.db; - int depth = CV_MAT_DEPTH(src->type); - int cn = CV_MAT_CN(src->type); - int i, y, x, cols = src->cols; - double xc = 0., yc = 0.; - - memset( &m, 0, sizeof(m)); - - for( y = 0; y < src->rows; y++ ) - { - double s0 = 0, s1 = 0, s2 = 0, s3 = 0; - uchar* ptr = src->data.ptr + y*src->step; - for( x = 0; x < cols; x++ ) - { - double val; - if( depth == CV_8U ) - val = ptr[x*cn + coi]; - else if( depth == CV_16U ) - val = ((ushort*)ptr)[x*cn + coi]; - else if( depth == CV_16S ) - val = ((short*)ptr)[x*cn + coi]; - else - val = ((float*)ptr)[x*cn + coi]; - - if( is_binary ) - val = val != 0; - - s0 += val; - s1 += val*x; - s2 += val*x*x; - s3 += ((val*x)*x)*x; - } - - m.m00 += s0; - m.m01 += s0*y; - m.m02 += (s0*y)*y; - m.m03 += ((s0*y)*y)*y; - - m.m10 += s1; - m.m11 += s1*y; - m.m12 += (s1*y)*y; - - m.m20 += s2; - m.m21 += s2*y; - - m.m30 += s3; - } - - if( m.m00 != 0 ) - { - xc = m.m10/m.m00, yc = m.m01/m.m00; - m.inv_sqrt_m00 = 1./sqrt(fabs(m.m00)); - } - - for( y = 0; y < src->rows; y++ ) - { - double s0 = 0, s1 = 0, s2 = 0, s3 = 0, y1 = y - yc; - uchar* ptr = src->data.ptr + y*src->step; - for( x = 0; x < cols; x++ ) - { - double val, x1 = x - xc; - if( depth == CV_8U ) - val = ptr[x*cn + coi]; - else if( depth == CV_16U ) - val = ((ushort*)ptr)[x*cn + coi]; - else if( depth == CV_16S ) - val = ((short*)ptr)[x*cn + coi]; - else - val = ((float*)ptr)[x*cn + coi]; - - if( is_binary ) - val = val != 0; - - s0 += val; - s1 += val*x1; - s2 += val*x1*x1; - s3 += ((val*x1)*x1)*x1; - } - - m.mu02 += s0*y1*y1; - m.mu03 += ((s0*y1)*y1)*y1; - - m.mu11 += s1*y1; - m.mu12 += (s1*y1)*y1; - - m.mu20 += s2; - m.mu21 += s2*y1; - - m.mu30 += s3; - } - - memcpy( mdata, &m, sizeof(m)); - mdata += sizeof(m)/sizeof(m.m00); - - /* calc normalized moments */ - { - double inv_m00 = m.inv_sqrt_m00*m.inv_sqrt_m00; - double s2 = inv_m00*inv_m00; /* 1./(m00 ^ (2/2 + 1)) */ - double s3 = s2*m.inv_sqrt_m00; /* 1./(m00 ^ (3/2 + 1)) */ - - mdata[0] = m.mu20 * s2; - mdata[1] = m.mu11 * s2; - mdata[2] = m.mu02 * s2; - - mdata[3] = m.mu30 * s3; - mdata[4] = m.mu21 * s3; - mdata[5] = m.mu12 * s3; - mdata[6] = m.mu03 * s3; - } - - { - double* a = test_mat[REF_OUTPUT][0].data.db; - double* b = test_mat[OUTPUT][0].data.db; - for( i = 0; i < MOMENT_COUNT; i++ ) - { - if( fabs(a[i]) < 1e-3 ) - a[i] = 0; - if( fabs(b[i]) < 1e-3 ) - b[i] = 0; - } - } -} - - -CV_MomentsTest img_moments_test; - - -// Hu invariants -class CV_HuMomentsTest : public CvArrTest -{ -public: - CV_HuMomentsTest(); - -protected: - - enum { MOMENT_COUNT = 18, HU_MOMENT_COUNT = 7 }; - - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); -}; - - -CV_HuMomentsTest::CV_HuMomentsTest() - : CvArrTest( "moments-hu", "cvHuMoments", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; // for now disable the timing test -} - - -void CV_HuMomentsTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - *low = cvScalarAll(-10000); - *high = cvScalarAll(10000); -} - - -void CV_HuMomentsTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[INPUT][0] = cvSize(MOMENT_COUNT,1); - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(HU_MOMENT_COUNT,1); -} - - -double CV_HuMomentsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return FLT_EPSILON; -} - - - -int CV_HuMomentsTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - // ... - } - - return code; -} - - -void CV_HuMomentsTest::run_func() -{ - cvGetHuMoments( (CvMoments*)test_mat[INPUT][0].data.db, - (CvHuMoments*)test_mat[OUTPUT][0].data.db ); -} - - -void CV_HuMomentsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMoments* m = (CvMoments*)test_mat[INPUT][0].data.db; - CvHuMoments* hu = (CvHuMoments*)test_mat[REF_OUTPUT][0].data.db; - - double inv_m00 = m->inv_sqrt_m00*m->inv_sqrt_m00; - double s2 = inv_m00*inv_m00; /* 1./(m00 ^ (2/2 + 1)) */ - double s3 = s2*m->inv_sqrt_m00; /* 1./(m00 ^ (3/2 + 1)) */ - - double nu20 = m->mu20 * s2; - double nu11 = m->mu11 * s2; - double nu02 = m->mu02 * s2; - - double nu30 = m->mu30 * s3; - double nu21 = m->mu21 * s3; - double nu12 = m->mu12 * s3; - double nu03 = m->mu03 * s3; - - #undef sqr - #define sqr(a) ((a)*(a)) - - hu->hu1 = nu20 + nu02; - hu->hu2 = sqr(nu20 - nu02) + 4*sqr(nu11); - hu->hu3 = sqr(nu30 - 3*nu12) + sqr(3*nu21 - nu03); - hu->hu4 = sqr(nu30 + nu12) + sqr(nu21 + nu03); - hu->hu5 = (nu30 - 3*nu12)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + - (3*nu21 - nu03)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); - hu->hu6 = (nu20 - nu02)*(sqr(nu30 + nu12) - sqr(nu21 + nu03)) + - 4*nu11*(nu30 + nu12)*(nu21 + nu03); - hu->hu7 = (3*nu21 - nu03)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + - (3*nu12 - nu30)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); -} - - -CV_HuMomentsTest hu_moments_test; diff --git a/tests/cv/src/amotiontemplates.cpp b/tests/cv/src/amotiontemplates.cpp deleted file mode 100644 index a871f71..0000000 --- a/tests/cv/src/amotiontemplates.cpp +++ /dev/null @@ -1,642 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const int motempl_silh_ratio[] = { 10, 50 }; -static const int motempl_duration[] = { 200, 2000 }; -static const int motempl_gradient_aperture[] = { 3, 5 }; -static const char* motempl_update_param_names[] = { "silh_ratio", "duration", "size", 0 }; -static const char* motempl_gradient_param_names[] = { "silh_ratio", "duration", "aperture", "size", 0 }; -static const char* motempl_global_param_names[] = { "silh_ratio", "duration", "size", 0 }; -static const CvSize motempl_sizes[] = {{320, 240}, {720,480}, {-1,-1}}; - -///////////////////// base MHI class /////////////////////// -class CV_MHIBaseTest : public CvArrTest -{ -public: - CV_MHIBaseTest( const char* test_name, const char* test_funcs ); - -protected: - int write_default_params(CvFileStorage* fs); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - int prepare_test_case( int test_case_idx ); - double timestamp, duration, max_log_duration; - int mhi_i, mhi_ref_i; - double silh_ratio; -}; - - -CV_MHIBaseTest::CV_MHIBaseTest( const char* test_name, const char* test_funcs ) - : CvArrTest( test_name, test_funcs ) -{ - timestamp = duration = 0; - max_log_duration = 9; - mhi_i = mhi_ref_i = -1; - - size_list = whole_size_list = strcmp( test_funcs, "" ) == 0 ? motempl_sizes : 0; - depth_list = 0; - cn_list = 0; - default_timing_param_names = 0; - - silh_ratio = 0.25; -} - - -int CV_MHIBaseTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE && strcmp(tested_functions, "") == 0 ) - { - start_write_param( fs ); - write_int_list( fs, "silh_ratio", motempl_silh_ratio, CV_DIM(motempl_silh_ratio) ); - write_int_list( fs, "duration", motempl_duration, CV_DIM(motempl_duration) ); - } - - return code; -} - - -void CV_MHIBaseTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT && CV_MAT_DEPTH(type) == CV_8U ) - { - *low = cvScalarAll(cvRound(-1./silh_ratio)+2.); - *high = cvScalarAll(2); - } - else if( i == mhi_i || i == mhi_ref_i ) - { - *low = cvScalarAll(-exp(max_log_duration)); - *high = cvScalarAll(0.); - } -} - - -void CV_MHIBaseTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - types[INPUT][0] = CV_8UC1; - types[mhi_i][0] = types[mhi_ref_i][0] = CV_32FC1; - duration = exp(cvTsRandReal(rng)*max_log_duration); - timestamp = duration + cvTsRandReal(rng)*30.-10.; -} - - -void CV_MHIBaseTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT][0] = CV_8UC1; - types[mhi_i][0] = CV_32FC1; - duration = cvReadInt( find_timing_param( "duration" ), 500 ); - silh_ratio = cvReadInt( find_timing_param( "silh_ratio" ), 25 )*0.01; - timestamp = duration; -} - - -void CV_MHIBaseTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "ratio=%d%%,duration=%dms,", cvRound(silh_ratio*100), cvRound(duration) ); - ptr += strlen(ptr); - params_left -= 2; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CV_MHIBaseTest::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - CvMat* mat = &test_mat[mhi_i][0]; - cvTsAdd( mat, cvScalarAll(1.), 0, cvScalarAll(0.), cvScalarAll(duration), mat, 0 ); - cvTsMinMaxS( mat, 0, mat, CV_TS_MAX ); - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE && mhi_i != mhi_ref_i ) - { - CvMat* mat0 = &test_mat[mhi_ref_i][0]; - cvTsCopy( mat, mat0 ); - } - } - - return code; -} - - -CV_MHIBaseTest mhi_base_test( "mhi", "" ); - - -///////////////////// update motion history //////////////////////////// - -static void cvTsUpdateMHI( const CvMat* silh, CvMat* mhi, double timestamp, double duration ) -{ - int i, j; - float delbound = (float)(timestamp - duration); - for( i = 0; i < mhi->rows; i++ ) - { - const uchar* silh_row = silh->data.ptr + i*silh->step; - float* mhi_row = (float*)(mhi->data.ptr + i*mhi->step); - - for( j = 0; j < mhi->cols; j++ ) - { - if( silh_row[j] ) - mhi_row[j] = (float)timestamp; - else if( mhi_row[j] < delbound ) - mhi_row[j] = 0.f; - } - } -} - - -class CV_UpdateMHITest : public CV_MHIBaseTest -{ -public: - CV_UpdateMHITest(); - -protected: - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_UpdateMHITest::CV_UpdateMHITest() - : CV_MHIBaseTest( "mhi-update", "cvUpdateMotionHistory" ) -{ - test_array[INPUT].push(NULL); - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - mhi_i = INPUT_OUTPUT; mhi_ref_i = REF_INPUT_OUTPUT; - - default_timing_param_names = motempl_update_param_names; -} - - -double CV_UpdateMHITest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CV_UpdateMHITest::run_func() -{ - cvUpdateMotionHistory( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], timestamp, duration ); -} - - -void CV_UpdateMHITest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsUpdateMHI( &test_mat[INPUT][0], &test_mat[REF_INPUT_OUTPUT][0], timestamp, duration ); -} - - -CV_UpdateMHITest mhi_update_test; - - -///////////////////// calc motion gradient //////////////////////////// - -static void cvTsMHIGradient( const CvMat* mhi, CvMat* mask, CvMat* orientation, - double delta1, double delta2, int aperture_size ) -{ - CvPoint anchor = { aperture_size/2, aperture_size/2 }; - CvMat* src = cvCreateMat( mhi->rows + aperture_size - 1, mhi->cols + aperture_size - 1, CV_32FC1 ); - CvMat* kernel = cvCreateMat( aperture_size, aperture_size, CV_32FC1 ); - CvMat* dx = cvCreateMat( mhi->rows, mhi->cols, CV_32FC1 ); - CvMat* dy = cvCreateMat( mhi->rows, mhi->cols, CV_32FC1 ); - CvMat* min_mhi = cvCreateMat( mhi->rows, mhi->cols, CV_32FC1 ); - CvMat* max_mhi = cvCreateMat( mhi->rows, mhi->cols, CV_32FC1 ); - IplConvKernel* element = cvCreateStructuringElementEx( aperture_size, aperture_size, - aperture_size/2, aperture_size/2, CV_SHAPE_RECT ); - int i, j; - double limit = 1e-4*aperture_size*aperture_size; - - cvTsPrepareToFilter( mhi, src, anchor ); - cvTsCalcSobelKernel2D( 1, 0, aperture_size, 0, kernel ); - cvTsConvolve2D( src, dx, kernel, anchor ); - cvTsCalcSobelKernel2D( 0, 1, aperture_size, 0, kernel ); - cvTsConvolve2D( src, dy, kernel, anchor ); - cvReleaseMat( &kernel ); - - cvTsMinMaxFilter( src, min_mhi, element, CV_TS_MIN ); - cvTsMinMaxFilter( src, max_mhi, element, CV_TS_MAX ); - cvReleaseMat( &src ); - cvReleaseStructuringElement( &element ); - - if( delta1 > delta2 ) - { - double t; - CV_SWAP( delta1, delta2, t ); - } - - for( i = 0; i < mhi->rows; i++ ) - { - uchar* mask_row = mask->data.ptr + i*mask->step; - float* orient_row = (float*)(orientation->data.ptr + i*orientation->step); - const float* dx_row = (float*)(dx->data.ptr + i*dx->step); - const float* dy_row = (float*)(dy->data.ptr + i*dy->step); - const float* min_row = (float*)(min_mhi->data.ptr + i*min_mhi->step); - const float* max_row = (float*)(max_mhi->data.ptr + i*max_mhi->step); - - for( j = 0; j < mhi->cols; j++ ) - { - double delta = max_row[j] - min_row[j]; - double _dx = dx_row[j], _dy = dy_row[j]; - - if( delta1 <= delta && delta <= delta2 && - (fabs(_dx) > limit || fabs(_dy) > limit) ) - { - mask_row[j] = 1; - double angle = atan2( _dy, _dx ) * (180/CV_PI); - if( angle < 0 ) - angle += 360.; - orient_row[j] = (float)angle; - } - else - { - mask_row[j] = 0; - orient_row[j] = 0.f; - } - } - } - - cvReleaseMat( &dx ); - cvReleaseMat( &dy ); - cvReleaseMat( &min_mhi ); - cvReleaseMat( &max_mhi ); -} - - -class CV_MHIGradientTest : public CV_MHIBaseTest -{ -public: - CV_MHIGradientTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - int write_default_params(CvFileStorage* fs); - - double delta1, delta2, delta_range_log; - int aperture_size; -}; - - -CV_MHIGradientTest::CV_MHIGradientTest() - : CV_MHIBaseTest( "mhi-gradient", "cvCalcMotionGradient" ) -{ - mhi_i = mhi_ref_i = INPUT; - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - delta1 = delta2 = 0; - aperture_size = 0; - delta_range_log = 4; - - default_timing_param_names = motempl_gradient_param_names; -} - - -int CV_MHIGradientTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_int_list( fs, "aperture", motempl_gradient_aperture, CV_DIM(motempl_gradient_aperture) ); - } - - return code; -} - - -void CV_MHIGradientTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_MHIBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8UC1; - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_32FC1; - delta1 = exp(cvTsRandReal(rng)*delta_range_log + 1.); - delta2 = exp(cvTsRandReal(rng)*delta_range_log + 1.); - aperture_size = (cvTsRandInt(rng)%3)*2+3; - //duration = exp(cvTsRandReal(rng)*max_log_duration); - //timestamp = duration + cvTsRandReal(rng)*30.-10.; -} - - -void CV_MHIGradientTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_MHIBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[OUTPUT][0] = CV_8UC1; - types[OUTPUT][1] = CV_32FC1; - aperture_size = cvReadInt( find_timing_param( "aperture" ), 3 ); - delta1 = duration*0.02; - delta2 = duration*0.2; -} - - -void CV_MHIGradientTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "aperture=%d,", aperture_size ); - ptr += strlen(ptr); - params_left--; - - CV_MHIBaseTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CV_MHIGradientTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int j ) -{ - return j == 0 ? 0 : 2e-1; -} - - -void CV_MHIGradientTest::run_func() -{ - cvCalcMotionGradient( test_array[INPUT][0], test_array[OUTPUT][0], - test_array[OUTPUT][1], delta1, delta2, aperture_size ); -} - - -void CV_MHIGradientTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsMHIGradient( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - &test_mat[REF_OUTPUT][1], delta1, delta2, aperture_size ); - cvTsAdd( &test_mat[REF_OUTPUT][1], cvScalarAll(1.), 0, cvScalarAll(0.), - cvScalarAll(1.), &test_mat[REF_OUTPUT][1], 0 ); - cvTsAdd( &test_mat[OUTPUT][1], cvScalarAll(1.), 0, cvScalarAll(0.), - cvScalarAll(1.), &test_mat[OUTPUT][1], 0 ); -} - - -CV_MHIGradientTest mhi_gradient_test; - - -////////////////////// calc global orientation ///////////////////////// - -static double -cvTsCalcGlobalOrientation( const CvMat* orient, const CvMat* mask, const CvMat* mhi, - double timestamp, double duration ) -{ - const int HIST_SIZE = 12; - int y, x; - int histogram[HIST_SIZE]; - int max_bin = 0; - - double base_orientation = 0, delta_orientation = 0, weight = 0; - double low_time, global_orientation; - - memset( histogram, 0, sizeof( histogram )); - timestamp = 0; - - for( y = 0; y < orient->rows; y++ ) - { - const float* orient_data = (const float*)(orient->data.ptr + y*orient->step); - const uchar* mask_data = mask->data.ptr + y*mask->step; - const float* mhi_data = (const float*)(mhi->data.ptr + y*mhi->step); - for( x = 0; x < orient->cols; x++ ) - if( mask_data[x] ) - { - int bin = cvFloor( (orient_data[x]*HIST_SIZE)/360 ); - histogram[bin < 0 ? 0 : bin >= HIST_SIZE ? HIST_SIZE-1 : bin]++; - if( mhi_data[x] > timestamp ) - timestamp = mhi_data[x]; - } - } - - low_time = timestamp - duration; - - for( x = 1; x < HIST_SIZE; x++ ) - { - if( histogram[x] > histogram[max_bin] ) - max_bin = x; - } - - base_orientation = ((double)max_bin*360)/HIST_SIZE; - - for( y = 0; y < orient->rows; y++ ) - { - const float* orient_data = (const float*)(orient->data.ptr + y*orient->step); - const float* mhi_data = (const float*)(mhi->data.ptr + y*mhi->step); - const uchar* mask_data = mask->data.ptr + y*mask->step; - - for( x = 0; x < orient->cols; x++ ) - { - if( mask_data[x] && mhi_data[x] > low_time ) - { - double diff = orient_data[x] - base_orientation; - double delta_weight = (((mhi_data[x] - low_time)/duration)*254 + 1)/255; - - if( diff < -180 ) diff += 360; - if( diff > 180 ) diff -= 360; - - if( delta_weight > 0 && fabs(diff) < 45 ) - { - delta_orientation += diff*delta_weight; - weight += delta_weight; - } - } - } - } - - if( weight == 0 ) - global_orientation = base_orientation; - else - { - global_orientation = base_orientation + delta_orientation/weight; - if( global_orientation < 0 ) global_orientation += 360; - if( global_orientation > 360 ) global_orientation -= 360; - } - - return global_orientation; -} - - -class CV_MHIGlobalOrientTest : public CV_MHIBaseTest -{ -public: - CV_MHIGlobalOrientTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - int validate_test_results( int test_case_idx ); - void run_func(); - double angle, min_angle, max_angle; -}; - - -CV_MHIGlobalOrientTest::CV_MHIGlobalOrientTest() - : CV_MHIBaseTest( "mhi-global", "cvCalcGlobalOrientation" ) -{ - mhi_i = mhi_ref_i = INPUT; - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - min_angle = max_angle = 0; - - default_timing_param_names = motempl_global_param_names; -} - - -void CV_MHIGlobalOrientTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CV_MHIBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize size = sizes[INPUT][0]; - - size.width = MAX( size.width, 16 ); - size.height = MAX( size.height, 16 ); - sizes[INPUT][0] = sizes[INPUT][1] = sizes[INPUT][2] = size; - - types[INPUT][1] = CV_8UC1; // mask - types[INPUT][2] = CV_32FC1; // orientation - - min_angle = cvTsRandReal(rng)*359.9; - max_angle = cvTsRandReal(rng)*359.9; - if( min_angle >= max_angle ) - { - double t; - CV_SWAP( min_angle, max_angle, t ); - } - max_angle += 0.1; - duration = exp(cvTsRandReal(rng)*max_log_duration); - timestamp = duration + cvTsRandReal(rng)*30.-10.; -} - - -void CV_MHIGlobalOrientTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CV_MHIBaseTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - types[INPUT][1] = CV_8UC1; - types[INPUT][2] = CV_32FC1; -} - - -void CV_MHIGlobalOrientTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CV_MHIBaseTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT && j == 2 ) - { - *low = cvScalarAll(min_angle); - *high = cvScalarAll(max_angle); - } -} - - -double CV_MHIGlobalOrientTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 15; -} - - -void CV_MHIGlobalOrientTest::run_func() -{ - angle = cvCalcGlobalOrientation( test_array[INPUT][2], test_array[INPUT][1], - test_array[INPUT][0], timestamp, duration ); -} - - -int CV_MHIGlobalOrientTest::validate_test_results( int test_case_idx ) -{ - //printf("%d. rows=%d, cols=%d, nzmask=%d\n", test_case_idx, test_mat[INPUT][1].rows, test_mat[INPUT][1].cols, - // cvCountNonZero(test_array[INPUT][1])); - - double ref_angle = cvTsCalcGlobalOrientation( &test_mat[INPUT][2], &test_mat[INPUT][1], - &test_mat[INPUT][0], timestamp, duration ); - double err_level = get_success_error_level( test_case_idx, 0, 0 ); - int code = CvTS::OK; - int nz = cvCountNonZero( test_array[INPUT][1] ); - - if( nz > 32 && !(min_angle - err_level <= angle && - max_angle + err_level >= angle) && - !(min_angle - err_level <= angle+360 && - max_angle + err_level >= angle+360) ) - { - ts->printf( CvTS::LOG, "The angle=%g is outside (%g,%g) range\n", - angle, min_angle - err_level, max_angle + err_level ); - code = CvTS::FAIL_BAD_ACCURACY; - } - else if( fabs(angle - ref_angle) > err_level && - fabs(360 - fabs(angle - ref_angle)) > err_level ) - { - ts->printf( CvTS::LOG, "The angle=%g differs too much from reference value=%g\n", - angle, ref_angle ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_MHIGlobalOrientTest mhi_global_orient_test; - diff --git a/tests/cv/src/amotseg.cpp b/tests/cv/src/amotseg.cpp deleted file mode 100644 index 70c3b3d..0000000 --- a/tests/cv/src/amotseg.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -#define PUSHC(Y,X) { CurStack[CStIn].y=Y; \ - CurStack[CStIn].x=X; \ - CStIn++;} -#define PUSHN(Y,X) { NextStack[NStIn].y=Y; \ - NextStack[NStIn].x=X; \ - NStIn++;} - -#define POP(Y,X) { CStIn--; \ - Y=CurStack[CStIn].y; \ - X=CurStack[CStIn].x;} - -void testFill( float* img, - int step, - CvSize imgSize, - CvPoint seed_point, - float nv, - float* RP, - int itsstep, - float SegThresh, - CvConnectedComp* region) -{ - CvPoint* CurStack = (CvPoint*)cvAlloc(imgSize.height*imgSize.width*sizeof(CvPoint)); - CvPoint* NextStack = (CvPoint*)cvAlloc(imgSize.height*imgSize.width*sizeof(CvPoint)); - CvPoint* Temp; - int ownstep=step/4; - int RPstep=itsstep/4; - float thr = -SegThresh; - float nthr = thr*2; - int CStIn=0; - int NStIn=0; - int TempIn; - int x,y; - int XMax=0; - int YMax=0; - int XMin = imgSize.width; - int YMin = imgSize.height; - int Sum=0; - - PUSHC(seed_point.y,seed_point.x); -again: - while(CStIn) - { - POP(y,x); - XMax = MAX(XMax,x); - YMax = MAX(YMax,y); - XMin = MIN(XMin,x); - YMin = MIN(YMin,y); - if((y>0)&&(!RP[(y-1)*RPstep+x])&& - (((img[(y-1)*ownstep+x]-img[y*ownstep+x])<0)&& - ((img[(y-1)*ownstep+x]-img[y*ownstep+x])>=thr)))PUSHC(y-1,x); - if((y>0)&&(!RP[(y-1)*RPstep+x])&& - (((img[(y-1)*ownstep+x]-img[y*ownstep+x])<=thr)&& - ((img[(y-1)*ownstep+x]-img[y*ownstep+x])>=nthr)))PUSHN(y-1,x); - if((y=thr)))PUSHC(y+1,x); - if((y=nthr)))PUSHN(y+1,x); - if((x>0)&&(!RP[y*RPstep+x-1])&& - (((img[y*ownstep+x-1]-img[y*ownstep+x])<=0)&& - ((img[y*ownstep+x-1]-img[y*ownstep+x])>=thr)))PUSHC(y,x-1); - if((x>0)&&(!RP[y*RPstep+x-1])&& - (((img[y*ownstep+x-1]-img[y*ownstep+x])<=thr)&& - ((img[y*ownstep+x-1]-img[y*ownstep+x])>=nthr)))PUSHN(y,x-1); - if((x=thr)))PUSHC(y,x+1); - if((x=nthr)))PUSHN(y,x+1); - Sum++; - RP[y*RPstep+x]=nv; - img[y*ownstep+x] = -255; - } - if(NStIn) - { - Temp=CurStack; - CurStack=NextStack; - NextStack=Temp; - TempIn=CStIn; - CStIn=NStIn; - NStIn=TempIn; - goto again; - } - region->area = Sum; - region->rect.x = XMin; - region->rect.y = YMin; - region->rect.width = XMax - XMin + 1; - region->rect.height = YMax - YMin + 1; - region->value = cvScalar(nv); - cvFree(&CurStack); - cvFree(&NextStack); - return; -} - -/* Testing parameters */ -static char TestName[] = "Checking MotionSegmentation"; -static char TestClass[] = "Algorithm"; -static int lImageWidth; -static int lImageHeight; - -static int read_param = 0; -static int data_types = 0; -static float thresh = 0; -static double EPSILON = 3; - - -static int fcaMotSeg( void ) -{ - int step; - float* src; - AtsRandState state; - double Error = 0; - int color = 1; - CvSize roi; - - IplImage* mhi; - IplImage* mask32f; - IplImage* test32f; - CvSeq* seq1 = NULL; - CvSeq* seq2 = NULL; - CvMemStorage* storage; - CvSeqWriter writer; - - CvConnectedComp ConComp; - - storage = cvCreateMemStorage( 0 ); - cvClearMemStorage( storage ); - - /* Initialization global parameters */ - if( !read_param ) - { - read_param = 1; - /* Determining which test are needed to run */ - trsCaseRead( &data_types,"/u/s/f/a", "a", - "u - unsigned char, s - signed char, f - float, a - all" ); - /* Reading test-parameters */ - trsiRead( &lImageHeight, "20", "Image height" ); - trsiRead( &lImageWidth, "20", "Image width" ); - trssRead( &thresh, "10", "Segmentation Threshold" ); - } - if( data_types != 3 && data_types != 0 ) return TRS_UNDEF; - - /* Creating images for testing */ - mhi = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); - mask32f = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); - test32f = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); - - atsRandInit(&state,40,100,60); - atsFillRandomImageEx(mhi, &state ); - src = (float*)mhi->imageData; - step = mhi->widthStep/4; - int i; - for(i=0; i80)src[i*step+j]=80; - } - } - cvZero(test32f); - seq1 = cvSegmentMotion(mhi,mask32f,storage,80,thresh); - cvStartWriteSeq( 0, sizeof( CvSeq ), sizeof( CvConnectedComp ), storage, &writer ); - roi.width = lImageWidth; - roi.height = lImageHeight; - for(i=1;i=(80-thresh))&&(src[(i-1)*step+j]<80)) - { - CvPoint MinPoint; - MinPoint.x=j; - MinPoint.y=i-1; - testFill(src, - step*4, - roi, - MinPoint, - (float)color, - (float*)test32f->imageData, - test32f->widthStep, - thresh, - &ConComp); - ConComp.value = cvScalar(color); - CV_WRITE_SEQ_ELEM( ConComp, writer ); - color+=1; - } - - if((src[i*step+j-1]>=(80-thresh))&&(src[i*step+j-1]<80)) - { - CvPoint MinPoint; - MinPoint.x=j-1; - MinPoint.y=i; - testFill(src, - step*4, - roi, - MinPoint, - (float)color, - (float*)test32f->imageData, - test32f->widthStep, - thresh, - &ConComp); - ConComp.value = cvScalar(color); - CV_WRITE_SEQ_ELEM( ConComp, writer ); - color+=1; - } - if((src[i*step+j+1]>=(80-thresh))&&(src[i*step+j+1]<80)) - { - CvPoint MinPoint; - MinPoint.x=j+1; - MinPoint.y=i; - testFill(src, - step*4, - roi, - MinPoint, - (float)color, - (float*)test32f->imageData, - test32f->widthStep, - thresh, - &ConComp); - ConComp.value = cvScalar(color); - CV_WRITE_SEQ_ELEM( ConComp, writer ); - color+=1; - } - if((src[(i+1)*step+j]>=(80-thresh))&&(src[(i+1)*step+j]<80)) - { - CvPoint MinPoint; - MinPoint.x=j; - MinPoint.y=i+1; - testFill(src, - step*4, - roi, - MinPoint, - (float)color, - (float*)test32f->imageData, - test32f->widthStep, - thresh, - &ConComp); - ConComp.value = cvScalar(color); - CV_WRITE_SEQ_ELEM( ConComp, writer ); - color+=1; - } - - } - } - } - seq2 = cvEndWriteSeq( &writer ); - Error += cvNorm(test32f,mask32f,CV_C); - cvReleaseMemStorage(&storage); - cvReleaseImage(&mhi); - cvReleaseImage(&test32f); - cvReleaseImage(&mask32f); - /* Free Memory */ - - if(Error>=EPSILON)return TRS_FAIL; - return TRS_OK; -} /* fcaSobel8uC1R */ - -void InitAMotSeg(void) -{ - trsReg( "cvMotSeg", TestName, TestClass, fcaMotSeg); -} /* InitASobel */ - -#endif - -/* End of file. */ diff --git a/tests/cv/src/amser.cpp b/tests/cv/src/amser.cpp deleted file mode 100644 index cbe4683..0000000 --- a/tests/cv/src/amser.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -using namespace std; -using namespace cv; - -class CV_MserTest : public CvTest -{ -public: - CV_MserTest(); -protected: - void run(int); - int LoadBoxes(const char* path, vector& boxes); - int SaveBoxes(const char* path, const vector& boxes); - int CompareBoxes(const vector& boxes1,const vector& boxes2, float max_rel_diff = 0.01f); -}; - -CV_MserTest::CV_MserTest() : CvTest("MSER","cvExtractMSER") -{ -} - -int CV_MserTest::LoadBoxes(const char* path, vector& boxes) -{ - boxes.clear(); - FILE* f = fopen(path,"r"); - - if (f==NULL) - { - return 0; - } - - while (!feof(f)) - { - CvBox2D box; - fscanf(f,"%f,%f,%f,%f,%f\n",&box.angle,&box.center.x,&box.center.y,&box.size.width,&box.size.height); - boxes.push_back(box); - } - fclose(f); - return 1; -} - -int CV_MserTest::SaveBoxes(const char* path, const vector& boxes) -{ - FILE* f = fopen(path,"w"); - if (f==NULL) - { - return 0; - } - for (int i=0;i<(int)boxes.size();i++) - { - fprintf(f,"%f,%f,%f,%f,%f\n",boxes[i].angle,boxes[i].center.x,boxes[i].center.y,boxes[i].size.width,boxes[i].size.height); - } - fclose(f); - return 1; -} - -int CV_MserTest::CompareBoxes(const vector& boxes1,const vector& boxes2, float max_rel_diff) -{ - if (boxes1.size() != boxes2.size()) - return 0; - - for (int i=0; i<(int)boxes1.size();i++) - { - float rel_diff; - if (!((boxes1[i].angle == 0.0f) && (abs(boxes2[i].angle) < max_rel_diff))) - { - rel_diff = abs(boxes1[i].angle-boxes2[i].angle)/abs(boxes1[i].angle); - if (rel_diff > max_rel_diff) - return i; - } - - if (!((boxes1[i].center.x == 0.0f) && (abs(boxes2[i].center.x) < max_rel_diff))) - { - rel_diff = abs(boxes1[i].center.x-boxes2[i].center.x)/abs(boxes1[i].center.x); - if (rel_diff > max_rel_diff) - return i; - } - - if (!((boxes1[i].center.y == 0.0f) && (abs(boxes2[i].center.y) < max_rel_diff))) - { - rel_diff = abs(boxes1[i].center.y-boxes2[i].center.y)/abs(boxes1[i].center.y); - if (rel_diff > max_rel_diff) - return i; - } - if (!((boxes1[i].size.width == 0.0f) && (abs(boxes2[i].size.width) < max_rel_diff))) - { - rel_diff = abs(boxes1[i].size.width-boxes2[i].size.width)/abs(boxes1[i].size.width); - if (rel_diff > max_rel_diff) - return i; - } - - if (!((boxes1[i].size.height == 0.0f) && (abs(boxes2[i].size.height) < max_rel_diff))) - { - rel_diff = abs(boxes1[i].size.height-boxes2[i].size.height)/abs(boxes1[i].size.height); - if (rel_diff > max_rel_diff) - return i; - } - } - - return -1; -} - -void CV_MserTest::run(int) -{ - string image_path = string(ts->get_data_path()) + "mser/puzzle.png"; - - IplImage* img = cvLoadImage( image_path.c_str()); - if (!img) - { - ts->printf( CvTS::LOG, "Unable to open image mser/puzzle.png\n"); - ts->set_failed_test_info(CvTS::FAIL_MISSING_TEST_DATA); - return; - } - - CvSeq* contours; - CvMemStorage* storage= cvCreateMemStorage(); - IplImage* hsv = cvCreateImage( cvGetSize( img ), IPL_DEPTH_8U, 3 ); - cvCvtColor( img, hsv, CV_BGR2YCrCb ); - CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 ); - cvExtractMSER( hsv, NULL, &contours, storage, params ); - - vector boxes; - vector boxes_orig; - for ( int i = 0; i < contours->total; i++ ) - { - CvContour* r = *(CvContour**)cvGetSeqElem( contours, i ); - CvBox2D box = cvFitEllipse2( r ); - box.angle=(float)CV_PI/2-box.angle; - boxes.push_back(box); - } - - string boxes_path = string(ts->get_data_path()) + "mser/boxes.txt"; - - if (!LoadBoxes(boxes_path.c_str(),boxes_orig)) - { - SaveBoxes(boxes_path.c_str(),boxes); - ts->printf( CvTS::LOG, "Unable to open data file mser/boxes.txt\n"); - ts->set_failed_test_info(CvTS::FAIL_MISSING_TEST_DATA); - return; - } - - const float dissimularity = 0.01f; - int n_box = CompareBoxes(boxes_orig,boxes,dissimularity); - if (n_box < 0) - { - ts->set_failed_test_info(CvTS::OK); - } - else - { - ts->set_failed_test_info(CvTS::FAIL_BAD_ACCURACY); - ts->printf( CvTS::LOG, "Incorrect correspondence in %d box\n",n_box); - } - - cvReleaseMemStorage(&storage); - cvReleaseImage(&hsv); - cvReleaseImage(&img); -} - -CV_MserTest mser_test; diff --git a/tests/cv/src/anearestneighbors.cpp b/tests/cv/src/anearestneighbors.cpp deleted file mode 100644 index 6d1af6a..0000000 --- a/tests/cv/src/anearestneighbors.cpp +++ /dev/null @@ -1,526 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#include -#include -#include - -using namespace cv; -using namespace cv::flann; - -//-------------------------------------------------------------------------------- -class NearestNeighborTest : public CvTest -{ -public: - NearestNeighborTest( const char* test_name, const char* test_funcs ) - : CvTest( test_name, test_funcs ) {} -protected: - static const int minValue = 0; - static const int maxValue = 1; - static const int dims = 30; - static const int featuresCount = 2000; - static const int K = 1; // * should also test 2nd nn etc.? - - - virtual void run( int start_from ); - virtual void createModel( const Mat& data ) = 0; - virtual int findNeighbors( Mat& points, Mat& neighbors ) = 0; - virtual int checkGetPoins( const Mat& data ); - virtual int checkFindBoxed(); - virtual int checkFind( const Mat& data ); - virtual void releaseModel() = 0; -}; - -int NearestNeighborTest::checkGetPoins( const Mat& ) -{ - return CvTS::OK; -} - -int NearestNeighborTest::checkFindBoxed() -{ - return CvTS::OK; -} - -int NearestNeighborTest::checkFind( const Mat& data ) -{ - int code = CvTS::OK; - int pointsCount = 1000; - float noise = 0.2f; - - RNG rng; - Mat points( pointsCount, dims, CV_32FC1 ); - Mat results( pointsCount, K, CV_32SC1 ); - - std::vector fmap( pointsCount ); - for( int pi = 0; pi < pointsCount; pi++ ) - { - int fi = rng.next() % featuresCount; - fmap[pi] = fi; - for( int d = 0; d < dims; d++ ) - points.at(pi, d) = data.at(fi, d) + rng.uniform(0.0f, 1.0f) * noise; - } - - code = findNeighbors( points, results ); - - if( code == CvTS::OK ) - { - int correctMatches = 0; - for( int pi = 0; pi < pointsCount; pi++ ) - { - if( fmap[pi] == results.at(pi, 0) ) - correctMatches++; - } - - double correctPerc = correctMatches / (double)pointsCount; - if (correctPerc < .75) - { - ts->printf( CvTS::LOG, "correct_perc = %d\n", correctPerc ); - code = CvTS::FAIL_BAD_ACCURACY; - } - } - - return code; -} - -void NearestNeighborTest::run( int /*start_from*/ ) { - int code = CvTS::OK, tempCode; - Mat desc( featuresCount, dims, CV_32FC1 ); - randu( desc, Scalar(minValue), Scalar(maxValue) ); - - createModel( desc ); - - tempCode = checkGetPoins( desc ); - if( tempCode != CvTS::OK ) - { - ts->printf( CvTS::LOG, "bad accuracy of GetPoints \n" ); - code = tempCode; - } - - tempCode = checkFindBoxed(); - if( tempCode != CvTS::OK ) - { - ts->printf( CvTS::LOG, "bad accuracy of FindBoxed \n" ); - code = tempCode; - } - - tempCode = checkFind( desc ); - if( tempCode != CvTS::OK ) - { - ts->printf( CvTS::LOG, "bad accuracy of Find \n" ); - code = tempCode; - } - - releaseModel(); - - ts->set_failed_test_info( code ); -} - -//-------------------------------------------------------------------------------- -class CV_LSHTest : public NearestNeighborTest -{ -public: - CV_LSHTest() : NearestNeighborTest( "lsh", "cvLSHQuery" ) {} -protected: - virtual void createModel( const Mat& data ); - virtual int findNeighbors( Mat& points, Mat& neighbors ); - virtual void releaseModel(); - struct CvLSH* lsh; - CvMat desc; -}; - -void CV_LSHTest::createModel( const Mat& data ) -{ - desc = data; - lsh = cvCreateMemoryLSH( data.cols, data.rows, 70, 20, CV_32FC1 ); - cvLSHAdd( lsh, &desc ); -} - -int CV_LSHTest::findNeighbors( Mat& points, Mat& neighbors ) -{ - const int emax = 20; - Mat dist( points.rows, neighbors.cols, CV_64FC1); - CvMat _dist = dist, _points = points, _neighbors = neighbors; - cvLSHQuery( lsh, &_points, &_neighbors, &_dist, neighbors.cols, emax ); - return CvTS::OK; -} - -void CV_LSHTest::releaseModel() -{ - cvReleaseLSH( &lsh ); -} - -//-------------------------------------------------------------------------------- -class CV_FeatureTreeTest_C : public NearestNeighborTest -{ -public: - CV_FeatureTreeTest_C( const char* test_name, const char* test_funcs ) - : NearestNeighborTest( test_name, test_funcs ) {} -protected: - virtual int findNeighbors( Mat& points, Mat& neighbors ); - virtual void releaseModel(); - CvFeatureTree* tr; - CvMat desc; -}; - -int CV_FeatureTreeTest_C::findNeighbors( Mat& points, Mat& neighbors ) -{ - const int emax = 20; - Mat dist( points.rows, neighbors.cols, CV_64FC1); - CvMat _dist = dist, _points = points, _neighbors = neighbors; - cvFindFeatures( tr, &_points, &_neighbors, &_dist, neighbors.cols, emax ); - return CvTS::OK; -} - -void CV_FeatureTreeTest_C::releaseModel() -{ - cvReleaseFeatureTree( tr ); -} - -//-------------------------------------- -class CV_SpillTreeTest_C : public CV_FeatureTreeTest_C -{ -public: - CV_SpillTreeTest_C(): CV_FeatureTreeTest_C( "spilltree_c", "cvFindFeatures-spill" ) {} -protected: - virtual void createModel( const Mat& data ); -}; - -void CV_SpillTreeTest_C::createModel( const Mat& data ) -{ - desc = data; - tr = cvCreateSpillTree( &desc ); -} - -//-------------------------------------- -class CV_KDTreeTest_C : public CV_FeatureTreeTest_C -{ -public: - CV_KDTreeTest_C(): CV_FeatureTreeTest_C( "kdtree_c", "cvFindFeatures-kd" ) {} -protected: - virtual void createModel( const Mat& data ); - virtual int checkFindBoxed(); -}; - -void CV_KDTreeTest_C::createModel( const Mat& data ) -{ - desc = data; - tr = cvCreateKDTree( &desc ); -} - -int CV_KDTreeTest_C::checkFindBoxed() -{ - Mat min(1, dims, CV_32FC1 ), max(1, dims, CV_32FC1 ), indices( 1, 1, CV_32SC1 ); - float l = minValue, r = maxValue; - min.setTo(Scalar(l)), max.setTo(Scalar(r)); - CvMat _min = min, _max = max, _indices = indices; - // TODO check indices - if( cvFindFeaturesBoxed( tr, &_min, &_max, &_indices ) != featuresCount ) - return CvTS::FAIL_BAD_ACCURACY; - return CvTS::OK; -} - -//-------------------------------------------------------------------------------- -class CV_KDTreeTest_CPP : public NearestNeighborTest -{ -public: - CV_KDTreeTest_CPP() : NearestNeighborTest( "kdtree_cpp", "cv::KDTree funcs" ) {} -protected: - virtual void createModel( const Mat& data ); - virtual int checkGetPoins( const Mat& data ); - virtual int findNeighbors( Mat& points, Mat& neighbors ); - virtual int checkFindBoxed(); - virtual void releaseModel(); - KDTree* tr; -}; - - -void CV_KDTreeTest_CPP::createModel( const Mat& data ) -{ - tr = new KDTree( data, false ); -} - -int CV_KDTreeTest_CPP::checkGetPoins( const Mat& data ) -{ - Mat res1( data.size(), data.type() ), - res2( data.size(), data.type() ), - res3( data.size(), data.type() ); - Mat idxs( 1, data.rows, CV_32SC1 ); - for( int pi = 0; pi < data.rows; pi++ ) - { - idxs.at(0, pi) = pi; - // 1st way - const float* point = tr->getPoint(pi); - for( int di = 0; di < data.cols; di++ ) - res1.at(pi, di) = point[di]; - } - // 2nd way - tr->getPoints( idxs.ptr(0), data.rows, res2 ); - - // 3d way - tr->getPoints( idxs, res3 ); - - if( norm( res1, data, NORM_L1) != 0 || - norm( res2, data, NORM_L1) != 0 || - norm( res3, data, NORM_L1) != 0) - return CvTS::FAIL_BAD_ACCURACY; - return CvTS::OK; -} - -int CV_KDTreeTest_CPP::checkFindBoxed() -{ - vector min( dims, minValue), max(dims, maxValue); - vector indices; - tr->findOrthoRange( &min[0], &max[0], &indices ); - // TODO check indices - if( (int)indices.size() != featuresCount) - return CvTS::FAIL_BAD_ACCURACY; - return CvTS::OK; -} - -int CV_KDTreeTest_CPP::findNeighbors( Mat& points, Mat& neighbors ) -{ - const int emax = 20; - Mat neighbors2( neighbors.size(), CV_32SC1 ); - int j; - vector min(points.cols, minValue); - vector max(points.cols, maxValue); - for( int pi = 0; pi < points.rows; pi++ ) - { - // 1st way - tr->findNearest( points.ptr(pi), neighbors.cols, emax, neighbors.ptr(pi) ); - - // 2nd way - vector neighborsIdx2( neighbors2.cols, 0 ); - tr->findNearest( points.ptr(pi), neighbors2.cols, emax, &neighborsIdx2 ); - vector::const_iterator it2 = neighborsIdx2.begin(); - for( j = 0; it2 != neighborsIdx2.end(); ++it2, j++ ) - neighbors2.at(pi,j) = *it2; - } - - // compare results - if( norm( neighbors, neighbors2, NORM_L1 ) != 0 ) - return CvTS::FAIL_BAD_ACCURACY; - - return CvTS::OK; -} - -void CV_KDTreeTest_CPP::releaseModel() -{ - delete tr; -} - -//-------------------------------------------------------------------------------- -class CV_FlannTest : public NearestNeighborTest -{ -public: - CV_FlannTest( const char* test_name, const char* test_funcs ) - : NearestNeighborTest( test_name, test_funcs ) {} -protected: - void createIndex( const Mat& data, const IndexParams& params ); - int knnSearch( Mat& points, Mat& neighbors ); - int radiusSearch( Mat& points, Mat& neighbors ); - virtual void releaseModel(); - Index* index; -}; - -void CV_FlannTest::createIndex( const Mat& data, const IndexParams& params ) -{ - index = new Index( data, params ); -} - -int CV_FlannTest::knnSearch( Mat& points, Mat& neighbors ) -{ - Mat dist( points.rows, neighbors.cols, CV_32FC1); - int knn = 1, j; - - // 1st way - index->knnSearch( points, neighbors, dist, knn, SearchParams() ); - - // 2nd way - Mat neighbors1( neighbors.size(), CV_32SC1 ); - for( int i = 0; i < points.rows; i++ ) - { - float* fltPtr = points.ptr(i); - vector query( fltPtr, fltPtr + points.cols ); - vector indices( neighbors1.cols, 0 ); - vector dists( dist.cols, 0 ); - index->knnSearch( query, indices, dists, knn, SearchParams() ); - vector::const_iterator it = indices.begin(); - for( j = 0; it != indices.end(); ++it, j++ ) - neighbors1.at(i,j) = *it; - } - - // compare results - if( norm( neighbors, neighbors1, NORM_L1 ) != 0 ) - return CvTS::FAIL_BAD_ACCURACY; - - return CvTS::OK; -} - -int CV_FlannTest::radiusSearch( Mat& points, Mat& neighbors ) -{ - Mat dist( 1, neighbors.cols, CV_32FC1); - Mat neighbors1( neighbors.size(), CV_32SC1 ); - float radius = 10.0f; - int j; - - // radiusSearch can only search one feature at a time for range search - for( int i = 0; i < points.rows; i++ ) - { - // 1st way - Mat p( 1, points.cols, CV_32FC1, points.ptr(i) ), - n( 1, neighbors.cols, CV_32SC1, neighbors.ptr(i) ); - index->radiusSearch( p, n, dist, radius, SearchParams() ); - - // 2nd way - float* fltPtr = points.ptr(i); - vector query( fltPtr, fltPtr + points.cols ); - vector indices( neighbors1.cols, 0 ); - vector dists( dist.cols, 0 ); - index->radiusSearch( query, indices, dists, radius, SearchParams() ); - vector::const_iterator it = indices.begin(); - for( j = 0; it != indices.end(); ++it, j++ ) - neighbors1.at(i,j) = *it; - } - // compare results - if( norm( neighbors, neighbors1, NORM_L1 ) != 0 ) - return CvTS::FAIL_BAD_ACCURACY; - - return CvTS::OK; -} - -void CV_FlannTest::releaseModel() -{ - delete index; -} - -//--------------------------------------- -class CV_FlannLinearIndexTest : public CV_FlannTest -{ -public: - CV_FlannLinearIndexTest() : CV_FlannTest( "flann_linear", "LinearIndex" ) {} -protected: - virtual void createModel( const Mat& data ) { createIndex( data, LinearIndexParams() ); } - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); } -}; - -//--------------------------------------- -class CV_FlannKMeansIndexTest : public CV_FlannTest -{ -public: - CV_FlannKMeansIndexTest() : CV_FlannTest( "flann_kmeans", "KMeansIndex" ) {} -protected: - virtual void createModel( const Mat& data ) { createIndex( data, KMeansIndexParams() ); } - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return radiusSearch( points, neighbors ); } -}; - -//--------------------------------------- -class CV_FlannKDTreeIndexTest : public CV_FlannTest -{ -public: - CV_FlannKDTreeIndexTest() : CV_FlannTest( "flann_kdtree", "KDTreeIndex" ) {} -protected: - virtual void createModel( const Mat& data ) { createIndex( data, KDTreeIndexParams() ); } - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return radiusSearch( points, neighbors ); } -}; - -//---------------------------------------- -class CV_FlannCompositeIndexTest : public CV_FlannTest -{ -public: - CV_FlannCompositeIndexTest() : CV_FlannTest( "flann_composite", "CompositeIndex" ) {} -protected: - virtual void createModel( const Mat& data ) { createIndex( data, CompositeIndexParams() ); } - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); } -}; - -//---------------------------------------- -class CV_FlannAutotunedIndexTest : public CV_FlannTest -{ -public: - CV_FlannAutotunedIndexTest() : CV_FlannTest( "flann_autotuned", "AutotunedIndex" ) {} -protected: - virtual void createModel( const Mat& data ) { createIndex( data, AutotunedIndexParams() ); } - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); } -}; -//---------------------------------------- -class CV_FlannSavedIndexTest : public CV_FlannTest -{ -public: - CV_FlannSavedIndexTest() : CV_FlannTest( "flann_saved", "SavedIndex" ) {} -protected: - virtual void createModel( const Mat& data ); - virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); } -}; - -void CV_FlannSavedIndexTest::createModel(const cv::Mat &data) -{ - switch ( cvRandInt(ts->get_rng()) % 2 ) - { - //case 0: createIndex( data, LinearIndexParams() ); break; // nothing to save for linear search - case 0: createIndex( data, KMeansIndexParams() ); break; - case 1: createIndex( data, KDTreeIndexParams() ); break; - //case 2: createIndex( data, CompositeIndexParams() ); break; // nothing to save for linear search - //case 2: createIndex( data, AutotunedIndexParams() ); break; // possible linear index ! - default: assert(0); - } - char filename[50]; - tmpnam( filename ); - if(filename[0] == '\\') filename[0] = '_'; - index->save( filename ); - - createIndex( data, SavedIndexParams(filename)); - remove( filename ); -} - -CV_LSHTest lsh_test; -CV_SpillTreeTest_C spilltree_test_c; -CV_KDTreeTest_C kdtree_test_c; -CV_KDTreeTest_CPP kdtree_test_cpp; -CV_FlannLinearIndexTest flann_linear_test; -CV_FlannKMeansIndexTest flann_kmeans_test; -CV_FlannKDTreeIndexTest flann_kdtree_test; -CV_FlannCompositeIndexTest flann_composite_test; -CV_FlannAutotunedIndexTest flann_autotuned_test; -CV_FlannSavedIndexTest flann_saved_test; diff --git a/tests/cv/src/aoptflowhs.cpp b/tests/cv/src/aoptflowhs.cpp deleted file mode 100644 index 2d0ce8c..0000000 --- a/tests/cv/src/aoptflowhs.cpp +++ /dev/null @@ -1,431 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -/* Testing parameters */ -static char FuncName[] = "cvCalcOpticalFlowHS"; -static char TestName[] = "Optical flow (Horn & Schunck)"; -static char TestClass[] = "Algorithm"; - -static long lImageWidth; -static long lImageHeight; -static float lambda; - -#define EPSILON 0.0001f - -static int fmaCalcOpticalFlowHS( void ) -{ - /* Some Variables */ - int i,j,k; - - uchar* roiA; - uchar* roiB; - - float* VelocityX; - float* VelocityY; - - float* auxVelocityX; - float* auxVelocityY; - - float* DerX; - float* DerY; - float* DerT; - - long lErrors = 0; - - CvTermCriteria criteria; - - int usePrevious; - - int Stop = 0; - int iteration = 0; - float epsilon = 0; - - static int read_param = 0; - - /* Initialization global parameters */ - if( !read_param ) - { - read_param = 1; - /* Reading test-parameters */ - trslRead( &lImageHeight, "300", "Image height" ); - trslRead( &lImageWidth, "300", "Image width" ); - trssRead( &lambda, "20", "lambda" ); - } - - /* initialization - for warning disable */ - criteria.epsilon = 0; - criteria.max_iter = 0; - criteria.type = 1; - - /* Allocating memory for all frames */ - IplImage* imgA = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); - IplImage* imgB = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); - - IplImage* testVelocityX = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); - IplImage* testVelocityY = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); - - VelocityX = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - VelocityY = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - - auxVelocityX = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - auxVelocityY = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - - DerX = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - DerY = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - DerT = (float*)cvAlloc( lImageWidth*lImageHeight * sizeof(float) ); - - /* Filling images */ - ats1bInitRandom( 0, 255, (uchar*)imgA->imageData, lImageWidth * lImageHeight ); - ats1bInitRandom( 0, 255, (uchar*)imgB->imageData, lImageWidth * lImageHeight ); - - /* set ROI of images */ - roiA = (uchar*)imgA->imageData; - roiB = (uchar*)imgB->imageData; - - /* example of 3*3 ROI*/ - /*roiA[0] = 0; - roiA[1] = 1; - roiA[2] = 2; - roiA[lImageWidth] = 0; - roiA[lImageWidth+1] = 1; - roiA[lImageWidth+2] = 2; - roiA[2*lImageWidth] = 0; - roiA[2*lImageWidth+1] = 1; - roiA[2*lImageWidth+2] = 2; - - roiB[0] = 1; - roiB[1] = 2; - roiB[2] = 3; - roiB[lImageWidth] = 1; - roiB[lImageWidth+1] = 2; - roiB[lImageWidth+2] = 3; - roiB[2*lImageWidth] = 1; - roiB[2*lImageWidth+1] = 2; - roiB[2*lImageWidth+2] = 3;*/ -/****************************************************************************************\ -* Calculate derivatives * -\****************************************************************************************/ - for (i=0; iwidthStep + jr ] - - roiA[ (it)*imgA->widthStep + jl ] - + 2*roiA[ (i)*imgA->widthStep + jr ] - - 2*roiA[ (i)*imgA->widthStep + jl ] - + roiA[ (ib)*imgA->widthStep + jr ] - - roiA[ (ib)*imgA->widthStep + jl ])/8 ; - - DerY[ i*lImageWidth + j ] = (float) - ( roiA[ (ib)*imgA->widthStep + jl ] - + 2*roiA[ (ib)*imgA->widthStep + j ] - + roiA[ (ib)*imgA->widthStep + jr ] - - roiA[ (it)*imgA->widthStep + jl ] - - 2*roiA[ (it)*imgA->widthStep + j ] - - roiA[ (it)*imgA->widthStep + jr ])/8 ; - - DerT[ i*lImageWidth + j ] = (float) - (roiB[i*imgB->widthStep + j] - roiA[i*imgA->widthStep + j]); - } - } -for( usePrevious = 0; usePrevious < 2; usePrevious++ ) -{ -/****************************************************************************************\ -* Cases * -\****************************************************************************************/ - for ( k = 0; k < 4; k++ ) - { - switch (k) - { - case 0: - { - criteria.type = CV_TERMCRIT_ITER; - criteria.max_iter = 3; - - trsWrite( ATS_LST|ATS_CON, - "usePrevious = %d, criteria = ITER, max_iter = %d\n", - usePrevious, criteria.max_iter); - - break; - } - case 1: - { - criteria.type = CV_TERMCRIT_EPS; - criteria.epsilon = 0.001f; - trsWrite( ATS_LST|ATS_CON, - "usePrevious = %d, criteria = EPS, epsilon = %f\n", - usePrevious, criteria.epsilon); - - break; - } - case 2: - { - criteria.type = CV_TERMCRIT_EPS | CV_TERMCRIT_ITER; - criteria.epsilon = 0.0001f; - criteria.max_iter = 3; - trsWrite( ATS_LST|ATS_CON, - "usePrevious = %d," - "criteria = EPS|ITER," - "epsilon = %f, max_iter = %d\n", - usePrevious, criteria.epsilon, criteria.max_iter); - - break; - } - case 3: - { - criteria.type = CV_TERMCRIT_EPS | CV_TERMCRIT_ITER; - criteria.epsilon = 0.00001f; - criteria.max_iter = 100; - trsWrite( ATS_LST|ATS_CON, - "usePrevious = %d," - "criteria = EPS|ITER," - "epsilon = %f, max_iter = %d\n", - usePrevious, criteria.epsilon, criteria.max_iter); - - break; - } - } - Stop = 0; - - /* Run CVL function */ - cvCalcOpticalFlowHS( imgA , imgB, usePrevious, - testVelocityX, testVelocityY, - lambda, criteria ); - - /* Calc by other way */ - if (!usePrevious) - { - /* Filling initial velocity with zero */ - for (i = 0; i < lImageWidth * lImageHeight; i++ ) - { - VelocityX[i] = 0 ; - VelocityY[i] = 0 ; - } - } - iteration = 0; - while ( !Stop ) - { - float* oldX; - float* oldY; - float* newX; - float* newY; - - iteration++; - - if ( iteration & 1 ) - { - oldX = VelocityX; - oldY = VelocityY; - newX = auxVelocityX; - newY = auxVelocityY; - } - else - { - oldX = auxVelocityX; - oldY = auxVelocityY; - newX = VelocityX; - newY = VelocityY; - } - - for( i = 0; i < lImageHeight; i++) - { - for(j = 0; j< lImageWidth; j++) - { - float aveX = 0; - float aveY = 0; - float dx,dy,dt; - - aveX +=(j==0) ? oldX[ i*lImageWidth + j ] : oldX[ i*lImageWidth + j-1 ]; - aveX +=(j==lImageWidth-1) ? oldX[ i*lImageWidth + j ] : - oldX[ i*lImageWidth + j+1 ]; - aveX +=(i==0) ? oldX[ i*lImageWidth + j ] : oldX[ (i-1)*lImageWidth + j ]; - aveX +=(i==lImageHeight-1) ? oldX[ i*lImageWidth + j ] : - oldX[ (i+1)*lImageWidth + j ]; - aveX /=4; - - aveY +=(j==0) ? oldY[ i*lImageWidth + j ] : oldY[ i*lImageWidth + j-1 ]; - aveY +=(j==lImageWidth-1) ? oldY[ i*lImageWidth + j ] : - oldY[ i*lImageWidth + j+1 ]; - aveY +=(i==0) ? oldY[ i*lImageWidth + j ] : oldY[ (i-1)*lImageWidth + j ]; - aveY +=(i==lImageHeight-1) ? oldY[ i*lImageWidth + j ] : - oldY[ (i+1)*lImageWidth + j ]; - aveY /=4; - - dx = DerX[ i*lImageWidth + j ]; - dy = DerY[ i*lImageWidth + j ]; - dt = DerT[ i*lImageWidth + j ]; - - /* Horn & Schunck pure formulas */ - newX[ i*lImageWidth + j ] = aveX - ( dx * aveX + - dy * aveY + dt ) * lambda * dx / - (1 + lambda * ( dx*dx + dy*dy )); - - newY[ i*lImageWidth + j ] = aveY - ( dx * aveX + - dy * aveY + dt ) * lambda * dy / - (1 + lambda * ( dx*dx + dy*dy )); - } - } - /* evaluate epsilon */ - epsilon = 0; - for ( i = 0; i < lImageHeight; i++) - { - for ( j = 0; j < lImageWidth; j++) - { - epsilon = MAX((float)fabs(newX[i*lImageWidth + j] - - oldX[i*lImageWidth + j]), epsilon ); - epsilon = MAX((float)fabs(newY[i*lImageWidth + j] - - oldY[i*lImageWidth + j]), epsilon ); - } - } - - switch (criteria.type) - { - case CV_TERMCRIT_ITER: - Stop = (criteria.max_iter == iteration );break; - case CV_TERMCRIT_EPS: - Stop = (criteria.epsilon > epsilon );break; - case CV_TERMCRIT_ITER|CV_TERMCRIT_EPS: - Stop = ( ( criteria.epsilon > epsilon ) || - ( criteria.max_iter == iteration )); - break; - } - if (Stop) - { - if ( (newX != VelocityX) && (newY != VelocityY) ) - { - memcpy( VelocityX, newX, lImageWidth * lImageHeight * sizeof(float) ); - memcpy( VelocityY, newY, lImageWidth * lImageHeight * sizeof(float) ); - } - } - } - trsWrite( ATS_LST|ATS_CON, - "%d iterations are made\n", iteration ); - - for( i = 0; i < lImageHeight; i++) - { - for(j = 0; j< lImageWidth; j++) - { - float tvx = ((float*)(testVelocityX->imageData + i*testVelocityX->widthStep))[j]; - float tvy = ((float*)(testVelocityY->imageData + i*testVelocityY->widthStep))[j]; - - if (( fabs( tvx - VelocityX[i*lImageWidth + j])>EPSILON )|| - ( fabs( tvy - VelocityY[i*lImageWidth + j])>EPSILON ) ) - { - //trsWrite( ATS_LST | ATS_CON, " ValueX %f \n", - // testVelocityX[i*lROIWidth + j] ); - //trsWrite( ATS_LST | ATS_CON, " mustX %f \n", - // VelocityX[i*lROIWidth + j] ); - - //trsWrite( ATS_LST | ATS_CON, " ValueY %f \n", - // testVelocityY[i*lROIWidth + j] ); - //trsWrite( ATS_LST | ATS_CON, " mustY %f \n", - // VelocityY[i*lROIWidth + j] ); - - //trsWrite( ATS_LST | ATS_CON, " Coordinates %d %d\n", i, j ); - - lErrors++; - } - } - } - }/* for */ - /* Filling initial velocity with zero */ - cvZero( testVelocityX ); - cvZero( testVelocityY ); - for (i = 0; i < lImageWidth * lImageHeight; i++ ) - { - VelocityX[i] = 0 ; - VelocityY[i] = 0 ; - } -} - - /* Free memory */ - cvFree( &VelocityX ); - cvFree( &VelocityY ); - cvFree( &auxVelocityX ); - cvFree( &auxVelocityY ); - - - cvFree( &DerX ); - cvFree( &DerY ); - cvFree( &DerT ); - - cvReleaseImage( &imgA ); - cvReleaseImage( &imgB ); - cvReleaseImage( &testVelocityX ); - cvReleaseImage( &testVelocityY ); - - - if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" ); - else return trsResult( TRS_FAIL, "Total fixed %d errors", lErrors ); -} /*fmaCalcOpticalFlowHS*/ - -void InitACalcOpticalFlowHS( void ) -{ - /* Registering test function */ - trsReg( FuncName, TestName, TestClass, fmaCalcOpticalFlowHS ); -} /* InitACalcOpticalFlowHS */ - -#endif - -/* End of file. */ diff --git a/tests/cv/src/aoptflowlk.cpp b/tests/cv/src/aoptflowlk.cpp deleted file mode 100644 index ba05aa0..0000000 --- a/tests/cv/src/aoptflowlk.cpp +++ /dev/null @@ -1,304 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -#if 0 - -/* Testing parameters */ -static char FuncName[] = "cvCalcOpticalFlowLK"; -static char TestName[] = "Optical flow (Lucas & Kanade)"; -static char TestClass[] = "Algorithm"; - -static long lImageWidth; -static long lImageHeight; -static long lWinWidth; -static long lWinHeight; - -#define EPSILON 0.00001f - -static int fmaCalcOpticalFlowLK( void ) -{ - /* Some Variables */ - int* WH = NULL; - int* WV = NULL; - - int W3[3] = { 1, 2, 1 }; - int W5[5] = { 1, 4, 6, 4, 1 }; - int W7[7] = { 1, 6, 15, 20, 15, 6, 1 }; - int W9[9] = { 1, 8, 28, 56, 70, 56, 28, 8, 1 }; - int W11[11] = {1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1 }; - - int i,j,m,k; - uchar* roiA; - uchar* roiB; - - float* VelocityX; - float* VelocityY; - - float* DerivativeX; - float* DerivativeY; - float* DerivativeT; - - long lErrors = 0; - CvSize winSize; - - int HRad; - int VRad; - - float A1, A2, B1, B2, C1, C2; - - static int read_param = 0; - - /* Initialization global parameters */ - if( !read_param ) - { - read_param = 1; - /* Reading test-parameters */ - trslRead( &lImageHeight, "563", "Image height" ); - trslRead( &lImageWidth, "345", "Image width" ); - trslRead( &lWinHeight, "7", "win height 3/5/7/9/11 " ); - trslRead( &lWinWidth, "9", "win width 3/5/7/9/11 " ); - } - - /* Checking all sizes of source histogram in ranges */ - IplImage* imgA = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); - IplImage* imgB = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); - - IplImage* testVelocityX = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); - IplImage* testVelocityY = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); - - VelocityX = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); - VelocityY = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); - - DerivativeX = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); - DerivativeY = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); - DerivativeT = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); - - winSize.height = lWinHeight; - winSize.width = lWinWidth; - - switch (lWinHeight) - { - case 3: - WV = W3; break; - case 5: - WV = W5; break; - case 7: - WV = W7; break; - case 9: - WV = W9; break; - case 11: - WV = W11; break; - } - switch (lWinWidth) - { - case 3: - WH = W3; break; - case 5: - WH = W5; break; - case 7: - WH = W7; break; - case 9: - WH = W9; break; - case 11: - WH = W11; break; - - } - - HRad = (winSize.width - 1)/2; - VRad = (winSize.height - 1)/2; - - /* Filling images */ - ats1bInitRandom( 0, 255, (uchar*)imgA->imageData, lImageHeight * imgA->widthStep ); - ats1bInitRandom( 0, 255, (uchar*)imgB->imageData, imgA->widthStep * lImageHeight ); - - /* Run CVL function */ - cvCalcOpticalFlowLK( imgA , imgB, winSize, - testVelocityX, testVelocityY ); - - - /* Calc by other way */ - roiA = (uchar*)imgA->imageData; - roiB = (uchar*)imgB->imageData; - - /* Calculate derivatives */ - for (i=0; iheight; i++) - { - for(j=0; jwidth; j++) - { - int jr,jl,it,ib; - - if ( j==imgA->width-1 ) - jr = imgA->width-1; - else jr = j + 1; - - if ( j==0 ) - jl = 0; - else jl = j - 1; - - if ( i==(imgA->height - 1) ) - ib = imgA->height - 1; - else ib = i + 1; - - if ( i==0 ) - it = 0; - else it = i - 1; - - DerivativeX[ i*lImageWidth + j ] = (float) - (roiA[ (it)*imgA->widthStep + jr ] - - roiA[ (it)*imgA->widthStep + jl ] - + 2*roiA[ (i)*imgA->widthStep + jr ] - - 2*roiA[ (i)*imgA->widthStep + jl ] - + roiA[ (ib)*imgA->widthStep + jr ] - - roiA[ (ib)*imgA->widthStep + jl ]) ; - - DerivativeY[ i*lImageWidth + j ] = (float) - ( roiA[ (ib)*imgA->widthStep + jl ] - + 2*roiA[ (ib)*imgA->widthStep + j ] - + roiA[ (ib)*imgA->widthStep + jr ] - - roiA[ (it)*imgA->widthStep + jl ] - - 2*roiA[ (it)*imgA->widthStep + j ] - - roiA[ (it)*imgA->widthStep + jr ]) ; - - DerivativeT[ i*lImageWidth + j ] = (float) - (roiB[i*imgB->widthStep + j] - roiA[i*imgA->widthStep + j])*8; - } - } - - for( i = 0; i < lImageHeight; i++) - { - for(j = 0; j< lImageWidth; j++) - { - A1 =0; - A2 =0; - B1 =0; - B2 =0; - C1= 0; - C2= 0; - - for( k = -VRad ; k <= VRad ; k++ ) - { - for( m = - HRad; m <= HRad ; m++ ) - { - int coord = (i+k)*lImageWidth + (j+m); - if ( (j+m<0) || - (j+m >lImageWidth-1) || - ( (k+i)<0 ) || - ( (k+i)>lImageHeight-1) ) - {continue;} - - A1+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeY[coord]; - A2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeX[coord]; - B1+=WV[k+VRad]*WH[m+HRad]* DerivativeY[coord]*DerivativeY[coord]; - B2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeY[coord]; - C1+=WV[k+VRad]*WH[m+HRad]* DerivativeY[coord]*DerivativeT[coord]; - C2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeT[coord]; - } - } - if (A1*B2 - A2*B1) - { - VelocityX[i*lImageWidth + j] = - (C1*B2 - C2*B1)/(A1*B2 - A2*B1); - VelocityY[i*lImageWidth + j] = - (A1*C2 - A2*C1)/(A1*B2 - A2*B1); - } - else if ( (A1+A2)*(A1+A2) + (B1+B2)*(B1+B2) ) - { /* Calculate Normal flow */ - VelocityX[i*lImageWidth + j] = -(A1+A2)*(C1+C2)/((A1+A2)*(A1+A2)+(B1+B2)*(B1+B2)); - VelocityY[i*lImageWidth + j] = -(B1+B2)*(C1+C2)/((A1+A2)*(A1+A2)+(B1+B2)*(B1+B2)); - } - else - { - VelocityX[i*lImageWidth + j] = 0; - VelocityY[i*lImageWidth + j] = 0; - } - } - } - - for( i = 0; i < lImageHeight; i++) - { - for(j = 0; j< lImageWidth; j++) - { - float tvx = ((float*)(testVelocityX->imageData + i*testVelocityX->widthStep))[j]; - float tvy = ((float*)(testVelocityY->imageData + i*testVelocityY->widthStep))[j]; - - - - if (( fabs(tvx - VelocityX[i*lImageWidth + j])>EPSILON )|| - ( fabs(tvy - VelocityY[i*lImageWidth + j])>EPSILON ) ) - { - //trsWrite( ATS_LST | ATS_CON, " ValueX %f \n", tvx ); - //trsWrite( ATS_LST | ATS_CON, " mustX %f \n", VelocityX[i*lImageWidth + j] ); - - //trsWrite( ATS_LST | ATS_CON, " ValueY %f \n", tvy ); - //trsWrite( ATS_LST | ATS_CON, " mustY %f \n", VelocityY[i*lImageWidth + j] ); - - //trsWrite( ATS_LST | ATS_CON, " Coordinates %d %d\n", i, j ); - - lErrors++; - } - } - } - cvFree( &VelocityX ); - cvFree( &VelocityY ); - - cvFree( &DerivativeX ); - cvFree( &DerivativeY ); - cvFree( &DerivativeT ); - - cvReleaseImage( &imgA ); - cvReleaseImage( &imgB ); - cvReleaseImage( &testVelocityX ); - cvReleaseImage( &testVelocityY ); - - - if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" ); - else return trsResult( TRS_FAIL, "Total fixed %d errors", lErrors ); -} /*fmaCalcOpticalFlowLK*/ - -void InitACalcOpticalFlowLK( void ) -{ - /* Registering test function */ - trsReg( FuncName, TestName, TestClass, fmaCalcOpticalFlowLK ); -} /* InitAACalcOpticalFlowLK */ - -#endif - -/* End of file. */ diff --git a/tests/cv/src/aoptflowpyrlk.cpp b/tests/cv/src/aoptflowpyrlk.cpp deleted file mode 100644 index 25966f9..0000000 --- a/tests/cv/src/aoptflowpyrlk.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -/* ///////////////////// pyrlk_test ///////////////////////// */ - -class CV_OptFlowPyrLKTest : public CvTest -{ -public: - CV_OptFlowPyrLKTest(); -protected: - void run(int); -}; - - -CV_OptFlowPyrLKTest::CV_OptFlowPyrLKTest(): - CvTest( "optflow-pyrlk", "cvCalcOpticalFlowPyrLK" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_OptFlowPyrLKTest::run( int ) -{ - int code = CvTS::OK; - - const double success_error_level = 0.2; - const int bad_points_max = 2; - - /* test parameters */ - double max_err = 0., sum_err = 0; - int pt_cmpd = 0; - int pt_exceed = 0; - int merr_i = 0, merr_j = 0, merr_k = 0; - char filename[1000]; - - CvPoint2D32f *u = 0, *v = 0, *v2 = 0; - CvMat *_u = 0, *_v = 0, *_v2 = 0; - char* status = 0; - - IplImage* imgI = 0; - IplImage* imgJ = 0; - - int n = 0, i = 0; - - sprintf( filename, "%soptflow/%s", ts->get_data_path(), "lk_prev.dat" ); - _u = (CvMat*)cvLoad( filename ); - - if( !_u ) - { - ts->printf( CvTS::LOG, "could not read %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - sprintf( filename, "%soptflow/%s", ts->get_data_path(), "lk_next.dat" ); - _v = (CvMat*)cvLoad( filename ); - - if( !_v ) - { - ts->printf( CvTS::LOG, "could not read %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - if( _u->cols != 2 || CV_MAT_TYPE(_u->type) != CV_32F || - _v->cols != 2 || CV_MAT_TYPE(_v->type) != CV_32F || _v->rows != _u->rows ) - { - ts->printf( CvTS::LOG, "the loaded matrices of points are not valid\n" ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - - } - - u = (CvPoint2D32f*)_u->data.fl; - v = (CvPoint2D32f*)_v->data.fl; - - /* allocate adidtional buffers */ - _v2 = cvCloneMat( _u ); - v2 = (CvPoint2D32f*)_v2->data.fl; - - /* read first image */ - sprintf( filename, "%soptflow/%s", ts->get_data_path(), "rock_1.bmp" ); - imgI = cvLoadImage( filename, -1 ); - - if( !imgI ) - { - ts->printf( CvTS::LOG, "could not read %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - /* read second image */ - sprintf( filename, "%soptflow/%s", ts->get_data_path(), "rock_2.bmp" ); - imgJ = cvLoadImage( filename, -1 ); - - if( !imgJ ) - { - ts->printf( CvTS::LOG, "could not read %s\n", filename ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - n = _u->rows; - status = (char*)cvAlloc(n*sizeof(status[0])); - - /* calculate flow */ - cvCalcOpticalFlowPyrLK( imgI, imgJ, 0, 0, u, v2, n, cvSize( 20, 20 ), - 4, status, 0, cvTermCriteria( CV_TERMCRIT_ITER| - CV_TERMCRIT_EPS, 30, 0.01f ), 0 ); - - /* compare results */ - for( i = 0; i < n; i++ ) - { - if( status[i] != 0 ) - { - double err; - if( cvIsNaN(v[i].x) ) - { - merr_j++; - continue; - } - - err = fabs(v2[i].x - v[i].x) + fabs(v2[i].y - v[i].y); - if( err > max_err ) - { - max_err = err; - merr_i = i; - } - - pt_exceed += err > success_error_level; - if( pt_exceed > bad_points_max ) - { - ts->printf( CvTS::LOG, - "The number of poorly tracked points is too big (>=%d)\n", pt_exceed ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - sum_err += err; - pt_cmpd++; - } - else - { - if( !cvIsNaN( v[i].x )) - { - merr_i = i; - merr_k++; - ts->printf( CvTS::LOG, "The algorithm lost the point #%d\n", i ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - } - } - - if( max_err > 1 ) - { - ts->printf( CvTS::LOG, "Maximum tracking error is too big (=%g)\n", max_err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - cvFree( &status ); - cvReleaseMat( &_u ); - cvReleaseMat( &_v ); - cvReleaseMat( &_v2 ); - - cvReleaseImage( &imgI ); - cvReleaseImage( &imgJ ); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_OptFlowPyrLKTest optflow_pyr_lk_test; - -/* End of file. */ diff --git a/tests/cv/src/aposit.cpp b/tests/cv/src/aposit.cpp deleted file mode 100644 index de45f82..0000000 --- a/tests/cv/src/aposit.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -class CV_POSITTest : public CvTest -{ -public: - CV_POSITTest(); -protected: - void run(int); -}; - - -CV_POSITTest::CV_POSITTest(): - CvTest( "posit", "cvPOSIT" ) -{ - test_case_count = 20; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_POSITTest::run( int start_from ) -{ - int code = CvTS::OK; - - /* fixed parameters output */ - /*float rot[3][3]={ 0.49010f, 0.85057f, 0.19063f, - -0.56948f, 0.14671f, 0.80880f, - 0.65997f, -0.50495f, 0.55629f }; - - float trans[3] = { 0.0f, 0.0f, 40.02637f }; - */ - - /* Some variables */ - int i, counter; - - CvTermCriteria criteria; - CvPoint3D32f* obj_points; - CvPoint2D32f* img_points; - CvPOSITObject* object; - - float angleX, angleY, angleZ; - CvRNG* rng = ts->get_rng(); - int progress = 0; - - CvMat* true_rotationX = cvCreateMat( 3, 3, CV_32F ); - CvMat* true_rotationY = cvCreateMat( 3, 3, CV_32F ); - CvMat* true_rotationZ = cvCreateMat( 3, 3, CV_32F ); - CvMat* tmp_matrix = cvCreateMat( 3, 3, CV_32F ); - CvMat* true_rotation = cvCreateMat( 3, 3, CV_32F ); - CvMat* rotation = cvCreateMat( 3, 3, CV_32F ); - CvMat* translation = cvCreateMat( 3, 1, CV_32F ); - CvMat* true_translation = cvCreateMat( 3, 1, CV_32F ); - - const float flFocalLength = 760.f; - const float flEpsilon = 0.5f; - - /* Initilization */ - criteria.type = CV_TERMCRIT_EPS|CV_TERMCRIT_ITER; - criteria.epsilon = flEpsilon; - criteria.max_iter = 10000; - - /* Allocating source arrays; */ - obj_points = (CvPoint3D32f*)cvAlloc( 8 * sizeof(CvPoint3D32f) ); - img_points = (CvPoint2D32f*)cvAlloc( 8 * sizeof(CvPoint2D32f) ); - - /* Fill points arrays with values */ - - /* cube model with edge size 10 */ - obj_points[0].x = 0; obj_points[0].y = 0; obj_points[0].z = 0; - obj_points[1].x = 10; obj_points[1].y = 0; obj_points[1].z = 0; - obj_points[2].x = 10; obj_points[2].y = 10; obj_points[2].z = 0; - obj_points[3].x = 0; obj_points[3].y = 10; obj_points[3].z = 0; - obj_points[4].x = 0; obj_points[4].y = 0; obj_points[4].z = 10; - obj_points[5].x = 10; obj_points[5].y = 0; obj_points[5].z = 10; - obj_points[6].x = 10; obj_points[6].y = 10; obj_points[6].z = 10; - obj_points[7].x = 0; obj_points[7].y = 10; obj_points[7].z = 10; - - /* Loop for test some random object positions */ - for( counter = start_from; counter < test_case_count; counter++ ) - { - ts->update_context( this, counter, true ); - progress = update_progress( progress, counter, test_case_count, 0 ); - - /* set all rotation matrix to zero */ - cvZero( true_rotationX ); - cvZero( true_rotationY ); - cvZero( true_rotationZ ); - - /* fill random rotation matrix */ - angleX = (float)(cvTsRandReal(rng)*2*CV_PI); - angleY = (float)(cvTsRandReal(rng)*2*CV_PI); - angleZ = (float)(cvTsRandReal(rng)*2*CV_PI); - - true_rotationX->data.fl[0 *3+ 0] = 1; - true_rotationX->data.fl[1 *3+ 1] = (float)cos(angleX); - true_rotationX->data.fl[2 *3+ 2] = true_rotationX->data.fl[1 *3+ 1]; - true_rotationX->data.fl[1 *3+ 2] = -(float)sin(angleX); - true_rotationX->data.fl[2 *3+ 1] = -true_rotationX->data.fl[1 *3+ 2]; - - true_rotationY->data.fl[1 *3+ 1] = 1; - true_rotationY->data.fl[0 *3+ 0] = (float)cos(angleY); - true_rotationY->data.fl[2 *3+ 2] = true_rotationY->data.fl[0 *3+ 0]; - true_rotationY->data.fl[0 *3+ 2] = -(float)sin(angleY); - true_rotationY->data.fl[2 *3+ 0] = -true_rotationY->data.fl[0 *3+ 2]; - - true_rotationZ->data.fl[2 *3+ 2] = 1; - true_rotationZ->data.fl[0 *3+ 0] = (float)cos(angleZ); - true_rotationZ->data.fl[1 *3+ 1] = true_rotationZ->data.fl[0 *3+ 0]; - true_rotationZ->data.fl[0 *3+ 1] = -(float)sin(angleZ); - true_rotationZ->data.fl[1 *3+ 0] = -true_rotationZ->data.fl[0 *3+ 1]; - - cvMatMul( true_rotationX, true_rotationY, tmp_matrix); - cvMatMul( tmp_matrix, true_rotationZ, true_rotation); - - /* fill translation vector */ - true_translation->data.fl[2] = (float)(cvRandReal(rng)*(2*flFocalLength-40) + 60); - true_translation->data.fl[0] = (float)((cvRandReal(rng)*2-1)*true_translation->data.fl[2]); - true_translation->data.fl[1] = (float)((cvRandReal(rng)*2-1)*true_translation->data.fl[2]); - - /* calculate perspective projection */ - for ( i = 0; i < 8; i++ ) - { - float vec[3]; - CvMat Vec = cvMat( 3, 1, CV_32F, vec ); - CvMat Obj_point = cvMat( 3, 1, CV_32F, &obj_points[i].x ); - - cvMatMul( true_rotation, &Obj_point, &Vec ); - - vec[0] += true_translation->data.fl[0]; - vec[1] += true_translation->data.fl[1]; - vec[2] += true_translation->data.fl[2]; - - img_points[i].x = flFocalLength * vec[0] / vec[2]; - img_points[i].y = flFocalLength * vec[1] / vec[2]; - } - - /*img_points[0].x = 0 ; img_points[0].y = 0; - img_points[1].x = 80; img_points[1].y = -93; - img_points[2].x = 245;img_points[2].y = -77; - img_points[3].x = 185;img_points[3].y = 32; - img_points[4].x = 32; img_points[4].y = 135; - img_points[5].x = 99; img_points[5].y = 35; - img_points[6].x = 247; img_points[6].y = 62; - img_points[7].x = 195; img_points[7].y = 179; - */ - - object = cvCreatePOSITObject( obj_points, 8 ); - cvPOSIT( object, img_points, flFocalLength, criteria, - rotation->data.fl, translation->data.fl ); - cvReleasePOSITObject( &object ); - - code = cvTsCmpEps2( ts, rotation, true_rotation, flEpsilon, false, "rotation matrix" ); - if( code < 0 ) - goto _exit_; - - code = cvTsCmpEps2( ts, translation, true_translation, flEpsilon, false, "translation vector" ); - if( code < 0 ) - goto _exit_; - } - -_exit_: - - cvFree( &obj_points ); - cvFree( &img_points ); - - cvReleaseMat( &true_rotationX ); - cvReleaseMat( &true_rotationY ); - cvReleaseMat( &true_rotationZ ); - cvReleaseMat( &tmp_matrix ); - cvReleaseMat( &true_rotation ); - cvReleaseMat( &rotation ); - cvReleaseMat( &translation ); - cvReleaseMat( &true_translation ); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_POSITTest posit_test; - -/* End of file. */ diff --git a/tests/cv/src/apyrsegmentation.cpp b/tests/cv/src/apyrsegmentation.cpp deleted file mode 100644 index 9b9d6a4..0000000 --- a/tests/cv/src/apyrsegmentation.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_PyrSegmentationTest : public CvTest -{ -public: - CV_PyrSegmentationTest(); -protected: - void run(int); -}; - -#define SCAN 0 - -CV_PyrSegmentationTest::CV_PyrSegmentationTest(): - CvTest( "segmentation-pyramid", "cvPyrSegmentation" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_PyrSegmentationTest::run( int /*start_from*/ ) -{ - const int level = 5; - const double range = 15; - - int code = CvTS::OK; - - CvPoint _cp[] ={{33,33}, {43,33}, {43,43}, {33,43}}; - CvPoint _cp2[] ={{50,50}, {70,50}, {70,70}, {50,70}}; - CvPoint* cp = _cp; - CvPoint* cp2 = _cp2; - CvConnectedComp *dst_comp[3]; - CvRect rect[3] = {{50,50,21,21}, {0,0,128,128}, {33,33,11,11}}; - double a[3] = {441.0, 15822.0, 121.0}; - -/* ippiPoint cp3[] ={130,130, 150,130, 150,150, 130,150}; */ -/* CvPoint cp[] ={0,0, 5,5, 5,0, 10,5, 10,0, 15,5, 15,0}; */ - int nPoints = 4; - int block_size = 1000; - - CvMemStorage *storage; /* storage for connected component writing */ - CvSeq *comp; - - CvRNG* rng = ts->get_rng(); - int i, j, iter; - - IplImage *image, *image_f, *image_s; - CvSize size = {128, 128}; - const int threshold1 = 50, threshold2 = 50; - - rect[1].width = size.width; - rect[1].height = size.height; - a[1] = size.width*size.height - a[0] - a[2]; - - OPENCV_CALL( storage = cvCreateMemStorage( block_size ) ); - - for( iter = 0; iter < 2; iter++ ) - { - int channels = iter == 0 ? 1 : 3; - int mask[] = {0,0,0}; - - image = cvCreateImage(size, 8, channels ); - image_s = cvCloneImage( image ); - image_f = cvCloneImage( image ); - - if( channels == 1 ) - { - int color1 = 30, color2 = 110, color3 = 190; - - cvSet( image, cvScalarAll(color1)); - cvFillPoly( image, &cp, &nPoints, 1, cvScalar(color2)); - cvFillPoly( image, &cp2, &nPoints, 1, cvScalar(color3)); - } - else - { - CvScalar color1 = CV_RGB(30,30,30), color2 = CV_RGB(255,0,0), color3 = CV_RGB(0,255,0); - - assert( channels == 3 ); - cvSet( image, color1 ); - cvFillPoly( image, &cp, &nPoints, 1, color2); - cvFillPoly( image, &cp2, &nPoints, 1, color3); - } - - cvRandArr( rng, image_f, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(range*2) ); - cvAddWeighted( image, 1, image_f, 1, -range, image_f ); - - cvPyrSegmentation( image_f, image_s, - storage, &comp, - level, threshold1, threshold2 ); - - if(comp->total != 3) - { - ts->printf( CvTS::LOG, - "The segmentation function returned %d (not 3) components\n", comp->total ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - /* read the connected components */ - dst_comp[0] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 0 ); - dst_comp[1] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 1 ); - dst_comp[2] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 2 ); - - /*{ - for( i = 0; i < 3; i++ ) - { - CvRect r = dst_comp[i]->rect; - cvRectangle( image_s, cvPoint(r.x,r.y), cvPoint(r.x+r.width,r.y+r.height), - CV_RGB(255,255,255), 3, 8, 0 ); - } - - cvNamedWindow( "test", 1 ); - cvShowImage( "test", image_s ); - cvWaitKey(0); - }*/ - - code = cvTsCmpEps2( ts, image, image_s, 10, false, "the output image" ); - if( code < 0 ) - goto _exit_; - - for( i = 0; i < 3; i++) - { - for( j = 0; j < 3; j++ ) - { - if( !mask[j] && dst_comp[i]->area == a[j] && - dst_comp[i]->rect.x == rect[j].x && - dst_comp[i]->rect.y == rect[j].y && - dst_comp[i]->rect.width == rect[j].width && - dst_comp[i]->rect.height == rect[j].height ) - { - mask[j] = 1; - break; - } - } - if( j == 3 ) - { - ts->printf( CvTS::LOG, "The component #%d is incorrect\n", i ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - } - - cvReleaseImage(&image_f); - cvReleaseImage(&image); - cvReleaseImage(&image_s); - } - -_exit_: - - cvReleaseMemStorage( &storage ); - cvReleaseImage(&image_f); - cvReleaseImage(&image); - cvReleaseImage(&image_s); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_PyrSegmentationTest pyr_segmentation_test; - -/* End of file. */ diff --git a/tests/cv/src/areprojectImageTo3D.cpp b/tests/cv/src/areprojectImageTo3D.cpp deleted file mode 100644 index e61577a..0000000 --- a/tests/cv/src/areprojectImageTo3D.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include - -using namespace cv; -using namespace std; - -template double thres() { return 1.0; } -template<> double thres() { return 1e-5; } - -class CV_ReprojectImageTo3DTest : public CvTest -{ -public: - CV_ReprojectImageTo3DTest() - : CvTest( "reprojectImageTo3D", "cvReprojectImageTo3D") - { - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - } - ~CV_ReprojectImageTo3DTest() {} -protected: - - - void run(int) - { - ts->set_failed_test_info(CvTS::OK); - int progress = 0; - int caseId = 0; - - progress = update_progress( progress, 1, 14, 0 ); - runCase(++caseId, -100.f, 100.f); - progress = update_progress( progress, 2, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 3, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 4, 14, 0 ); - runCase(++caseId, 10, 100); - progress = update_progress( progress, 5, 14, 0 ); - - runCase(++caseId, -100.f, 100.f); - progress = update_progress( progress, 6, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 7, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 8, 14, 0 ); - runCase(++caseId, 10, 100); - progress = update_progress( progress, 10, 14, 0 ); - - runCase(++caseId, -100.f, 100.f); - progress = update_progress( progress, 11, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 12, 14, 0 ); - runCase(++caseId, -100, 100); - progress = update_progress( progress, 13, 14, 0 ); - runCase(++caseId, 10, 100); - progress = update_progress( progress, 14, 14, 0 ); - } - - template double error(const Vec& v1, const Vec& v2) const - { - double tmp, sum = 0; - double nsum = 0; - for(int i = 0; i < 3; ++i) - { - tmp = v1[i]; - nsum += tmp * tmp; - - tmp = tmp - v2[i]; - sum += tmp * tmp; - - } - return sqrt(sum)/(sqrt(nsum)+1.); - } - - template void runCase(int caseId, InT min, InT max) - { - typedef Vec out3d_t; - - bool handleMissingValues = (unsigned)theRNG() % 2 == 0; - - Mat_ disp(Size(320, 240)); - randu(disp, Scalar(min), Scalar(max)); - - if (handleMissingValues) - disp(disp.rows/2, disp.cols/2) = min - 1; - - Mat_ Q(4, 4); - randu(Q, Scalar(-5), Scalar(5)); - - Mat_ _3dImg(disp.size()); - - CvMat cvdisp = disp; CvMat cv_3dImg = _3dImg; CvMat cvQ = Q; - cvReprojectImageTo3D( &cvdisp, &cv_3dImg, &cvQ, handleMissingValues ); - - if (numeric_limits::max() == numeric_limits::max()) - reprojectImageTo3D(disp, _3dImg, Q, handleMissingValues); - - for(int y = 0; y < disp.rows; ++y) - for(int x = 0; x < disp.cols; ++x) - { - InT d = disp(y, x); - - double from[4] = { x, y, d, 1 }; - Mat_ res = Q * Mat_(4, 1, from); - res /= res(3, 0); - - out3d_t pixel_exp = *(Vec3d*)res.data; - out3d_t pixel_out = _3dImg(y, x); - - const int largeZValue = 10000; /* see documentation */ - - if (handleMissingValues && y == disp.rows/2 && x == disp.cols/2) - { - if (pixel_out[2] == largeZValue) - continue; - - ts->printf(CvTS::LOG, "Missing values are handled improperly\n"); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - else - { - double err = error(pixel_out, pixel_exp), t = thres(); - if ( err > t ) - { - ts->printf(CvTS::LOG, "case %d. too big error at (%d, %d): %g vs expected %g: res = (%g, %g, %g, w=%g) vs pixel_out = (%g, %g, %g)\n", - caseId, x, y, err, t, res(0,0), res(1,0), res(2,0), res(3,0), - (double)pixel_out[0], (double)pixel_out[1], (double)pixel_out[2]); - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - } - } - } -}; - -CV_ReprojectImageTo3DTest reprojectImageTo3D_test; diff --git a/tests/cv/src/asnakes.cpp b/tests/cv/src/asnakes.cpp deleted file mode 100644 index 1be250c..0000000 --- a/tests/cv/src/asnakes.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -/* This is regression test for Snakes functions of OpenCV. -// This test will generate fixed figure, read initial position -// of snake from file, run OpenCV function and compare result -// position of snake with position(from file) which must be resulting. -// -// Test is considered to be succesfull if resultant positions -// are identical. -*/ - -class CV_SnakeTest : public CvTest -{ -public: - CV_SnakeTest(); -protected: - void run(int); -}; - -#define SCAN 0 - -CV_SnakeTest::CV_SnakeTest(): - CvTest( "snakes", "cvSnakeImage" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_SnakeTest::run( int /*start_from*/ ) -{ - int code = CvTS::OK; - static const char* file_name[] = - { - "ring", - "square" - }; - - const int numfig_image = 1; - const int numfig_grad = 1; - - FILE* file = 0; -#ifndef _MAX_PATH -#define _MAX_PATH 1024 -#endif - char abs_file_name[_MAX_PATH]; - char rel_path[_MAX_PATH]; - - int i,j; - - /* source image */ - IplImage* iplSrc = NULL; - CvSize win; - int length; - - float alpha,beta,gamma; - CvTermCriteria criteria; - long lErrors = 0; - int progress = 0, test_case_count = numfig_image + numfig_grad; - CvPoint* Pts = 0; - CvPoint* resPts = 0; - - sprintf( rel_path, "%ssnakes/", ts->get_data_path() ); - - criteria.type = CV_TERMCRIT_ITER; - win.height = win.width = 3; - - for( i = 0; i < test_case_count; i++ ) - { - progress = update_progress( progress, i, test_case_count, 0 ); - int num_pos; - int k; - - char tmp[_MAX_PATH]; - - ts->update_context( this, i, false ); - - /* create full name of bitmap file */ - strcpy(tmp, rel_path); - strcat(tmp, file_name[i]); - strcpy( abs_file_name, tmp ); - strcat( abs_file_name, ".bmp" ); - - /* read bitmap with 8u image */ - iplSrc = cvLoadImage( abs_file_name, -1 ); - - if (!iplSrc) - { - ts->printf( CvTS::LOG, "can not load %s\n", abs_file_name ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - /* init snake reading file with snake */ - strcpy(tmp, rel_path); - strcat(tmp, file_name[i]); - strcpy( abs_file_name, tmp ); - strcat( abs_file_name, ".txt" ); - -#if !SCAN - file = fopen( abs_file_name, "r" ); -#else - file = fopen( abs_file_name, "r+" ); -#endif - - if (!file) - { - ts->printf( CvTS::LOG, "can not load %s\n", abs_file_name ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - /* read snake parameters */ - fscanf(file, "%d", &length ); - fscanf(file, "%f", &alpha ); - fscanf(file, "%f", &beta ); - fscanf(file, "%f", &gamma ); - - /* allocate memory for snakes */ - Pts = (CvPoint*)cvAlloc( length * sizeof(Pts[0]) ); - resPts = (CvPoint*)cvAlloc( length * sizeof(resPts[0]) ); - - /* get number of snake positions */ - fscanf(file, "%d", &num_pos ); - - /* get number iterations between two positions */ - fscanf(file, "%d", &criteria.max_iter ); - - /* read initial snake position */ - for ( j = 0; j < length; j++ ) - { - fscanf(file, "%d%d", &Pts[j].x, &Pts[j].y ); - } - - for ( k = 0; k < num_pos; k++ ) - { - /* Run CVL function to check it */ - if(i 0 ) - { - ts->printf( CvTS::LOG, "Total fixed %d errors", lErrors ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - -_exit_: - - if( file ) - fclose(file); - cvFree(&Pts); - cvFree(&resPts); - cvReleaseImage(&iplSrc); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_SnakeTest snake_test; - -/* End of file. */ diff --git a/tests/cv/src/astereocorrespondencegc.cpp b/tests/cv/src/astereocorrespondencegc.cpp deleted file mode 100644 index cf7325f..0000000 --- a/tests/cv/src/astereocorrespondencegc.cpp +++ /dev/null @@ -1,297 +0,0 @@ -#include "cvtest.h" - -#if 0 - -#define debug //enables showing images. -#define CONSOLEOUTPUT //enables printing rms error and percentage of bad pixels to console. - -//#define LOAD //enables skipping computing disparities and load them from images. -//#define SAVEIMAGES //enables saving computed disparity and red-marked disparity images. - -void MarkPixel(const IplImage* markedDisparity, const int h, const int w) -{ - uchar* data = (uchar*)&markedDisparity->imageData[h*markedDisparity->widthStep + w*3]; - data[0] = 0; - data[1] = 0; - data[2] = 255; -} - -int CalculateErrors(const IplImage* disparity,const IplImage* groundTruth, IplImage* markedDisparity, - double &rms_error, double &percentage_of_bad_pixels, - const int maxDisparity CV_DEFAULT(16), const int eval_ignore_border CV_DEFAULT(10)) -{ - if (disparity->width != groundTruth->width) - return CvTS::FAIL_INVALID_TEST_DATA; - if (disparity->height != groundTruth->height) - return CvTS::FAIL_INVALID_TEST_DATA; - - const double eval_bad_thresh = 1.0; - - char* DC = disparity->imageData; - char* DT = groundTruth->imageData; - - double currSum = 0; - unsigned int bad_pixels_counter=0; - - double diff=0; - - int w = disparity->width; - int h = disparity->height; - unsigned int numPixels = w*h; - - for(int i=eval_ignore_border; iwidthStep+j] - DT[i*groundTruth->widthStep+j])/(double)maxDisparity; - currSum += diff*diff; - - if ( diff > eval_bad_thresh ) - { - bad_pixels_counter++; - MarkPixel(markedDisparity, i, j); - } - } - - currSum /=(double)numPixels; - rms_error = sqrt(currSum); - - percentage_of_bad_pixels = (double)bad_pixels_counter/(double)numPixels * 100; - - return 0; -} - -class CV_StereoCorrespondenceTestGC : public CvTest -{ -public: - CV_StereoCorrespondenceTestGC(); -protected: - void run(int); -}; - - -CV_StereoCorrespondenceTestGC::CV_StereoCorrespondenceTestGC(): -CvTest( "stereo-gc", "cvFindStereoCorrespondenceGC" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -/* ///////////////////// stereo_correspondece_test ///////////////////////// */ -void CV_StereoCorrespondenceTestGC::run( int ) -{ - int code = CvTS::OK; - - const double rms_error_thresh = 1000.0; - const double percentage_of_bad_pixels_thresh = 90.0; - - double rms_error[2]; - double percentage_of_bad_pixels[2]; - - /* test parameters */ - char filepath[1000]; - char filename[1000]; - //char extension[5]; - - IplImage* left ; - IplImage* right; - IplImage* disparity_left; - IplImage* disparity_right; - IplImage* groundTruthLeft; - IplImage* groundTruthRight; - - sprintf( filepath, "%sstereocorrespondence/", ts->get_data_path() ); - sprintf( filename, "%sstereocorrespondence_list.txt", filepath ); - - FILE* f = fopen(filename,"r"); - int numImages=0; - fscanf(f,"%d\n",&numImages); - - for(int i=0; iprintf( CvTS::LOG, "Left or right image doesn't exist" ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - if ((cvGetSize(left).height != cvGetSize(right).height) - || ((cvGetSize(left).width != cvGetSize(right).width))) - { - ts->printf( CvTS::LOG, "Left and right image sizes aren't equal" ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - sprintf(filename,"%s%s_gtL.png",filepath,dataName); - groundTruthLeft = cvLoadImage(filename,0); - sprintf(filename,"%s%s_gtR.png",filepath,dataName); - groundTruthRight = cvLoadImage(filename,0); - - if (!groundTruthLeft && !groundTruthRight) - { - ts->printf( CvTS::LOG, "Left and right ground truth images don't exist" ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - for(int i=0; i<2; i++) - { - IplImage*& groundTruth = (i == 0) ? groundTruthLeft : groundTruthRight; - if (groundTruth) - if (groundTruth->nChannels != 1) - { - IplImage* tmp = groundTruth; - groundTruth = cvCreateImage(cvGetSize(left),IPL_DEPTH_8U,1); - cvCvtColor(tmp, groundTruth,CV_BGR2GRAY); - } - } - - /*Find disparity map for current image pair*/ -#ifndef LOAD - disparity_left = cvCreateImage( cvGetSize(left), IPL_DEPTH_32S, 1 ); - disparity_right = cvCreateImage( cvGetSize(left), IPL_DEPTH_32S, 1 ); - - CvStereoGCState* state = cvCreateStereoGCState(maxDisparity, 2); - cvFindStereoCorrespondenceGC( left, right, - disparity_left, disparity_right, state); - - double scale = 256/maxDisparity ; - if (!strcmp(dataName,"sawtooth") || !strcmp(dataName,"map") || !strcmp(dataName,"poster") - || !strcmp(dataName,"bull") || !strcmp(dataName,"barn1") || !strcmp(dataName,"barn2")) - scale = 8.0; - - IplImage* temp; - temp = disparity_left; - disparity_left = cvCreateImage(cvGetSize(temp), IPL_DEPTH_8U,1); - cvConvertScale(temp, disparity_left, -scale); - temp = disparity_right; - disparity_right = cvCreateImage(cvGetSize(temp), IPL_DEPTH_8U,1); - cvConvertScale(temp, disparity_right, scale ); -#endif -#ifdef LOAD - disparity_left; - disparity_right; - sprintf(filename,"%s%s_dLgc.png",filepath,dataName); - disparity_left = cvLoadImage(filename,0); - sprintf(filename,"%s%s_dRgc.png",filepath,dataName); - disparity_right = cvLoadImage(filename,0); -#endif -#ifdef debug - cvNamedWindow("disparity_left"); - cvNamedWindow("disparity_right"); - cvNamedWindow("ground_truth_left"); - cvNamedWindow("ground_truth_right"); - - cvShowImage("disparity_left",disparity_left); - cvShowImage("disparity_right",disparity_right); - cvShowImage("ground_truth_left", groundTruthLeft); - cvShowImage("ground_truth_right", groundTruthRight); -#endif - - /*Calculate RMS error and percentage of bad pixels*/ - IplImage* markedDisparity_left = cvCreateImage(cvGetSize(left), IPL_DEPTH_8U, 3); - IplImage* markedDisparity_right = cvCreateImage(cvGetSize(left), IPL_DEPTH_8U, 3); - cvCvtColor(disparity_left,markedDisparity_left,CV_GRAY2RGB); - cvCvtColor(disparity_right,markedDisparity_right,CV_GRAY2RGB); - - int eval_ignore_border = 10; - if (strcmp(dataName,"tsukuba") == 0) - eval_ignore_border = 18; - - /*Left*/ - int retcode[2] = {0,0}; - if (groundTruthLeft) - retcode[0] = CalculateErrors(disparity_left,groundTruthLeft, markedDisparity_left, - rms_error[0], percentage_of_bad_pixels[0], maxDisparity, eval_ignore_border); - /*Right*/ - if (groundTruthRight) - retcode[1] = CalculateErrors(disparity_right,groundTruthRight, markedDisparity_right, - rms_error[1], percentage_of_bad_pixels[1], maxDisparity, eval_ignore_border); - -#ifdef SAVEIMAGES -#ifndef LOAD - sprintf(filename,"%s%s_dLgc.png",filepath,dataName); - cvSaveImage(filename,disparity_left); - sprintf(filename,"%s%s_dRgc.png",filepath,dataName); - cvSaveImage(filename,disparity_right); - - sprintf(filename,"%s%s_mdLgc.png",filepath,dataName); - cvSaveImage(filename,markedDisparity_left); - sprintf(filename,"%s%s_mdRgc.png",filepath,dataName); - cvSaveImage(filename,markedDisparity_right); -#endif -#endif -#ifdef debug - cvNamedWindow("markedDisparity_left"); - cvNamedWindow("markedDisparity_right"); - cvShowImage("markedDisparity_left",markedDisparity_left); - cvShowImage("markedDisparity_right",markedDisparity_right); - cvWaitKey(1000); -#endif - if (retcode[0]) - { - ts->printf(CvTS::LOG,"Calculation error"); - code = retcode[0]; - //goto _exit_; - } - if (retcode[1]) - { - ts->printf(CvTS::LOG,"Calculation error"); - code = retcode[1]; - //goto _exit_; - } -#ifdef CONSOLEOUTPUT - printf("\n%s\n",dataName); - if (groundTruthLeft) - printf("L rms error = %f\npercentage of bad pixels = %f\n", - rms_error[0], percentage_of_bad_pixels[0]); - if(groundTruthRight) - printf("R rms error = %f\npercentage of bad pixels = %f\n", - rms_error[1], percentage_of_bad_pixels[1]); -#endif - for(int i=0; i<2; i++) - { - IplImage* groundTruth = (i == 0) ? groundTruthLeft : groundTruthRight; - if (groundTruth) - { - if (rms_error[i] > rms_error_thresh) - { - ts->printf( CvTS::LOG, "Big RMS error" ); - code = CvTS::FAIL_BAD_ACCURACY; - //goto _exit_; - } - if (percentage_of_bad_pixels[i] > percentage_of_bad_pixels_thresh) - { - ts->printf( CvTS::LOG, "Big percentage of bad pixels" ); - code = CvTS::FAIL_BAD_ACCURACY; - //goto _exit_; - } - } - } - } -_exit_: - cvReleaseImage(&left); - cvReleaseImage(&right); - cvReleaseImage(&disparity_left); - cvReleaseImage(&disparity_right); - cvReleaseImage(&groundTruthLeft); - cvReleaseImage(&groundTruthRight); -#ifndef LOAD - //cvReleaseStereoCorrespondenceGCState(&stereoMatcher); -#endif - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_StereoCorrespondenceTestGC stereo_correspondece_test_gc; - -#endif diff --git a/tests/cv/src/astereomatching.cpp b/tests/cv/src/astereomatching.cpp deleted file mode 100755 index c6c9720..0000000 --- a/tests/cv/src/astereomatching.cpp +++ /dev/null @@ -1,823 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* - This is a regression test for stereo matching algorithms. This test gets some quality metrics - discribed in "A Taxonomy and Evaluation of Dense Two-Frame Stereo Correspondence Algorithms". - Daniel Scharstein, Richard Szeliski -*/ - -#include "cvtest.h" -#include -#include - -using namespace std; -using namespace cv; - -const float EVAL_BAD_THRESH = 1.f; -const int EVAL_TEXTURELESS_WIDTH = 3; -const float EVAL_TEXTURELESS_THRESH = 4.f; -const float EVAL_DISP_THRESH = 1.f; -const float EVAL_DISP_GAP = 2.f; -const int EVAL_DISCONT_WIDTH = 9; -const int EVAL_IGNORE_BORDER = 10; - -const int ERROR_KINDS_COUNT = 6; - -//============================== quality measuring functions ================================================= - -/* - Calculate textureless regions of image (regions where the squared horizontal intensity gradient averaged over - a square window of size=evalTexturelessWidth is below a threshold=evalTexturelessThresh) and textured regions. -*/ -void computeTextureBasedMasks( const Mat& _img, Mat* texturelessMask, Mat* texturedMask, - int texturelessWidth = EVAL_TEXTURELESS_WIDTH, float texturelessThresh = EVAL_TEXTURELESS_THRESH ) -{ - if( !texturelessMask && !texturedMask ) - return; - if( _img.empty() ) - CV_Error( CV_StsBadArg, "img is empty" ); - - Mat img = _img; - if( _img.channels() > 1) - { - Mat tmp; cvtColor( _img, tmp, CV_BGR2GRAY ); img = tmp; - } - Mat dxI; Sobel( img, dxI, CV_32FC1, 1, 0, 3 ); - Mat dxI2; pow( dxI / 8.f/*normalize*/, 2, dxI2 ); - Mat avgDxI2; boxFilter( dxI2, avgDxI2, CV_32FC1, Size(texturelessWidth,texturelessWidth) ); - - if( texturelessMask ) - *texturelessMask = avgDxI2 < texturelessThresh; - if( texturedMask ) - *texturedMask = avgDxI2 >= texturelessThresh; -} - -void checkTypeAndSizeOfDisp( const Mat& dispMap, const Size* sz ) -{ - if( dispMap.empty() ) - CV_Error( CV_StsBadArg, "dispMap is empty" ); - if( dispMap.type() != CV_32FC1 ) - CV_Error( CV_StsBadArg, "dispMap must have CV_32FC1 type" ); - if( sz && (dispMap.rows != sz->height || dispMap.cols != sz->width) ) - CV_Error( CV_StsBadArg, "dispMap has incorrect size" ); -} - -void checkTypeAndSizeOfMask( const Mat& mask, Size sz ) -{ - if( mask.empty() ) - CV_Error( CV_StsBadArg, "mask is empty" ); - if( mask.type() != CV_8UC1 ) - CV_Error( CV_StsBadArg, "mask must have CV_8UC1 type" ); - if( mask.rows != sz.height || mask.cols != sz.width ) - CV_Error( CV_StsBadArg, "mask has incorrect size" ); -} - -void checkDispMapsAndUnknDispMasks( const Mat& leftDispMap, const Mat& rightDispMap, - const Mat& leftUnknDispMask, const Mat& rightUnknDispMask ) -{ - // check type and size of disparity maps - checkTypeAndSizeOfDisp( leftDispMap, 0 ); - if( !rightDispMap.empty() ) - { - Size sz = leftDispMap.size(); - checkTypeAndSizeOfDisp( rightDispMap, &sz ); - } - - // check size and type of unknown disparity maps - if( !leftUnknDispMask.empty() ) - checkTypeAndSizeOfMask( leftUnknDispMask, leftDispMap.size() ); - if( !rightUnknDispMask.empty() ) - checkTypeAndSizeOfMask( rightUnknDispMask, rightDispMap.size() ); - - // check values of disparity maps (known disparity values musy be positive) - double leftMinVal = 0, rightMinVal = 0; - if( leftUnknDispMask.empty() ) - minMaxLoc( leftDispMap, &leftMinVal ); - else - minMaxLoc( leftDispMap, &leftMinVal, 0, 0, 0, ~leftUnknDispMask ); - if( !rightDispMap.empty() ) - { - if( rightUnknDispMask.empty() ) - minMaxLoc( rightDispMap, &rightMinVal ); - else - minMaxLoc( rightDispMap, &rightMinVal, 0, 0, 0, ~rightUnknDispMask ); - } - if( leftMinVal < 0 || rightMinVal < 0) - CV_Error( CV_StsBadArg, "known disparity values must be positive" ); -} - -/* - Calculate occluded regions of reference image (left image) (regions that are occluded in the matching image (right image), - i.e., where the forward-mapped disparity lands at a location with a larger (nearer) disparity) and non occluded regions. -*/ -void computeOcclusionBasedMasks( const Mat& leftDisp, const Mat& _rightDisp, - Mat* occludedMask, Mat* nonOccludedMask, - const Mat& leftUnknDispMask = Mat(), const Mat& rightUnknDispMask = Mat(), - float dispThresh = EVAL_DISP_THRESH ) -{ - if( !occludedMask && !nonOccludedMask ) - return; - checkDispMapsAndUnknDispMasks( leftDisp, _rightDisp, leftUnknDispMask, rightUnknDispMask ); - - Mat rightDisp; - if( _rightDisp.empty() ) - { - if( !rightUnknDispMask.empty() ) - CV_Error( CV_StsBadArg, "rightUnknDispMask must be empty if _rightDisp is empty" ); - rightDisp.create(leftDisp.size(), CV_32FC1); - rightDisp.setTo(Scalar::all(0) ); - for( int leftY = 0; leftY < leftDisp.rows; leftY++ ) - { - for( int leftX = 0; leftX < leftDisp.cols; leftX++ ) - { - if( !leftUnknDispMask.empty() && leftUnknDispMask.at(leftY,leftX) ) - continue; - float leftDispVal = leftDisp.at(leftY, leftX); - int rightX = leftX - cvRound(leftDispVal), rightY = leftY; - if( rightX >= 0) - rightDisp.at(rightY,rightX) = max(rightDisp.at(rightY,rightX), leftDispVal); - } - } - } - else - _rightDisp.copyTo(rightDisp); - - if( occludedMask ) - { - occludedMask->create(leftDisp.size(), CV_8UC1); - occludedMask->setTo(Scalar::all(0) ); - } - if( nonOccludedMask ) - { - nonOccludedMask->create(leftDisp.size(), CV_8UC1); - nonOccludedMask->setTo(Scalar::all(0) ); - } - for( int leftY = 0; leftY < leftDisp.rows; leftY++ ) - { - for( int leftX = 0; leftX < leftDisp.cols; leftX++ ) - { - if( !leftUnknDispMask.empty() && leftUnknDispMask.at(leftY,leftX) ) - continue; - float leftDispVal = leftDisp.at(leftY, leftX); - int rightX = leftX - cvRound(leftDispVal), rightY = leftY; - if( rightX < 0 && occludedMask ) - occludedMask->at(leftY, leftX) = 255; - else - { - if( !rightUnknDispMask.empty() && rightUnknDispMask.at(rightY,rightX) ) - continue; - float rightDispVal = rightDisp.at(rightY, rightX); - if( rightDispVal > leftDispVal + dispThresh ) - { - if( occludedMask ) - occludedMask->at(leftY, leftX) = 255; - } - else - { - if( nonOccludedMask ) - nonOccludedMask->at(leftY, leftX) = 255; - } - } - } - } -} - -/* - Calculate depth discontinuty regions: pixels whose neiboring disparities differ by more than - dispGap, dilated by window of width discontWidth. -*/ -void computeDepthDiscontMask( const Mat& disp, Mat& depthDiscontMask, const Mat& unknDispMask = Mat(), - float dispGap = EVAL_DISP_GAP, int discontWidth = EVAL_DISCONT_WIDTH ) -{ - if( disp.empty() ) - CV_Error( CV_StsBadArg, "disp is empty" ); - if( disp.type() != CV_32FC1 ) - CV_Error( CV_StsBadArg, "disp must have CV_32FC1 type" ); - if( !unknDispMask.empty() ) - checkTypeAndSizeOfMask( unknDispMask, disp.size() ); - - Mat curDisp; disp.copyTo( curDisp ); - if( !unknDispMask.empty() ) - curDisp.setTo( Scalar(-numeric_limits::max()), unknDispMask ); - Mat maxNeighbDisp; dilate( curDisp, maxNeighbDisp, Mat(3, 3, CV_8UC1, Scalar(1)) ); - if( !unknDispMask.empty() ) - curDisp.setTo( Scalar(numeric_limits::max()), unknDispMask ); - Mat minNeighbDisp; erode( curDisp, minNeighbDisp, Mat(3, 3, CV_8UC1, Scalar(1)) ); - depthDiscontMask = max( (Mat)(maxNeighbDisp-disp), (Mat)(disp-minNeighbDisp) ) > dispGap; - if( !unknDispMask.empty() ) - depthDiscontMask &= ~unknDispMask; - dilate( depthDiscontMask, depthDiscontMask, Mat(discontWidth, discontWidth, CV_8UC1, Scalar(1)) ); -} - -/* - Get evaluation masks excluding a border. -*/ -Mat getBorderedMask( Size maskSize, int border = EVAL_IGNORE_BORDER ) -{ - CV_Assert( border >= 0 ); - Mat mask(maskSize, CV_8UC1, Scalar(0)); - int w = maskSize.width - 2*border, h = maskSize.height - 2*border; - if( w < 0 || h < 0 ) - mask.setTo(Scalar(0)); - else - mask( Rect(Point(border,border),Size(w,h)) ).setTo(Scalar(255)); - return mask; -} - -/* - Calculate root-mean-squared error between the computed disparity map (computedDisp) and ground truth map (groundTruthDisp). -*/ -float dispRMS( const Mat& computedDisp, const Mat& groundTruthDisp, const Mat& mask ) -{ - checkTypeAndSizeOfDisp( groundTruthDisp, 0 ); - Size sz = groundTruthDisp.size(); - checkTypeAndSizeOfDisp( computedDisp, &sz ); - - int pointsCount = sz.height*sz.width; - if( !mask.empty() ) - { - checkTypeAndSizeOfMask( mask, sz ); - pointsCount = countNonZero(mask); - } - return 1.f/sqrt((float)pointsCount) * (float)norm(computedDisp, groundTruthDisp, NORM_L2, mask); -} - -/* - Calculate fraction of bad matching pixels. -*/ -float badMatchPxlsFraction( const Mat& computedDisp, const Mat& groundTruthDisp, const Mat& mask, - float _badThresh = EVAL_BAD_THRESH ) -{ - int badThresh = cvRound(_badThresh); - checkTypeAndSizeOfDisp( groundTruthDisp, 0 ); - Size sz = groundTruthDisp.size(); - checkTypeAndSizeOfDisp( computedDisp, &sz ); - - Mat badPxlsMap; - absdiff( computedDisp, groundTruthDisp, badPxlsMap ); - badPxlsMap = badPxlsMap > badThresh; - int pointsCount = sz.height*sz.width; - if( !mask.empty() ) - { - checkTypeAndSizeOfMask( mask, sz ); - badPxlsMap = badPxlsMap & mask; - pointsCount = countNonZero(mask); - } - return 1.f/pointsCount * countNonZero(badPxlsMap); -} - -//===================== regression test for stereo matching algorithms ============================== - -const string ALGORITHMS_DIR = "stereomatching/algorithms/"; -const string DATASETS_DIR = "stereomatching/datasets/"; -const string DATASETS_FILE = "datasets.xml"; - -const string RUN_PARAMS_FILE = "_params.xml"; -const string RESULT_FILE = "_res.xml"; - -const string LEFT_IMG_NAME = "im2.png"; -const string RIGHT_IMG_NAME = "im6.png"; -const string TRUE_LEFT_DISP_NAME = "disp2.png"; -const string TRUE_RIGHT_DISP_NAME = "disp6.png"; - -string ERROR_PREFIXES[] = { "borderedAll", - "borderedNoOccl", - "borderedOccl", - "borderedTextured", - "borderedTextureless", - "borderedDepthDiscont" }; // size of ERROR_KINDS_COUNT - - -const string RMS_STR = "RMS"; -const string BAD_PXLS_FRACTION_STR = "BadPxlsFraction"; - -class QualityEvalParams -{ -public: - QualityEvalParams() { setDefaults(); } - QualityEvalParams( int _ignoreBorder ) - { - setDefaults(); - ignoreBorder = _ignoreBorder; - } - void setDefaults() - { - badThresh = EVAL_BAD_THRESH; - texturelessWidth = EVAL_TEXTURELESS_WIDTH; - texturelessThresh = EVAL_TEXTURELESS_THRESH; - dispThresh = EVAL_DISP_THRESH; - dispGap = EVAL_DISP_GAP; - discontWidth = EVAL_DISCONT_WIDTH; - ignoreBorder = EVAL_IGNORE_BORDER; - } - float badThresh; - int texturelessWidth; - float texturelessThresh; - float dispThresh; - float dispGap; - int discontWidth; - int ignoreBorder; -}; - -class CV_StereoMatchingTest : public CvTest -{ -public: - CV_StereoMatchingTest( const char* testName ) : CvTest( testName, "stereo-matching" ) - { rmsEps.resize( ERROR_KINDS_COUNT, 0.01f ); fracEps.resize( ERROR_KINDS_COUNT, 1.e-6f ); } -protected: - // assumed that left image is a reference image - virtual int runStereoMatchingAlgorithm( const Mat& leftImg, const Mat& rightImg, - Mat& leftDisp, Mat& rightDisp, int caseIdx ) = 0; // return ignored border width - - int readDatasetsParams( FileStorage& fs ); - virtual int readRunParams( FileStorage& fs ); - void writeErrors( const string& errName, const vector& errors, FileStorage* fs = 0 ); - void readErrors( FileNode& fn, const string& errName, vector& errors ); - int compareErrors( const vector& calcErrors, const vector& validErrors, - const vector& eps, const string& errName ); - int processStereoMatchingResults( FileStorage& fs, int caseIdx, bool isWrite, - const Mat& leftImg, const Mat& rightImg, - const Mat& trueLeftDisp, const Mat& trueRightDisp, - const Mat& leftDisp, const Mat& rightDisp, - const QualityEvalParams& qualityEvalParams ); - void run( int ); - - vector rmsEps; - vector fracEps; - - struct DatasetParams - { - int dispScaleFactor; - int dispUnknVal; - }; - map datasetsParams; - - vector caseNames; - vector caseDatasets; -}; - -void CV_StereoMatchingTest::run(int) -{ - string dataPath = ts->get_data_path(); - string algorithmName = name; - assert( !algorithmName.empty() ); - if( dataPath.empty() ) - { - ts->printf( CvTS::LOG, "dataPath is empty" ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ARG_CHECK ); - return; - } - - FileStorage datasetsFS( dataPath + DATASETS_DIR + DATASETS_FILE, FileStorage::READ ); - int code = readDatasetsParams( datasetsFS ); - if( code != CvTS::OK ) - { - ts->set_failed_test_info( code ); - return; - } - FileStorage runParamsFS( dataPath + ALGORITHMS_DIR + algorithmName + RUN_PARAMS_FILE, FileStorage::READ ); - code = readRunParams( runParamsFS ); - if( code != CvTS::OK ) - { - ts->set_failed_test_info( code ); - return; - } - - string fullResultFilename = dataPath + ALGORITHMS_DIR + algorithmName + RESULT_FILE; - FileStorage resFS( fullResultFilename, FileStorage::READ ); - bool isWrite = true; // write or compare results - if( resFS.isOpened() ) - isWrite = false; - else - { - resFS.open( fullResultFilename, FileStorage::WRITE ); - if( !resFS.isOpened() ) - { - ts->printf( CvTS::LOG, "file %s can not be read or written\n", fullResultFilename.c_str() ); - ts->set_failed_test_info( CvTS::FAIL_BAD_ARG_CHECK ); - return; - } - resFS << "stereo_matching" << "{"; - } - - int progress = 0, caseCount = (int)caseNames.size(); - for( int ci = 0; ci < caseCount; ci++) - { - progress = update_progress( progress, ci, caseCount, 0 ); - - string datasetName = caseDatasets[ci]; - string datasetFullDirName = dataPath + DATASETS_DIR + datasetName + "/"; - Mat leftImg = imread(datasetFullDirName + LEFT_IMG_NAME); - Mat rightImg = imread(datasetFullDirName + RIGHT_IMG_NAME); - Mat trueLeftDisp = imread(datasetFullDirName + TRUE_LEFT_DISP_NAME, 0); - Mat trueRightDisp = imread(datasetFullDirName + TRUE_RIGHT_DISP_NAME, 0); - - if( leftImg.empty() || rightImg.empty() || trueLeftDisp.empty() ) - { - ts->printf( CvTS::LOG, "images or left ground-truth disparities of dataset %s can not be read", datasetName.c_str() ); - code = CvTS::FAIL_INVALID_TEST_DATA; - continue; - } - int dispScaleFactor = datasetsParams[datasetName].dispScaleFactor; - Mat tmp; trueLeftDisp.convertTo( tmp, CV_32FC1, 1.f/dispScaleFactor ); trueLeftDisp = tmp; tmp.release(); - if( !trueRightDisp.empty() ) - trueRightDisp.convertTo( tmp, CV_32FC1, 1.f/dispScaleFactor ); trueRightDisp = tmp; tmp.release(); - - Mat leftDisp, rightDisp; - int ignBorder = max(runStereoMatchingAlgorithm(leftImg, rightImg, leftDisp, rightDisp, ci), EVAL_IGNORE_BORDER); - leftDisp.convertTo( tmp, CV_32FC1 ); leftDisp = tmp; tmp.release(); - rightDisp.convertTo( tmp, CV_32FC1 ); rightDisp = tmp; tmp.release(); - - int tempCode = processStereoMatchingResults( resFS, ci, isWrite, - leftImg, rightImg, trueLeftDisp, trueRightDisp, leftDisp, rightDisp, QualityEvalParams(ignBorder)); - code = tempCode==CvTS::OK ? code : tempCode; - } - - if( isWrite ) - resFS << "}"; // "stereo_matching" - - ts->set_failed_test_info( code ); -} - -void calcErrors( const Mat& leftImg, const Mat& /*rightImg*/, - const Mat& trueLeftDisp, const Mat& trueRightDisp, - const Mat& trueLeftUnknDispMask, const Mat& trueRightUnknDispMask, - const Mat& calcLeftDisp, const Mat& /*calcRightDisp*/, - vector& rms, vector& badPxlsFractions, - const QualityEvalParams& qualityEvalParams ) -{ - Mat texturelessMask, texturedMask; - computeTextureBasedMasks( leftImg, &texturelessMask, &texturedMask, - qualityEvalParams.texturelessWidth, qualityEvalParams.texturelessThresh ); - Mat occludedMask, nonOccludedMask; - computeOcclusionBasedMasks( trueLeftDisp, trueRightDisp, &occludedMask, &nonOccludedMask, - trueLeftUnknDispMask, trueRightUnknDispMask, qualityEvalParams.dispThresh); - Mat depthDiscontMask; - computeDepthDiscontMask( trueLeftDisp, depthDiscontMask, trueLeftUnknDispMask, - qualityEvalParams.dispGap, qualityEvalParams.discontWidth); - - Mat borderedKnownMask = getBorderedMask( leftImg.size(), qualityEvalParams.ignoreBorder ) & ~trueLeftUnknDispMask; - - nonOccludedMask &= borderedKnownMask; - occludedMask &= borderedKnownMask; - texturedMask &= nonOccludedMask; // & borderedKnownMask - texturelessMask &= nonOccludedMask; // & borderedKnownMask - depthDiscontMask &= nonOccludedMask; // & borderedKnownMask - - rms.resize(ERROR_KINDS_COUNT); - rms[0] = dispRMS( calcLeftDisp, trueLeftDisp, borderedKnownMask ); - rms[1] = dispRMS( calcLeftDisp, trueLeftDisp, nonOccludedMask ); - rms[2] = dispRMS( calcLeftDisp, trueLeftDisp, occludedMask ); - rms[3] = dispRMS( calcLeftDisp, trueLeftDisp, texturedMask ); - rms[4] = dispRMS( calcLeftDisp, trueLeftDisp, texturelessMask ); - rms[5] = dispRMS( calcLeftDisp, trueLeftDisp, depthDiscontMask ); - - badPxlsFractions.resize(ERROR_KINDS_COUNT); - badPxlsFractions[0] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, borderedKnownMask, qualityEvalParams.badThresh ); - badPxlsFractions[1] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, nonOccludedMask, qualityEvalParams.badThresh ); - badPxlsFractions[2] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, occludedMask, qualityEvalParams.badThresh ); - badPxlsFractions[3] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, texturedMask, qualityEvalParams.badThresh ); - badPxlsFractions[4] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, texturelessMask, qualityEvalParams.badThresh ); - badPxlsFractions[5] = badMatchPxlsFraction( calcLeftDisp, trueLeftDisp, depthDiscontMask, qualityEvalParams.badThresh ); -} - -int CV_StereoMatchingTest::processStereoMatchingResults( FileStorage& fs, int caseIdx, bool isWrite, - const Mat& leftImg, const Mat& rightImg, - const Mat& trueLeftDisp, const Mat& trueRightDisp, - const Mat& leftDisp, const Mat& rightDisp, - const QualityEvalParams& qualityEvalParams ) -{ - // rightDisp is not used in current test virsion - int code = CvTS::OK; - assert( fs.isOpened() ); - assert( trueLeftDisp.type() == CV_32FC1 && trueRightDisp.type() == CV_32FC1 ); - assert( leftDisp.type() == CV_32FC1 && rightDisp.type() == CV_32FC1 ); - - // get masks for unknown ground truth disparity values - Mat leftUnknMask, rightUnknMask; - DatasetParams params = datasetsParams[caseDatasets[caseIdx]]; - absdiff( trueLeftDisp, Scalar(params.dispUnknVal), leftUnknMask ); - leftUnknMask = leftUnknMask < numeric_limits::epsilon(); - assert(leftUnknMask.type() == CV_8UC1); - if( !trueRightDisp.empty() ) - { - absdiff( trueRightDisp, Scalar(params.dispUnknVal), rightUnknMask ); - rightUnknMask = rightUnknMask < numeric_limits::epsilon(); - assert(leftUnknMask.type() == CV_8UC1); - } - - // calculate errors - vector rmss, badPxlsFractions; - calcErrors( leftImg, rightImg, trueLeftDisp, trueRightDisp, leftUnknMask, rightUnknMask, - leftDisp, rightDisp, rmss, badPxlsFractions, qualityEvalParams ); - - if( isWrite ) - { - fs << caseNames[caseIdx] << "{"; - cvWriteComment( fs.fs, RMS_STR.c_str(), 0 ); - writeErrors( RMS_STR, rmss, &fs ); - cvWriteComment( fs.fs, BAD_PXLS_FRACTION_STR.c_str(), 0 ); - writeErrors( BAD_PXLS_FRACTION_STR, badPxlsFractions, &fs ); - fs << "}"; // datasetName - } - else // compare - { - ts->printf( CvTS::LOG, "\nquality of case named %s\n", caseNames[caseIdx].c_str() ); - ts->printf( CvTS::LOG, "%s\n", RMS_STR.c_str() ); - writeErrors( RMS_STR, rmss ); - ts->printf( CvTS::LOG, "%s\n", BAD_PXLS_FRACTION_STR.c_str() ); - writeErrors( BAD_PXLS_FRACTION_STR, badPxlsFractions ); - - FileNode fn = fs.getFirstTopLevelNode()[caseNames[caseIdx]]; - vector validRmss, validBadPxlsFractions; - - readErrors( fn, RMS_STR, validRmss ); - readErrors( fn, BAD_PXLS_FRACTION_STR, validBadPxlsFractions ); - int tempCode = compareErrors( rmss, validRmss, rmsEps, RMS_STR ); - code = tempCode==CvTS::OK ? code : tempCode; - tempCode = compareErrors( badPxlsFractions, validBadPxlsFractions, fracEps, BAD_PXLS_FRACTION_STR ); - code = tempCode==CvTS::OK ? code : tempCode; - } - return code; -} - -int CV_StereoMatchingTest::readDatasetsParams( FileStorage& fs ) -{ - if( !fs.isOpened() ) - { - ts->printf( CvTS::LOG, "datasetsParams can not be read " ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - datasetsParams.clear(); - FileNode fn = fs.getFirstTopLevelNode(); - assert(fn.isSeq()); - for( int i = 0; i < (int)fn.size(); i+=3 ) - { - string name = fn[i]; - DatasetParams params; - string sf = fn[i+1]; params.dispScaleFactor = atoi(sf.c_str()); - string uv = fn[i+2]; params.dispUnknVal = atoi(uv.c_str()); - datasetsParams[name] = params; - } - return CvTS::OK; -} - -int CV_StereoMatchingTest::readRunParams( FileStorage& fs ) -{ - if( !fs.isOpened() ) - { - ts->printf( CvTS::LOG, "runParams can not be read " ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - caseNames.clear();; - caseDatasets.clear(); - return CvTS::OK; -} - -void CV_StereoMatchingTest::writeErrors( const string& errName, const vector& errors, FileStorage* fs ) -{ - assert( (int)errors.size() == ERROR_KINDS_COUNT ); - vector::const_iterator it = errors.begin(); - if( fs ) - for( int i = 0; i < ERROR_KINDS_COUNT; i++, ++it ) - *fs << ERROR_PREFIXES[i] + errName << *it; - else - for( int i = 0; i < ERROR_KINDS_COUNT; i++, ++it ) - ts->printf( CvTS::LOG, "%s = %f\n", string(ERROR_PREFIXES[i]+errName).c_str(), *it ); -} - -void CV_StereoMatchingTest::readErrors( FileNode& fn, const string& errName, vector& errors ) -{ - errors.resize( ERROR_KINDS_COUNT ); - vector::iterator it = errors.begin(); - for( int i = 0; i < ERROR_KINDS_COUNT; i++, ++it ) - fn[ERROR_PREFIXES[i]+errName] >> *it; -} - -int CV_StereoMatchingTest::compareErrors( const vector& calcErrors, const vector& validErrors, - const vector& eps, const string& errName ) -{ - assert( (int)calcErrors.size() == ERROR_KINDS_COUNT ); - assert( (int)validErrors.size() == ERROR_KINDS_COUNT ); - assert( (int)eps.size() == ERROR_KINDS_COUNT ); - vector::const_iterator calcIt = calcErrors.begin(), - validIt = validErrors.begin(), - epsIt = eps.begin(); - bool ok = true; - for( int i = 0; i < ERROR_KINDS_COUNT; i++, ++calcIt, ++validIt, ++epsIt ) - if( *calcIt - *validIt > *epsIt ) - { - ts->printf( CvTS::LOG, "bad accuracy of %s (valid=%f; calc=%f)\n", string(ERROR_PREFIXES[i]+errName).c_str(), *validIt, *calcIt ); - ok = false; - } - return ok ? CvTS::OK : CvTS::FAIL_BAD_ACCURACY; -} - -//----------------------------------- StereoBM test ----------------------------------------------------- - -class CV_StereoBMTest : public CV_StereoMatchingTest -{ -public: - CV_StereoBMTest() : CV_StereoMatchingTest( "stereobm" ) - { fill(rmsEps.begin(), rmsEps.end(), 0.4f); fill(fracEps.begin(), fracEps.end(), 0.022f); } - -protected: - struct RunParams - { - int ndisp; - int winSize; - }; - vector caseRunParams; - - virtual int readRunParams( FileStorage& fs ) - { - int code = CV_StereoMatchingTest::readRunParams( fs ); - FileNode fn = fs.getFirstTopLevelNode(); - assert(fn.isSeq()); - for( int i = 0; i < (int)fn.size(); i+=4 ) - { - string caseName = fn[i], datasetName = fn[i+1]; - RunParams params; - string ndisp = fn[i+2]; params.ndisp = atoi(ndisp.c_str()); - string winSize = fn[i+3]; params.winSize = atoi(winSize.c_str()); - caseNames.push_back( caseName ); - caseDatasets.push_back( datasetName ); - caseRunParams.push_back( params ); - } - return code; - } - - virtual int runStereoMatchingAlgorithm( const Mat& _leftImg, const Mat& _rightImg, - Mat& leftDisp, Mat& /*rightDisp*/, int caseIdx ) - { - RunParams params = caseRunParams[caseIdx]; - assert( params.ndisp%16 == 0 ); - assert( _leftImg.type() == CV_8UC3 && _rightImg.type() == CV_8UC3 ); - Mat leftImg; cvtColor( _leftImg, leftImg, CV_BGR2GRAY ); - Mat rightImg; cvtColor( _rightImg, rightImg, CV_BGR2GRAY ); - - StereoBM bm( StereoBM::BASIC_PRESET, params.ndisp, params.winSize ); - bm( leftImg, rightImg, leftDisp, CV_32F ); - return params.winSize/2; - } -}; - -CV_StereoBMTest stereoBM; - -//----------------------------------- StereoGC test ----------------------------------------------------- - -class CV_StereoGCTest : public CV_StereoMatchingTest -{ -public: - CV_StereoGCTest() : CV_StereoMatchingTest( "stereogc" ) - { - fill(rmsEps.begin(), rmsEps.end(), 3.f); - fracEps[0] = 0.05f; // all - fracEps[1] = 0.05f; // noOccl - fracEps[2] = 0.25f; // occl - fracEps[3] = 0.05f; // textured - fracEps[4] = 0.10f; // textureless - fracEps[5] = 0.10f; // borderedDepthDiscont - } -protected: - struct RunParams - { - int ndisp; - int iterCount; - }; - vector caseRunParams; - - virtual int readRunParams( FileStorage& fs ) - { - int code = CV_StereoMatchingTest::readRunParams(fs); - FileNode fn = fs.getFirstTopLevelNode(); - assert(fn.isSeq()); - for( int i = 0; i < (int)fn.size(); i+=4 ) - { - string caseName = fn[i], datasetName = fn[i+1]; - RunParams params; - string ndisp = fn[i+2]; params.ndisp = atoi(ndisp.c_str()); - string iterCount = fn[i+3]; params.iterCount = atoi(iterCount.c_str()); - caseNames.push_back( caseName ); - caseDatasets.push_back( datasetName ); - caseRunParams.push_back( params ); - } - return code; - } - - virtual int runStereoMatchingAlgorithm( const Mat& _leftImg, const Mat& _rightImg, - Mat& leftDisp, Mat& rightDisp, int caseIdx ) - { - RunParams params = caseRunParams[caseIdx]; - assert( _leftImg.type() == CV_8UC3 && _rightImg.type() == CV_8UC3 ); - Mat leftImg, rightImg, tmp; - cvtColor( _leftImg, leftImg, CV_BGR2GRAY ); - cvtColor( _rightImg, rightImg, CV_BGR2GRAY ); - - leftDisp.create( leftImg.size(), CV_16SC1 ); - rightDisp.create( rightImg.size(), CV_16SC1 ); - - CvMat _limg = leftImg, _rimg = rightImg, _ldisp = leftDisp, _rdisp = rightDisp; - CvStereoGCState *state = cvCreateStereoGCState( params.ndisp, params.iterCount ); - cvFindStereoCorrespondenceGC( &_limg, &_rimg, &_ldisp, &_rdisp, state ); - cvReleaseStereoGCState( &state ); - - leftDisp = - leftDisp; - return 0; - } - -}; - -CV_StereoGCTest stereoGC; - -//----------------------------------- StereoSGBM test ----------------------------------------------------- - -class CV_StereoSGBMTest : public CV_StereoMatchingTest -{ -public: - CV_StereoSGBMTest() : CV_StereoMatchingTest( "stereosgbm" ) - { fill(rmsEps.begin(), rmsEps.end(), 0.25f); fill(fracEps.begin(), fracEps.end(), 0.01f); } - -protected: - struct RunParams - { - int ndisp; - int winSize; - bool fullDP; - }; - vector caseRunParams; - - virtual int readRunParams( FileStorage& fs ) - { - int code = CV_StereoMatchingTest::readRunParams(fs); - FileNode fn = fs.getFirstTopLevelNode(); - assert(fn.isSeq()); - for( int i = 0; i < (int)fn.size(); i+=5 ) - { - string caseName = fn[i], datasetName = fn[i+1]; - RunParams params; - string ndisp = fn[i+2]; params.ndisp = atoi(ndisp.c_str()); - string winSize = fn[i+3]; params.winSize = atoi(winSize.c_str()); - string fullDP = fn[i+4]; params.fullDP = atoi(fullDP.c_str()) == 0 ? false : true; - caseNames.push_back( caseName ); - caseDatasets.push_back( datasetName ); - caseRunParams.push_back( params ); - } - return code; - } - - virtual int runStereoMatchingAlgorithm( const Mat& leftImg, const Mat& rightImg, - Mat& leftDisp, Mat& /*rightDisp*/, int caseIdx ) - { - RunParams params = caseRunParams[caseIdx]; - assert( params.ndisp%16 == 0 ); - StereoSGBM sgbm( 0, params.ndisp, params.winSize, 10*params.winSize*params.winSize, 40*params.winSize*params.winSize, - 1, 63, 10, 100, 32, params.fullDP ); - sgbm( leftImg, rightImg, leftDisp ); - assert( leftDisp.type() == CV_16SC1 ); - leftDisp/=16; - return 0; - } -}; - -CV_StereoSGBMTest stereoSGBM; - diff --git a/tests/cv/src/asubdivisions.cpp b/tests/cv/src/asubdivisions.cpp deleted file mode 100644 index f10c90a..0000000 --- a/tests/cv/src/asubdivisions.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -class CV_SubdivTest : public CvTest -{ -public: - CV_SubdivTest(); - ~CV_SubdivTest(); - int write_default_params(CvFileStorage* fs); - void clear(); - -protected: - int read_params( CvFileStorage* fs ); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void run_func(); - - int min_log_img_size, max_log_img_size; - CvSize img_size; - int min_log_point_count; - int max_log_point_count; - int point_count; - CvSubdiv2D* subdiv; - CvMemStorage* storage; -}; - - -CV_SubdivTest::CV_SubdivTest() : - CvTest( "subdiv", - "cvCreateSubdivDelaunay2D, cvSubdivDelaunay2DInsert, cvSubdiv2DLocate, " - "cvCalcSubdivVoronoi2D, cvFindNearestPoint2D" ) -{ - test_case_count = 100; - min_log_point_count = 1; - max_log_point_count = 10; - min_log_img_size = 1; - max_log_img_size = 10; - - storage = 0; -} - - -CV_SubdivTest::~CV_SubdivTest() -{ - clear(); -} - - -void CV_SubdivTest::clear() -{ - CvTest::clear(); - cvReleaseMemStorage( &storage ); -} - - -int CV_SubdivTest::write_default_params( CvFileStorage* fs ) -{ - CvTest::write_default_params( fs ); - if( ts->get_testing_mode() != CvTS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "min_log_point_count", min_log_point_count ); - write_param( fs, "max_log_point_count", max_log_point_count ); - write_param( fs, "min_log_img_size", min_log_img_size ); - write_param( fs, "max_log_img_size", max_log_img_size ); - } - return 0; -} - - -int CV_SubdivTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - int t; - - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count ); - min_log_point_count = cvReadInt( find_param( fs, "min_log_point_count" ), min_log_point_count ); - max_log_point_count = cvReadInt( find_param( fs, "max_log_point_count" ), max_log_point_count ); - min_log_img_size = cvReadInt( find_param( fs, "min_log_img_size" ), min_log_img_size ); - max_log_img_size = cvReadInt( find_param( fs, "max_log_img_size" ), max_log_img_size ); - - min_log_point_count = cvTsClipInt( min_log_point_count, 1, 10 ); - max_log_point_count = cvTsClipInt( max_log_point_count, 1, 10 ); - if( min_log_point_count > max_log_point_count ) - CV_SWAP( min_log_point_count, max_log_point_count, t ); - - min_log_img_size = cvTsClipInt( min_log_img_size, 1, 10 ); - max_log_img_size = cvTsClipInt( max_log_img_size, 1, 10 ); - if( min_log_img_size > max_log_img_size ) - CV_SWAP( min_log_img_size, max_log_img_size, t ); - - return 0; -} - - -int CV_SubdivTest::prepare_test_case( int test_case_idx ) -{ - CvRNG* rng = ts->get_rng(); - int code = CvTest::prepare_test_case( test_case_idx ); - if( code < 0 ) - return code; - - clear(); - - point_count = cvRound(exp((cvTsRandReal(rng)* - (max_log_point_count - min_log_point_count) + min_log_point_count)*CV_LOG2)); - img_size.width = cvRound(exp((cvTsRandReal(rng)* - (max_log_img_size - min_log_img_size) + min_log_img_size)*CV_LOG2)); - img_size.height = cvRound(exp((cvTsRandReal(rng)* - (max_log_img_size - min_log_img_size) + min_log_img_size)*CV_LOG2)); - - storage = cvCreateMemStorage( 1 << 10 ); - return 1; -} - - -void CV_SubdivTest::run_func() -{ -} - - -// the whole testing is done here, run_func() is not utilized in this test -int CV_SubdivTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = CvTS::OK; - CvRNG* rng = ts->get_rng(); - int j, k, real_count = point_count; - double xrange = img_size.width*(1 - FLT_EPSILON); - double yrange = img_size.height*(1 - FLT_EPSILON); - - subdiv = subdiv = cvCreateSubdivDelaunay2D( - cvRect( 0, 0, img_size.width, img_size.height ), storage ); - - CvSeq* seq = cvCreateSeq( 0, sizeof(*seq), sizeof(CvPoint2D32f), storage ); - CvSeqWriter writer; - cvStartAppendToSeq( seq, &writer ); - - // insert random points - for( j = 0; j < point_count; j++ ) - { - CvPoint2D32f pt; - CvSubdiv2DPoint* point; - - pt.x = (float)(cvTsRandReal(rng)*xrange); - pt.y = (float)(cvTsRandReal(rng)*yrange); - - CvSubdiv2DPointLocation loc = - cvSubdiv2DLocate( subdiv, pt, 0, &point ); - - if( loc == CV_PTLOC_VERTEX ) - { - int index = cvSeqElemIdx( (CvSeq*)subdiv, point ); - CvPoint2D32f* pt1; - cvFlushSeqWriter( &writer ); - pt1 = (CvPoint2D32f*)cvGetSeqElem( seq, index - 3 ); - - if( !pt1 || - fabs(pt1->x - pt.x) > FLT_EPSILON || - fabs(pt1->y - pt.y) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "The point #%d: (%.1f,%.1f) is said to coinside with a subdivision vertex, " - "however it could be found in a sequence of inserted points\n", j, pt.x, pt.y ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - real_count--; - } - - point = cvSubdivDelaunay2DInsert( subdiv, pt ); - if( point->pt.x != pt.x || point->pt.y != pt.y ) - { - ts->printf( CvTS::LOG, "The point #%d: (%.1f,%.1f) has been incorrectly added\n", j, pt.x, pt.y ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - if( (j + 1) % 10 == 0 || j == point_count - 1 ) - { - if( !icvSubdiv2DCheck( subdiv )) - { - ts->printf( CvTS::LOG, "Subdivision consistency check failed after inserting the point #%d\n", j ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - - if( loc != CV_PTLOC_VERTEX ) - { - CV_WRITE_SEQ_ELEM( pt, writer ); - } - } - - if( code < 0 ) - goto _exit_; - - cvCalcSubdivVoronoi2D( subdiv ); - seq = cvEndWriteSeq( &writer ); - - if( !icvSubdiv2DCheck( subdiv )) - { - ts->printf( CvTS::LOG, "The subdivision failed consistency check after building the Voronoi tesselation\n" ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - for( j = 0; j < MAX((point_count - 5)/10 + 5, 10); j++ ) - { - CvPoint2D32f pt; - double minDistance; - - pt.x = (float)(cvTsRandReal(rng)*xrange); - pt.y = (float)(cvTsRandReal(rng)*yrange); - - CvSubdiv2DPoint* point = cvFindNearestPoint2D( subdiv, pt ); - CvSeqReader reader; - - if( !point ) - { - ts->printf( CvTS::LOG, "There is no nearest point (?!) for the point (%.1f, %.1f) in the subdivision\n", - pt.x, pt.y ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - cvStartReadSeq( seq, &reader ); - minDistance = icvSqDist2D32f( pt, point->pt ); - - for( k = 0; k < seq->total; k++ ) - { - CvPoint2D32f ptt; - CV_READ_SEQ_ELEM( ptt, reader ); - - double distance = icvSqDist2D32f( pt, ptt ); - if( minDistance > distance && icvSqDist2D32f(ptt, point->pt) > FLT_EPSILON*1000 ) - { - ts->printf( CvTS::LOG, "The triangulation vertex (%.3f,%.3f) was said to be nearest to (%.3f,%.3f),\n" - "whereas another vertex (%.3f,%.3f) is closer\n", - point->pt.x, point->pt.y, pt.x, pt.y, ptt.x, ptt.y ); - code = CvTS::FAIL_BAD_ACCURACY; - goto _exit_; - } - } - } - -_exit_: - if( code < 0 ) - ts->set_failed_test_info( code ); - - return code; -} - -CV_SubdivTest subdiv_test; - -/* End of file. */ - diff --git a/tests/cv/src/atemplmatch.cpp b/tests/cv/src/atemplmatch.cpp deleted file mode 100644 index e7fab4b..0000000 --- a/tests/cv/src/atemplmatch.cpp +++ /dev/null @@ -1,431 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const char* templmatch_param_names[] = { "template_size", "method", "size", "channels", "depth", 0 }; -static const int templmatch_depths[] = { CV_8U, CV_32F, -1 }; -static const int templmatch_channels[] = { 1, 3, -1 }; - -static const CvSize templmatch_sizes[] = {{320, 240}, {1024,768}, {-1,-1}}; -static const CvSize templmatch_whole_sizes[] = {{320,240}, {1024,768}, {-1,-1}}; -static const CvSize templmatch_template_sizes[] = {{15,15}, {60,60}, {-1,-1}}; -static const char* templmatch_methods[] = { "sqdiff", "sqdiff_norm", "ccorr", "ccorr_normed", "ccoeff", "ccoeff_normed", 0 }; - -class CV_TemplMatchTest : public CvArrTest -{ -public: - CV_TemplMatchTest(); - -protected: - int read_params( CvFileStorage* fs ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - - int max_template_size; - int method; - bool test_cpp; -}; - - -CV_TemplMatchTest::CV_TemplMatchTest() - : CvArrTest( "match-template", "cvMatchTemplate", "" ) -{ - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - element_wise_relative_error = false; - max_template_size = 100; - method = 0; - - size_list = templmatch_sizes; - whole_size_list = templmatch_whole_sizes; - cn_list = templmatch_channels; - depth_list = templmatch_depths; - - default_timing_param_names = templmatch_param_names; - test_cpp = false; -} - - -int CV_TemplMatchTest::read_params( CvFileStorage* fs ) -{ - int code = CvArrTest::read_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - max_template_size = cvReadInt( find_param( fs, "max_template_size" ), max_template_size ); - max_template_size = cvTsClipInt( max_template_size, 1, 100 ); - } - - return code; -} - - -int CV_TemplMatchTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - write_param( fs, "max_template_size", max_template_size ); - } - else - { - int i; - start_write_param( fs ); - - cvStartWriteStruct( fs, "template_size", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; templmatch_template_sizes[i].width >= 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteInt( fs, 0, templmatch_template_sizes[i].width ); - cvWriteInt( fs, 0, templmatch_template_sizes[i].height ); - cvEndWriteStruct(fs); - } - cvEndWriteStruct(fs); - - write_string_list( fs, "method", templmatch_methods ); - } - - return code; -} - - -void CV_TemplMatchTest::get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ) -{ - CvArrTest::get_minmax_bounds( i, j, type, low, high ); - int depth = CV_MAT_DEPTH(type); - if( depth == CV_32F ) - { - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); - } -} - - -void CV_TemplMatchTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2, cn = cvTsRandInt(rng) & 1 ? 3 : 1; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : CV_32F; - - types[INPUT][0] = types[INPUT][1] = CV_MAKETYPE(depth,cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_32FC1; - - sizes[INPUT][1].width = cvTsRandInt(rng)%MIN(sizes[INPUT][1].width,max_template_size) + 1; - sizes[INPUT][1].height = cvTsRandInt(rng)%MIN(sizes[INPUT][1].height,max_template_size) + 1; - sizes[OUTPUT][0].width = sizes[INPUT][0].width - sizes[INPUT][1].width + 1; - sizes[OUTPUT][0].height = sizes[INPUT][0].height - sizes[INPUT][1].height + 1; - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; - - method = cvTsRandInt(rng)%6; - test_cpp = (cvTsRandInt(rng) & 256) == 0; -} - - -void CV_TemplMatchTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* method_str = cvReadString( find_timing_param( "method" ), "ccorr" ); - const CvFileNode* node = find_timing_param( "template_size" ); - CvSize templ_size, result_size; - - assert( node && CV_NODE_IS_SEQ( node->tag )); - - method = strncmp( method_str, "sqdiff", 6 ) == 0 ? CV_TM_SQDIFF : - strncmp( method_str, "ccorr", 5 ) == 0 ? CV_TM_CCORR : CV_TM_CCOEFF; - method += strstr( method_str, "_normed" ) != 0; - - cvReadRawData( ts->get_file_storage(), node, &templ_size, "2i" ); - - sizes[INPUT][1] = whole_sizes[INPUT][1] = templ_size; - result_size.width = sizes[INPUT][0].width - templ_size.width + 1; - result_size.height = sizes[INPUT][0].height - templ_size.height + 1; - assert( result_size.width > 0 && result_size.height > 0 ); - sizes[OUTPUT][0] = whole_sizes[OUTPUT][0] = result_size; - - types[OUTPUT][0] = CV_32FC1; -} - - -void CV_TemplMatchTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "method" ), "ccorr" ) ); - ptr += strlen(ptr); - sprintf( ptr, "templ_size=%dx%d,", test_mat[INPUT][1].width, test_mat[INPUT][1].height ); - ptr += strlen(ptr); - params_left -= 2; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CV_TemplMatchTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - if( CV_MAT_DEPTH(test_mat[INPUT][1].type) == CV_8U || - (method >= CV_TM_CCOEFF && test_mat[INPUT][1].cols*test_mat[INPUT][1].rows <= 2) ) - return 1e-2; - else - return 1e-3; -} - - -void CV_TemplMatchTest::run_func() -{ - if(!test_cpp) - cvMatchTemplate( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0], method ); - else - { - cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::matchTemplate(cv::cvarrToMat(test_array[INPUT][0]), cv::cvarrToMat(test_array[INPUT][1]), _out, method); - } -} - - -static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* result, int method ) -{ - int i, j, k, l; - int depth = CV_MAT_DEPTH(img->type), cn = CV_MAT_CN(img->type); - int width_n = templ->cols*cn, height = templ->rows; - int a_step = img->step / CV_ELEM_SIZE(img->type & CV_MAT_DEPTH_MASK); - int b_step = templ->step / CV_ELEM_SIZE(templ->type & CV_MAT_DEPTH_MASK); - CvScalar b_mean, b_sdv; - double b_denom = 1., b_sum2 = 0; - int area = templ->rows*templ->cols; - - cvTsMeanStdDevNonZero( templ, 0, &b_mean, &b_sdv, 0 ); - - for( i = 0; i < cn; i++ ) - b_sum2 += (b_sdv.val[i]*b_sdv.val[i] + b_mean.val[i]*b_mean.val[i])*area; - - if( CV_SQR(b_sdv.val[0]) + CV_SQR(b_sdv.val[1]) + - CV_SQR(b_sdv.val[2]) + CV_SQR(b_sdv.val[3]) < DBL_EPSILON && - method == CV_TM_CCOEFF_NORMED ) - { - cvSet( result, cvScalarAll(1.) ); - return; - } - - if( method & 1 ) - { - b_denom = 0; - if( method != CV_TM_CCOEFF_NORMED ) - { - b_denom = b_sum2; - } - else - { - for( i = 0; i < cn; i++ ) - b_denom += b_sdv.val[i]*b_sdv.val[i]*area; - } - b_denom = sqrt(b_denom); - if( b_denom == 0 ) - b_denom = 1.; - } - - assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED ); - - for( i = 0; i < result->rows; i++ ) - { - for( j = 0; j < result->cols; j++ ) - { - CvScalar a_sum = {{ 0, 0, 0, 0 }}, a_sum2 = {{ 0, 0, 0, 0 }}; - CvScalar ccorr = {{ 0, 0, 0, 0 }}; - double value = 0.; - - if( depth == CV_8U ) - { - const uchar* a = img->data.ptr + i*img->step + j*cn; - const uchar* b = templ->data.ptr; - - if( cn == 1 || method < CV_TM_CCOEFF ) - { - for( k = 0; k < height; k++, a += a_step, b += b_step ) - for( l = 0; l < width_n; l++ ) - { - ccorr.val[0] += a[l]*b[l]; - a_sum.val[0] += a[l]; - a_sum2.val[0] += a[l]*a[l]; - } - } - else - { - for( k = 0; k < height; k++, a += a_step, b += b_step ) - for( l = 0; l < width_n; l += 3 ) - { - ccorr.val[0] += a[l]*b[l]; - ccorr.val[1] += a[l+1]*b[l+1]; - ccorr.val[2] += a[l+2]*b[l+2]; - a_sum.val[0] += a[l]; - a_sum.val[1] += a[l+1]; - a_sum.val[2] += a[l+2]; - a_sum2.val[0] += a[l]*a[l]; - a_sum2.val[1] += a[l+1]*a[l+1]; - a_sum2.val[2] += a[l+2]*a[l+2]; - } - } - } - else - { - const float* a = (const float*)(img->data.ptr + i*img->step) + j*cn; - const float* b = (const float*)templ->data.ptr; - - if( cn == 1 || method < CV_TM_CCOEFF ) - { - for( k = 0; k < height; k++, a += a_step, b += b_step ) - for( l = 0; l < width_n; l++ ) - { - ccorr.val[0] += a[l]*b[l]; - a_sum.val[0] += a[l]; - a_sum2.val[0] += a[l]*a[l]; - } - } - else - { - for( k = 0; k < height; k++, a += a_step, b += b_step ) - for( l = 0; l < width_n; l += 3 ) - { - ccorr.val[0] += a[l]*b[l]; - ccorr.val[1] += a[l+1]*b[l+1]; - ccorr.val[2] += a[l+2]*b[l+2]; - a_sum.val[0] += a[l]; - a_sum.val[1] += a[l+1]; - a_sum.val[2] += a[l+2]; - a_sum2.val[0] += a[l]*a[l]; - a_sum2.val[1] += a[l+1]*a[l+1]; - a_sum2.val[2] += a[l+2]*a[l+2]; - } - } - } - - switch( method ) - { - case CV_TM_CCORR: - case CV_TM_CCORR_NORMED: - value = ccorr.val[0]; - break; - case CV_TM_SQDIFF: - case CV_TM_SQDIFF_NORMED: - value = (a_sum2.val[0] + b_sum2 - 2*ccorr.val[0]); - break; - default: - value = (ccorr.val[0] - a_sum.val[0]*b_mean.val[0]+ - ccorr.val[1] - a_sum.val[1]*b_mean.val[1]+ - ccorr.val[2] - a_sum.val[2]*b_mean.val[2]); - } - - if( method & 1 ) - { - double denom; - - // calc denominator - if( method != CV_TM_CCOEFF_NORMED ) - { - denom = a_sum2.val[0] + a_sum2.val[1] + a_sum2.val[2]; - } - else - { - denom = a_sum2.val[0] - (a_sum.val[0]*a_sum.val[0])/area; - denom += a_sum2.val[1] - (a_sum.val[1]*a_sum.val[1])/area; - denom += a_sum2.val[2] - (a_sum.val[2]*a_sum.val[2])/area; - } - denom = sqrt(MAX(denom,0))*b_denom; - if( fabs(value) < denom ) - value /= denom; - else if( fabs(value) < denom*1.125 ) - value = value > 0 ? 1 : -1; - else - value = method != CV_TM_SQDIFF_NORMED ? 0 : 1; - } - - ((float*)(result->data.ptr + result->step*i))[j] = (float)value; - } - } -} - - -void CV_TemplMatchTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsMatchTemplate( &test_mat[INPUT][0], &test_mat[INPUT][1], - &test_mat[REF_OUTPUT][0], method ); - - //if( ts->get_current_test_info()->test_case_idx == 0 ) - /*{ - CvFileStorage* fs = cvOpenFileStorage( "_match_template.yml", 0, CV_STORAGE_WRITE ); - cvWrite( fs, "image", &test_mat[INPUT][0] ); - cvWrite( fs, "template", &test_mat[INPUT][1] ); - cvWrite( fs, "ref", &test_mat[REF_OUTPUT][0] ); - cvWrite( fs, "opencv", &test_mat[OUTPUT][0] ); - cvWriteInt( fs, "method", method ); - cvReleaseFileStorage( &fs ); - }*/ - - if( method >= CV_TM_CCOEFF ) - { - // avoid numerical stability problems in singular cases (when the results are near to 0) - const double delta = 10.; - cvTsAdd( &test_mat[REF_OUTPUT][0], cvScalar(1.), 0, cvScalar(0.), - cvScalar(delta), &test_mat[REF_OUTPUT][0], 0 ); - cvTsAdd( &test_mat[OUTPUT][0], cvScalar(1.), 0, cvScalar(0.), - cvScalar(delta), &test_mat[OUTPUT][0], 0 ); - } -} - - -CV_TemplMatchTest templ_match; diff --git a/tests/cv/src/athresh.cpp b/tests/cv/src/athresh.cpp deleted file mode 100644 index fa6350a..0000000 --- a/tests/cv/src/athresh.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -static const char* thresh_param_names[] = { "size", "depth", "thresh_type", 0 }; -static const CvSize thresh_sizes[] = {{30,30}, {320, 240}, {720,480}, {-1,-1}}; -static const CvSize thresh_whole_sizes[] = {{320,240}, {320, 240}, {720,480}, {-1,-1}}; -static const int thresh_depths[] = { CV_8U, CV_32F, -1 }; -static const char* thresh_types[] = { "binary", "binary_inv", "trunc", "tozero", "tozero_inv", 0 }; - -class CV_ThreshTest : public CvArrTest -{ -public: - CV_ThreshTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - - int thresh_type; - float thresh_val; - float max_val; -}; - - -CV_ThreshTest::CV_ThreshTest() - : CvArrTest( "thresh-simple", "cvThreshold", "" ) -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - optional_mask = false; - element_wise_relative_error = true; - - default_timing_param_names = thresh_param_names; - depth_list = thresh_depths; - size_list = thresh_sizes; - whole_size_list = thresh_whole_sizes; - cn_list = 0; -} - - -void CV_ThreshTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2, cn = cvTsRandInt(rng) % 4 + 1; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : CV_32F; - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - thresh_type = cvTsRandInt(rng) % 5; - - if( depth == CV_8U ) - { - thresh_val = (float)(cvTsRandReal(rng)*350. - 50.); - max_val = (float)(cvTsRandReal(rng)*350. - 50.); - if( cvTsRandInt(rng)%4 == 0 ) - max_val = 255; - } - else - { - thresh_val = (float)(cvTsRandReal(rng)*1000. - 500.); - max_val = (float)(cvTsRandReal(rng)*1000. - 500.); - } -} - - -double CV_ThreshTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return FLT_EPSILON*10; -} - - -void CV_ThreshTest::run_func() -{ - cvThreshold( test_array[INPUT][0], test_array[OUTPUT][0], - thresh_val, max_val, thresh_type ); -} - - -static void cvTsThreshold( const CvMat* _src, CvMat* _dst, - float thresh, float maxval, int thresh_type ) -{ - int i, j; - int depth = CV_MAT_DEPTH(_src->type), cn = CV_MAT_CN(_src->type); - int width_n = _src->cols*cn, height = _src->rows; - int ithresh = cvFloor(thresh), ithresh2, imaxval = cvRound(maxval); - const uchar* src = _src->data.ptr; - uchar* dst = _dst->data.ptr; - - ithresh2 = CV_CAST_8U(ithresh); - imaxval = CV_CAST_8U(imaxval); - - assert( depth == CV_8U || depth == CV_32F ); - - switch( thresh_type ) - { - case CV_THRESH_BINARY: - for( i = 0; i < height; i++, src += _src->step, dst += _dst->step ) - { - if( depth == CV_8U ) - for( j = 0; j < width_n; j++ ) - dst[j] = (uchar)(src[j] > ithresh ? imaxval : 0); - else - for( j = 0; j < width_n; j++ ) - ((float*)dst)[j] = ((const float*)src)[j] > thresh ? maxval : 0.f; - } - break; - case CV_THRESH_BINARY_INV: - for( i = 0; i < height; i++, src += _src->step, dst += _dst->step ) - { - if( depth == CV_8U ) - for( j = 0; j < width_n; j++ ) - dst[j] = (uchar)(src[j] > ithresh ? 0 : imaxval); - else - for( j = 0; j < width_n; j++ ) - ((float*)dst)[j] = ((const float*)src)[j] > thresh ? 0.f : maxval; - } - break; - case CV_THRESH_TRUNC: - for( i = 0; i < height; i++, src += _src->step, dst += _dst->step ) - { - if( depth == CV_8U ) - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? ithresh2 : s); - } - else - for( j = 0; j < width_n; j++ ) - { - float s = ((const float*)src)[j]; - ((float*)dst)[j] = s > thresh ? thresh : s; - } - } - break; - case CV_THRESH_TOZERO: - for( i = 0; i < height; i++, src += _src->step, dst += _dst->step ) - { - if( depth == CV_8U ) - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? s : 0); - } - else - for( j = 0; j < width_n; j++ ) - { - float s = ((const float*)src)[j]; - ((float*)dst)[j] = s > thresh ? s : 0.f; - } - } - break; - case CV_THRESH_TOZERO_INV: - for( i = 0; i < height; i++, src += _src->step, dst += _dst->step ) - { - if( depth == CV_8U ) - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? 0 : s); - } - else - for( j = 0; j < width_n; j++ ) - { - float s = ((const float*)src)[j]; - ((float*)dst)[j] = s > thresh ? 0.f : s; - } - } - break; - default: - assert(0); - } -} - - -void CV_ThreshTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsThreshold( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], - thresh_val, max_val, thresh_type ); -} - - -int CV_ThreshTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - start_write_param( fs ); - write_string_list( fs, "thresh_type", thresh_types ); - } - - return code; -} - - -void CV_ThreshTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* thresh_str = cvReadString( find_timing_param( "thresh_type" ), "binary" ); - thresh_type = strcmp( thresh_str, "binary" ) == 0 ? CV_THRESH_BINARY : - strcmp( thresh_str, "binary_inv" ) == 0 ? CV_THRESH_BINARY_INV : - strcmp( thresh_str, "trunc" ) == 0 ? CV_THRESH_TRUNC : - strcmp( thresh_str, "tozero" ) == 0 ? CV_THRESH_TOZERO : - CV_THRESH_TOZERO_INV; - - if( CV_MAT_DEPTH(types[INPUT][0]) == CV_8U ) - { - thresh_val = 128; - max_val = 255; - } - else - { - thresh_val = 500.; - max_val = 1.; - } -} - - -void CV_ThreshTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param( "thresh_type" ), "binary" ) ); - ptr += strlen(ptr); - params_left--; - - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -CV_ThreshTest thresh_test; - diff --git a/tests/cv/src/aundistort.cpp b/tests/cv/src/aundistort.cpp deleted file mode 100644 index 264ce56..0000000 --- a/tests/cv/src/aundistort.cpp +++ /dev/null @@ -1,907 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - - -class CV_DefaultNewCameraMatrixTest : public CvArrTest -{ -public: - CV_DefaultNewCameraMatrixTest(); -protected: - int prepare_test_case (int test_case_idx); - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - -private: - cv::Size img_size; - cv::Mat camera_mat; - cv::Mat new_camera_mat; - - int matrix_type; - - bool center_principal_point; - - static const int MAX_X = 2048; - static const int MAX_Y = 2048; - static const int MAX_VAL = 10000; -}; - -CV_DefaultNewCameraMatrixTest::CV_DefaultNewCameraMatrixTest() : CvArrTest("undistort-getDefaultNewCameraMatrix","getDefaultNewCameraMatrix") -{ - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); -} - -void CV_DefaultNewCameraMatrixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvArrTest::get_test_array_types_and_sizes(test_case_idx,sizes,types); - CvRNG* rng = ts->get_rng(); - matrix_type = types[INPUT][0] = types[OUTPUT][0]= types[REF_OUTPUT][0] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - sizes[INPUT][0] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(3,3); -} - -int CV_DefaultNewCameraMatrixTest::prepare_test_case(int test_case_idx) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - - if (code <= 0) - return code; - - CvRNG* rng = ts->get_rng(); - - img_size.width = cvTsRandInt(rng) % MAX_X + 1; - img_size.height = cvTsRandInt(rng) % MAX_Y + 1; - - center_principal_point = ((cvTsRandInt(rng) % 2)!=0); - - // Generating camera_mat matrix - double sz = MAX(img_size.width, img_size.height); - double aspect_ratio = cvTsRandReal(rng)*0.6 + 0.7; - double a[9] = {0,0,0,0,0,0,0,0,1}; - CvMat _a = cvMat(3,3,CV_64F,a); - a[2] = (img_size.width - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[5] = (img_size.height - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - a[0] = sz/(0.9 - cvTsRandReal(rng)*0.6); - a[4] = aspect_ratio*a[0]; - - //Copying into input array - CvMat* _a0 = &test_mat[INPUT][0]; - cvTsConvert( &_a, _a0 ); - camera_mat = _a0; - //new_camera_mat = camera_mat; - - return code; - -} - -void CV_DefaultNewCameraMatrixTest::run_func() -{ - new_camera_mat = cv::getDefaultNewCameraMatrix(camera_mat,img_size,center_principal_point); -} - -void CV_DefaultNewCameraMatrixTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - const CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_OUTPUT][0]; - CvMat* test_output = &test_mat[OUTPUT][0]; - CvMat output = new_camera_mat; - cvTsConvert( &output, test_output ); - if (!center_principal_point) - { - cvCopy(src,dst); - } - else - { - double a[9] = {0,0,0,0,0,0,0,0,1}; - CvMat _a = cvMat(3,3,CV_64F,a); - if (matrix_type == CV_64F) - { - a[0] = ((double*)(src->data.ptr + src->step*0))[0]; - a[4] = ((double*)(src->data.ptr + src->step*1))[1]; - } - else - { - a[0] = (double)((float*)(src->data.ptr + src->step*0))[0]; - a[4] = (double)((float*)(src->data.ptr + src->step*1))[1]; - } - a[2] = (img_size.width - 1)*0.5; - a[5] = (img_size.height - 1)*0.5; - cvTsConvert( &_a, dst ); - } -} - -CV_DefaultNewCameraMatrixTest default_new_camera_matrix_test; - -//--------- - -class CV_UndistortPointsTest : public CvArrTest -{ -public: - CV_UndistortPointsTest(); -protected: - int prepare_test_case (int test_case_idx); - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void cvTsDistortPoints(const CvMat* _src, CvMat* _dst, const CvMat* _cameraMatrix, - const CvMat* _distCoeffs, - const CvMat* matR, const CvMat* matP); - -private: - bool useCPlus; - bool useDstMat; - static const int N_POINTS = 10; - static const int MAX_X = 2048; - static const int MAX_Y = 2048; - - bool zero_new_cam; - bool zero_distortion; - bool zero_R; - - cv::Size img_size; - cv::Mat dst_points_mat; - - cv::Mat camera_mat; - cv::Mat R; - cv::Mat P; - cv::Mat distortion_coeffs; - cv::Mat src_points; - std::vector dst_points; -}; - -CV_UndistortPointsTest::CV_UndistortPointsTest() : CvArrTest("undistort-points","cvUndistortPoints") -{ - test_array[INPUT].push(NULL); // points matrix - test_array[INPUT].push(NULL); // camera matrix - test_array[INPUT].push(NULL); // distortion coeffs - test_array[INPUT].push(NULL); // R matrix - test_array[INPUT].push(NULL); // P matrix - test_array[OUTPUT].push(NULL); // distorted dst points - test_array[TEMP].push(NULL); // dst points - test_array[REF_OUTPUT].push(NULL); -} - -void CV_UndistortPointsTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvArrTest::get_test_array_types_and_sizes(test_case_idx,sizes,types); - CvRNG* rng = ts->get_rng(); - useCPlus = ((cvTsRandInt(rng) % 2)!=0); - //useCPlus = 0; - if (useCPlus) - { - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0]= CV_32FC2; - } - else - { - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0]= cvTsRandInt(rng)%2 ? CV_64FC2 : CV_32FC2; - } - types[INPUT][1] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][2] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][3] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][4] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - - sizes[INPUT][0] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sizes[TEMP][0]= cvTsRandInt(rng)%2 ? cvSize(1,N_POINTS) : cvSize(N_POINTS,1); - sizes[INPUT][1] = sizes[INPUT][3] = cvSize(3,3); - sizes[INPUT][4] = cvTsRandInt(rng)%2 ? cvSize(3,3) : cvSize(4,3); - - if (cvTsRandInt(rng)%2) - { - if (cvTsRandInt(rng)%2) - { - sizes[INPUT][2] = cvSize(1,4); - } - else - { - sizes[INPUT][2] = cvSize(1,5); - } - } - else - { - if (cvTsRandInt(rng)%2) - { - sizes[INPUT][2] = cvSize(4,1); - } - else - { - sizes[INPUT][2] = cvSize(5,1); - } - } -} - -int CV_UndistortPointsTest::prepare_test_case(int test_case_idx) -{ - CvRNG* rng = ts->get_rng(); - int code = CvArrTest::prepare_test_case( test_case_idx ); - - if (code <= 0) - return code; - - useDstMat = (cvTsRandInt(rng) % 2) == 0; - - img_size.width = cvTsRandInt(rng) % MAX_X + 1; - img_size.height = cvTsRandInt(rng) % MAX_Y + 1; - int dist_size = test_mat[INPUT][2].cols > test_mat[INPUT][2].rows ? test_mat[INPUT][2].cols : test_mat[INPUT][2].rows; - double cam[9] = {0,0,0,0,0,0,0,0,1}; - double* dist = new double[dist_size ]; - double* proj = new double[test_mat[INPUT][4].cols * test_mat[INPUT][4].rows]; - double* points = new double[N_POINTS*2]; - - CvMat _camera = cvMat(3,3,CV_64F,cam); - CvMat _distort = cvMat(test_mat[INPUT][2].rows,test_mat[INPUT][2].cols,CV_64F,dist); - CvMat _proj = cvMat(test_mat[INPUT][4].rows,test_mat[INPUT][4].cols,CV_64F,proj); - CvMat _points= cvMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_64FC2, points); - - for (int i=0;i 0 ) - dist[1] = -dist[1]; - if( cvTsRandInt(rng)%4 != 0 ) - { - dist[2] = cvTsRandReal(rng)*0.004 - 0.002; - dist[3] = cvTsRandReal(rng)*0.004 - 0.002; - if (dist_size > 4) - dist[4] = cvTsRandReal(rng)*0.004 - 0.002; - } - else - { - dist[2] = dist[3] = 0; - if (dist_size > 4) - dist[4] = 0; - } - - //Generating P matrix (projection) - if ( test_mat[INPUT][4].cols != 4) - { - proj[8] = 1; - if (cvTsRandInt(rng)%2 == 0) // use identity new camera matrix - { - proj[0] = 1; - proj[4] = 1; - } - else - { - proj[0] = cam[0] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[0]; //10% - proj[4] = cam[4] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[4]; //10% - proj[2] = cam[2] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.width; //15% - proj[5] = cam[5] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.height; //15% - } - } - else - { - proj[10] = 1; - proj[0] = cam[0] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[0]; //10% - proj[5] = cam[4] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[4]; //10% - proj[2] = cam[2] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.width; //15% - proj[6] = cam[5] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.height; //15% - - proj[3] = (img_size.height + img_size.width - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - proj[7] = (img_size.height + img_size.width - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - proj[11] = (img_size.height + img_size.width - 1)*0.5 + cvTsRandReal(rng)*10 - 5; - } - - //Generating R matrix - CvMat* _rot = cvCreateMat(3,3,CV_64F); - CvMat* rotation = cvCreateMat(1,3,CV_64F); - rotation->data.db[0] = CV_PI*(cvTsRandReal(rng) - (double)0.5); // phi - rotation->data.db[1] = CV_PI*(cvTsRandReal(rng) - (double)0.5); // ksi - rotation->data.db[2] = CV_PI*(cvTsRandReal(rng) - (double)0.5); //khi - cvRodrigues2(rotation,_rot); - cvReleaseMat(&rotation); - - //copying data - //src_points = &_points; - CvMat* dst = &test_mat[INPUT][0]; - cvTsConvert( &_points, dst); - dst = &test_mat[INPUT][1]; - cvTsConvert( &_camera, dst); - dst = &test_mat[INPUT][2]; - cvTsConvert( &_distort, dst); - dst = &test_mat[INPUT][3]; - cvTsConvert( _rot, dst); - dst = &test_mat[INPUT][4]; - cvTsConvert( &_proj, dst); - - zero_distortion = (cvRandInt(rng)%2) == 0 ? false : true; - zero_new_cam = (cvRandInt(rng)%2) == 0 ? false : true; - zero_R = (cvRandInt(rng)%2) == 0 ? false : true; - - - cvReleaseMat(&_rot); - - if (useCPlus) - { - CvMat* temp = cvCreateMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_32FC2); - for (int i=0;idata.fl[i] = (float)_points.data.db[i]; - - - src_points = cv::Mat(temp,true); - - cvReleaseMat(&temp); - - camera_mat = &test_mat[INPUT][1]; - distortion_coeffs = &test_mat[INPUT][2]; - R = &test_mat[INPUT][3]; - P = &test_mat[INPUT][4]; - } - delete[] dist; - delete[] proj; - delete[] points; - - return code; -} - -void CV_UndistortPointsTest::prepare_to_validation(int /*test_case_idx*/) -{ - int dist_size = test_mat[INPUT][2].cols > test_mat[INPUT][2].rows ? test_mat[INPUT][2].cols : test_mat[INPUT][2].rows; - double cam[9] = {0,0,0,0,0,0,0,0,1}; - double rot[9] = {1,0,0,0,1,0,0,0,1}; - double* dist = new double[dist_size ]; - double* proj = new double[test_mat[INPUT][4].cols * test_mat[INPUT][4].rows]; - double* points = new double[N_POINTS*2]; - double* r_points = new double[N_POINTS*2]; - //Run reference calculations - CvMat ref_points= cvMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_64FC2,r_points); - CvMat _camera = cvMat(3,3,CV_64F,cam); - CvMat _rot = cvMat(3,3,CV_64F,rot); - CvMat _distort = cvMat(test_mat[INPUT][2].rows,test_mat[INPUT][2].cols,CV_64F,dist); - CvMat _proj = cvMat(test_mat[INPUT][4].rows,test_mat[INPUT][4].cols,CV_64F,proj); - CvMat _points= cvMat(test_mat[TEMP][0].rows,test_mat[TEMP][0].cols,CV_64FC2,points); - - - cvTsConvert(&test_mat[INPUT][1],&_camera); - cvTsConvert(&test_mat[INPUT][2],&_distort); - cvTsConvert(&test_mat[INPUT][3],&_rot); - cvTsConvert(&test_mat[INPUT][4],&_proj); - - if (useCPlus) - { - if (useDstMat) - { - CvMat temp = dst_points_mat; - for (int i=0;icols == 3)) - __P = cvCreateMat(3,3,CV_64F); - else - __P = cvCreateMat(3,4,CV_64F); - if (matP) - { - cvTsConvert(matP,__P); - } - else - { - cvZero(__P); - __P->data.db[0] = 1; - __P->data.db[4] = 1; - __P->data.db[8] = 1; - } - CvMat* __R = cvCreateMat(3,3,CV_64F);; - if (matR) - { - cvCopy(matR,__R); - } - else - { - cvZero(__R); - __R->data.db[0] = 1; - __R->data.db[4] = 1; - __R->data.db[8] = 1; - } - for (int i=0;icols > 3 ? 1 : 0; - double x = (_src->data.db[2*i]-__P->data.db[2])/__P->data.db[0]; - double y = (_src->data.db[2*i+1]-__P->data.db[5+movement])/__P->data.db[4+movement]; - CvMat inverse = cvMat(3,3,CV_64F,a); - cvInvert(__R,&inverse); - double w1 = x*inverse.data.db[6]+y*inverse.data.db[7]+inverse.data.db[8]; - double _x = (x*inverse.data.db[0]+y*inverse.data.db[1]+inverse.data.db[2])/w1; - double _y = (x*inverse.data.db[3]+y*inverse.data.db[4]+inverse.data.db[5])/w1; - - //Distortions - - double __x = _x; - double __y = _y; - if (_distCoeffs) - { - double r2 = _x*_x+_y*_y; - - __x = _x*(1+_distCoeffs->data.db[0]*r2+_distCoeffs->data.db[1]*r2*r2)+ - 2*_distCoeffs->data.db[2]*_x*_y+_distCoeffs->data.db[3]*(r2+2*_x*_x); - __y = _y*(1+_distCoeffs->data.db[0]*r2+_distCoeffs->data.db[1]*r2*r2)+ - 2*_distCoeffs->data.db[3]*_x*_y+_distCoeffs->data.db[2]*(r2+2*_y*_y); - if ((_distCoeffs->cols > 4) || (_distCoeffs->rows > 4)) - { - __x+=_x*_distCoeffs->data.db[4]*r2*r2*r2; - __y+=_y*_distCoeffs->data.db[4]*r2*r2*r2; - } - } - - - _dst->data.db[2*i] = __x*_cameraMatrix->data.db[0]+_cameraMatrix->data.db[2]; - _dst->data.db[2*i+1] = __y*_cameraMatrix->data.db[4]+_cameraMatrix->data.db[5]; - - } - - cvReleaseMat(&__R); - cvReleaseMat(&__P); - -} - -double CV_UndistortPointsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 5e-2; -} - -CV_UndistortPointsTest undistort_points_test; - -//------------------------------------------------------ - -class CV_InitUndistortRectifyMapTest : public CvArrTest -{ -public: - CV_InitUndistortRectifyMapTest(); -protected: - int prepare_test_case (int test_case_idx); - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - -private: - bool useCPlus; - static const int N_POINTS = 100; - static const int MAX_X = 2048; - static const int MAX_Y = 2048; - bool zero_new_cam; - bool zero_distortion; - bool zero_R; - - - cv::Size img_size; - - cv::Mat camera_mat; - cv::Mat R; - cv::Mat new_camera_mat; - cv::Mat distortion_coeffs; - cv::Mat mapx; - cv::Mat mapy; - CvMat* _mapx; - CvMat* _mapy; - int mat_type; -}; - -CV_InitUndistortRectifyMapTest::CV_InitUndistortRectifyMapTest() : CvArrTest("undistort-undistort_rectify_map","cvInitUndistortRectifyMap") -{ - test_array[INPUT].push(NULL); // test points matrix - test_array[INPUT].push(NULL); // camera matrix - test_array[INPUT].push(NULL); // distortion coeffs - test_array[INPUT].push(NULL); // R matrix - test_array[INPUT].push(NULL); // new camera matrix - test_array[OUTPUT].push(NULL); // distorted dst points - test_array[REF_OUTPUT].push(NULL); -} - -void CV_InitUndistortRectifyMapTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvArrTest::get_test_array_types_and_sizes(test_case_idx,sizes,types); - CvRNG* rng = ts->get_rng(); - useCPlus = ((cvTsRandInt(rng) % 2)!=0); - //useCPlus = 0; - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC2; - - types[INPUT][1] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][2] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][3] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - types[INPUT][4] = cvTsRandInt(rng)%2 ? CV_64F : CV_32F; - - sizes[INPUT][0] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(N_POINTS,1); - sizes[INPUT][1] = sizes[INPUT][3] = cvSize(3,3); - sizes[INPUT][4] = cvSize(3,3); - - if (cvTsRandInt(rng)%2) - { - if (cvTsRandInt(rng)%2) - { - sizes[INPUT][2] = cvSize(1,4); - } - else - { - sizes[INPUT][2] = cvSize(1,5); - } - } - else - { - if (cvTsRandInt(rng)%2) - { - sizes[INPUT][2] = cvSize(4,1); - } - else - { - sizes[INPUT][2] = cvSize(5,1); - } - } -} - -int CV_InitUndistortRectifyMapTest::prepare_test_case(int test_case_idx) -{ - CvRNG* rng = ts->get_rng(); - int code = CvArrTest::prepare_test_case( test_case_idx ); - - if (code <= 0) - return code; - - img_size.width = cvTsRandInt(rng) % MAX_X + 1; - img_size.height = cvTsRandInt(rng) % MAX_Y + 1; - - if (useCPlus) - { - mat_type = (cvTsRandInt(rng) % 2) == 0 ? CV_32FC1 : CV_16SC2; - if ((cvTsRandInt(rng) % 4) == 0) - mat_type = -1; - if ((cvTsRandInt(rng) % 4) == 0) - mat_type = CV_32FC2; - _mapx = 0; - _mapy = 0; - } - else - { - int typex = (cvTsRandInt(rng) % 2) == 0 ? CV_32FC1 : CV_16SC2; - //typex = CV_32FC1; ///!!!!!!!!!!!!!!!! - int typey = (typex == CV_32FC1) ? CV_32FC1 : CV_16UC1; - - _mapx = cvCreateMat(img_size.height,img_size.width,typex); - _mapy = cvCreateMat(img_size.height,img_size.width,typey); - - - } - - int dist_size = test_mat[INPUT][2].cols > test_mat[INPUT][2].rows ? test_mat[INPUT][2].cols : test_mat[INPUT][2].rows; - double cam[9] = {0,0,0,0,0,0,0,0,1}; - double* dist = new double[dist_size ]; - double* new_cam = new double[test_mat[INPUT][4].cols * test_mat[INPUT][4].rows]; - double* points = new double[N_POINTS*2]; - - CvMat _camera = cvMat(3,3,CV_64F,cam); - CvMat _distort = cvMat(test_mat[INPUT][2].rows,test_mat[INPUT][2].cols,CV_64F,dist); - CvMat _new_cam = cvMat(test_mat[INPUT][4].rows,test_mat[INPUT][4].cols,CV_64F,new_cam); - CvMat _points= cvMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_64FC2, points); - - for (int i=0;i 0 ) - dist[1] = -dist[1]; - if( cvTsRandInt(rng)%4 != 0 ) - { - dist[2] = cvTsRandReal(rng)*0.004 - 0.002; - dist[3] = cvTsRandReal(rng)*0.004 - 0.002; - if (dist_size > 4) - dist[4] = cvTsRandReal(rng)*0.004 - 0.002; - } - else - { - dist[2] = dist[3] = 0; - if (dist_size > 4) - dist[4] = 0; - } - - //Generating new camera matrix - - new_cam[8] = 1; - - //new_cam[0] = cam[0]; - //new_cam[4] = cam[4]; - //new_cam[2] = cam[2]; - //new_cam[5] = cam[5]; - - new_cam[0] = cam[0] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[0]; //10% - new_cam[4] = cam[4] + (cvTsRandReal(rng) - (double)0.5)*0.2*cam[4]; //10% - new_cam[2] = cam[2] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.width; //15% - new_cam[5] = cam[5] + (cvTsRandReal(rng) - (double)0.5)*0.3*img_size.height; //15% - - - //Generating R matrix - CvMat* _rot = cvCreateMat(3,3,CV_64F); - CvMat* rotation = cvCreateMat(1,3,CV_64F); - rotation->data.db[0] = CV_PI/8*(cvTsRandReal(rng) - (double)0.5); // phi - rotation->data.db[1] = CV_PI/8*(cvTsRandReal(rng) - (double)0.5); // ksi - rotation->data.db[2] = CV_PI/3*(cvTsRandReal(rng) - (double)0.5); //khi - cvRodrigues2(rotation,_rot); - cvReleaseMat(&rotation); - - //cvSetIdentity(_rot); - //copying data - CvMat* dst = &test_mat[INPUT][0]; - cvTsConvert( &_points, dst); - dst = &test_mat[INPUT][1]; - cvTsConvert( &_camera, dst); - dst = &test_mat[INPUT][2]; - cvTsConvert( &_distort, dst); - dst = &test_mat[INPUT][3]; - cvTsConvert( _rot, dst); - dst = &test_mat[INPUT][4]; - cvTsConvert( &_new_cam, dst); - - zero_distortion = (cvRandInt(rng)%2) == 0 ? false : true; - zero_new_cam = (cvRandInt(rng)%2) == 0 ? false : true; - zero_R = (cvRandInt(rng)%2) == 0 ? false : true; - - cvReleaseMat(&_rot); - - if (useCPlus) - { - camera_mat = &test_mat[INPUT][1]; - distortion_coeffs = &test_mat[INPUT][2]; - R = &test_mat[INPUT][3]; - new_camera_mat = &test_mat[INPUT][4]; - } - delete[] dist; - delete[] new_cam; - delete[] points; - - return code; -} - -void CV_InitUndistortRectifyMapTest::prepare_to_validation(int/* test_case_idx*/) -{ - int dist_size = test_mat[INPUT][2].cols > test_mat[INPUT][2].rows ? test_mat[INPUT][2].cols : test_mat[INPUT][2].rows; - double cam[9] = {0,0,0,0,0,0,0,0,1}; - double rot[9] = {1,0,0,0,1,0,0,0,1}; - double* dist = new double[dist_size ]; - double* new_cam = new double[test_mat[INPUT][4].cols * test_mat[INPUT][4].rows]; - double* points = new double[N_POINTS*2]; - double* r_points = new double[N_POINTS*2]; - //Run reference calculations - CvMat ref_points= cvMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_64FC2,r_points); - CvMat _camera = cvMat(3,3,CV_64F,cam); - CvMat _rot = cvMat(3,3,CV_64F,rot); - CvMat _distort = cvMat(test_mat[INPUT][2].rows,test_mat[INPUT][2].cols,CV_64F,dist); - CvMat _new_cam = cvMat(test_mat[INPUT][4].rows,test_mat[INPUT][4].cols,CV_64F,new_cam); - CvMat _points= cvMat(test_mat[INPUT][0].rows,test_mat[INPUT][0].cols,CV_64FC2,points); - - cvTsConvert(&test_mat[INPUT][1],&_camera); - cvTsConvert(&test_mat[INPUT][2],&_distort); - cvTsConvert(&test_mat[INPUT][3],&_rot); - cvTsConvert(&test_mat[INPUT][4],&_new_cam); - - //Applying precalculated undistort rectify map - if (!useCPlus) - { - mapx = cv::Mat(_mapx); - mapy = cv::Mat(_mapy); - } - cv::Mat map1,map2; - cv::convertMaps(mapx,mapy,map1,map2,CV_32FC1); - CvMat _map1 = map1; - CvMat _map2 = map2; - for (int i=0;i - -using namespace cv; -using namespace std; - -class CV_CameraCalibrationBadArgTest : public CvBadArgTest -{ -public: - CV_CameraCalibrationBadArgTest() : CvBadArgTest("calibrate-camera-c-badarg", "cvCalibrateCamera2"), - imgSize(800, 600) - { - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; - }; - ~CV_CameraCalibrationBadArgTest() {} ; -protected: - void run(int); - void run_func(void) {}; - - const static int M = 1; - - Size imgSize; - Size corSize; - Mat chessBoard; - Mat corners; - - struct C_Caller - { - CvMat* objPts; - CvMat* imgPts; - CvMat* npoints; - Size imageSize; - CvMat *cameraMatrix; - CvMat *distCoeffs; - CvMat *rvecs; - CvMat *tvecs; - int flags; - - void operator()() const - { - cvCalibrateCamera2(objPts, imgPts, npoints, imageSize, - cameraMatrix, distCoeffs, rvecs, tvecs, flags ); - } - }; -}; - - -void CV_CameraCalibrationBadArgTest::run( int /* start_from */ ) -{ - Mat_ camMat(3, 3); - Mat_ distCoeffs0(1, 5); - - camMat << 300.f, 0.f, imgSize.width/2.f, 0, 300.f, imgSize.height/2.f, 0.f, 0.f, 1.f; - distCoeffs0 << 1.2f, 0.2f, 0.f, 0.f, 0.f; - - ChessBoardGenerator cbg(Size(8,6)); - corSize = cbg.cornersSize(); - vector exp_corn; - chessBoard = cbg(Mat(imgSize, CV_8U, Scalar(0)), camMat, distCoeffs0, exp_corn); - Mat_(corSize.height, corSize.width, (Point2f*)&exp_corn[0]).copyTo(corners); - - CvMat objPts, imgPts, npoints, cameraMatrix, distCoeffs, rvecs, tvecs; - Mat zeros(1, sizeof(CvMat), CV_8U, Scalar(0)); - - C_Caller caller, bad_caller; - caller.imageSize = imgSize; - caller.objPts = &objPts; - caller.imgPts = &imgPts; - caller.npoints = &npoints; - caller.cameraMatrix = &cameraMatrix; - caller.distCoeffs = &distCoeffs; - caller.rvecs = &rvecs; - caller.tvecs = &tvecs; - - ///////////////////////////// - Mat objPts_cpp; - Mat imgPts_cpp; - Mat npoints_cpp; - Mat cameraMatrix_cpp; - Mat distCoeffs_cpp; - Mat rvecs_cpp; - Mat tvecs_cpp; - - objPts_cpp.create(corSize, CV_32FC3); - for(int j = 0; j < corSize.height; ++j) - for(int i = 0; i < corSize.width; ++i) - objPts_cpp.at(j, i) = Point3i(i, j, 0); - objPts_cpp = objPts_cpp.reshape(3, 1); - - imgPts_cpp = corners.clone().reshape(2, 1); - npoints_cpp = Mat_(M, 1, corSize.width * corSize.height); - cameraMatrix_cpp.create(3, 3, CV_32F); - distCoeffs_cpp.create(5, 1, CV_32F); - rvecs_cpp.create(M, 1, CV_32FC3); - tvecs_cpp.create(M, 1, CV_32FC3); - - caller.flags = 0; - //CV_CALIB_USE_INTRINSIC_GUESS; //CV_CALIB_FIX_ASPECT_RATIO - //CV_CALIB_USE_INTRINSIC_GUESS //CV_CALIB_FIX_ASPECT_RATIO - //CV_CALIB_FIX_PRINCIPAL_POINT //CV_CALIB_ZERO_TANGENT_DIST - //CV_CALIB_FIX_FOCAL_LENGTH //CV_CALIB_FIX_K1 //CV_CALIB_FIX_K2 //CV_CALIB_FIX_K3 - - objPts = objPts_cpp; - imgPts = imgPts_cpp; - npoints = npoints_cpp; - cameraMatrix = cameraMatrix_cpp; - distCoeffs = distCoeffs_cpp; - rvecs = rvecs_cpp; - tvecs = tvecs_cpp; - - /* /*//*/ */ - int errors = 0; - - bad_caller = caller; - bad_caller.objPts = 0; - errors += run_test_case( CV_StsBadArg, "Zero passed in objPts", bad_caller); - - bad_caller = caller; - bad_caller.imgPts = 0; - errors += run_test_case( CV_StsBadArg, "Zero passed in imgPts", bad_caller ); - - bad_caller = caller; - bad_caller.npoints = 0; - errors += run_test_case( CV_StsBadArg, "Zero passed in npoints", bad_caller ); - - bad_caller = caller; - bad_caller.cameraMatrix = 0; - errors += run_test_case( CV_StsBadArg, "Zero passed in cameraMatrix", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = 0; - errors += run_test_case( CV_StsBadArg, "Zero passed in distCoeffs", bad_caller ); - - bad_caller = caller; - bad_caller.imageSize.width = -1; - errors += run_test_case( CV_StsOutOfRange, "Bad image width", bad_caller ); - - bad_caller = caller; - bad_caller.imageSize.height = -1; - errors += run_test_case( CV_StsOutOfRange, "Bad image height", bad_caller ); - - Mat bad_nts_cpp1 = Mat_(M, 1, 1.f); - Mat bad_nts_cpp2 = Mat_(3, 3, corSize.width * corSize.height); - CvMat bad_npts_c1 = bad_nts_cpp1; - CvMat bad_npts_c2 = bad_nts_cpp2; - - bad_caller = caller; - bad_caller.npoints = &bad_npts_c1; - errors += run_test_case( CV_StsUnsupportedFormat, "Bad npoints format", bad_caller ); - - bad_caller = caller; - bad_caller.npoints = &bad_npts_c2; - errors += run_test_case( CV_StsUnsupportedFormat, "Bad npoints size", bad_caller ); - - bad_caller = caller; - bad_caller.rvecs = (CvMat*)zeros.ptr(); - errors += run_test_case( CV_StsBadArg, "Bad rvecs header", bad_caller ); - - bad_caller = caller; - bad_caller.tvecs = (CvMat*)zeros.ptr(); - errors += run_test_case( CV_StsBadArg, "Bad tvecs header", bad_caller ); - - Mat bad_rvecs_cpp1(M+1, 1, CV_32FC3); CvMat bad_rvecs_c1 = bad_rvecs_cpp1; - Mat bad_tvecs_cpp1(M+1, 1, CV_32FC3); CvMat bad_tvecs_c1 = bad_tvecs_cpp1; - - - - Mat bad_rvecs_cpp2(M, 2, CV_32FC3); CvMat bad_rvecs_c2 = bad_rvecs_cpp2; - Mat bad_tvecs_cpp2(M, 2, CV_32FC3); CvMat bad_tvecs_c2 = bad_tvecs_cpp2; - - bad_caller = caller; - bad_caller.rvecs = &bad_rvecs_c1; - errors += run_test_case( CV_StsBadArg, "Bad tvecs header", bad_caller ); - - bad_caller = caller; - bad_caller.rvecs = &bad_rvecs_c2; - errors += run_test_case( CV_StsBadArg, "Bad tvecs header", bad_caller ); - - bad_caller = caller; - bad_caller.tvecs = &bad_tvecs_c1; - errors += run_test_case( CV_StsBadArg, "Bad tvecs header", bad_caller ); - - bad_caller = caller; - bad_caller.tvecs = &bad_tvecs_c2; - errors += run_test_case( CV_StsBadArg, "Bad tvecs header", bad_caller ); - - Mat bad_cameraMatrix_cpp1(3, 3, CV_32S); CvMat bad_cameraMatrix_c1 = bad_cameraMatrix_cpp1; - Mat bad_cameraMatrix_cpp2(2, 3, CV_32F); CvMat bad_cameraMatrix_c2 = bad_cameraMatrix_cpp2; - Mat bad_cameraMatrix_cpp3(3, 2, CV_64F); CvMat bad_cameraMatrix_c3 = bad_cameraMatrix_cpp3; - - - - bad_caller = caller; - bad_caller.cameraMatrix = &bad_cameraMatrix_c1; - errors += run_test_case( CV_StsBadArg, "Bad camearaMatrix header", bad_caller ); - - bad_caller = caller; - bad_caller.cameraMatrix = &bad_cameraMatrix_c2; - errors += run_test_case( CV_StsBadArg, "Bad camearaMatrix header", bad_caller ); - - bad_caller = caller; - bad_caller.cameraMatrix = &bad_cameraMatrix_c3; - errors += run_test_case( CV_StsBadArg, "Bad camearaMatrix header", bad_caller ); - - Mat bad_distCoeffs_cpp1(1, 5, CV_32S); CvMat bad_distCoeffs_c1 = bad_distCoeffs_cpp1; - Mat bad_distCoeffs_cpp2(2, 2, CV_64F); CvMat bad_distCoeffs_c2 = bad_distCoeffs_cpp2; - Mat bad_distCoeffs_cpp3(1, 6, CV_64F); CvMat bad_distCoeffs_c3 = bad_distCoeffs_cpp3; - - - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c1; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs header", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c2; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs header", bad_caller ); - - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c3; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs header", bad_caller ); - - double CM[] = {0, 0, 0, /**/0, 0, 0, /**/0, 0, 0}; - Mat bad_cameraMatrix_cpp4(3, 3, CV_64F, CM); CvMat bad_cameraMatrix_c4 = bad_cameraMatrix_cpp4; - - bad_caller = caller; - bad_caller.flags |= CV_CALIB_USE_INTRINSIC_GUESS; - bad_caller.cameraMatrix = &bad_cameraMatrix_c4; - CM[0] = 0; //bad fx - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 0; //bad fy - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 500; CM[2] = -1; //bad cx - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 500; CM[2] = imgSize.width*2; //bad cx - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 500; CM[2] = imgSize.width/2; CM[5] = -1; //bad cy - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 500; CM[2] = imgSize.width/2; CM[5] = imgSize.height*2; //bad cy - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[0] = 500; CM[4] = 500; CM[2] = imgSize.width/2; CM[5] = imgSize.height/2; - CM[1] = 0.1; //Non-zero skew - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[1] = 0; - CM[3] = 0.1; /* mad matrix shape */ - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[3] = 0; CM[6] = 0.1; /* mad matrix shape */ - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[3] = 0; CM[6] = 0; CM[7] = 0.1; /* mad matrix shape */ - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - - CM[3] = 0; CM[6] = 0; CM[7] = 0; CM[8] = 1.1; /* mad matrix shape */ - errors += run_test_case( CV_StsOutOfRange, "Bad camearaMatrix data", bad_caller ); - CM[8] = 1.0; - - ///////////////////////////////////////////////////////////////////////////////////// - bad_caller = caller; - Mat bad_objPts_cpp5 = objPts_cpp.clone(); CvMat bad_objPts_c5 = bad_objPts_cpp5; - bad_caller.objPts = &bad_objPts_c5; - - cv::RNG& rng = theRNG(); - for(int i = 0; i < bad_objPts_cpp5.rows; ++i) - bad_objPts_cpp5.at(0, i).z += ((float)rng - 0.5f); - - errors += run_test_case( CV_StsBadArg, "Bad objPts data", bad_caller ); - - if (errors) - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - else - ts->set_failed_test_info(CvTS::OK); - - //try { caller(); } - //catch (...) - //{ - // ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - // printf("+!"); - //} -} - -CV_CameraCalibrationBadArgTest camera_calibration_bad_arg_test; - - -class CV_Rodrigues2BadArgTest : public CvBadArgTest -{ -public: - CV_Rodrigues2BadArgTest() : CvBadArgTest("_3d-rodrigues-badarg", "cvRodrigues2") { }; - ~CV_Rodrigues2BadArgTest() {} ; -protected: - void run_func(void) {}; - - struct C_Caller - { - CvMat* src; - CvMat* dst; - CvMat* jacobian; - - void operator()() { cvRodrigues2(src, dst, jacobian); } - }; - - void run(int /* start_from */ ) - { - Mat zeros(1, sizeof(CvMat), CV_8U, Scalar(0)); - CvMat src_c, dst_c, jacobian_c; - - Mat src_cpp(3, 1, CV_32F); src_c = src_cpp; - Mat dst_cpp(3, 3, CV_32F); dst_c = dst_cpp; - Mat jacobian_cpp(3, 9, CV_32F); jacobian_c = jacobian_cpp; - - C_Caller caller, bad_caller; - caller.src = &src_c; - caller.dst = &dst_c; - caller.jacobian = &jacobian_c; - - /* try { caller(); } - catch (...) - { - printf("badasfas"); - }*/ - - /*/*//*/*/ - int errors = 0; - - bad_caller = caller; - bad_caller.src = 0; - errors += run_test_case( CV_StsNullPtr, "Src is zero pointer", bad_caller ); - - bad_caller = caller; - bad_caller.dst = 0; - errors += run_test_case( CV_StsNullPtr, "Dst is zero pointer", bad_caller ); - - Mat bad_src_cpp1(3, 1, CV_8U); CvMat bad_src_c1 = bad_src_cpp1; - Mat bad_dst_cpp1(3, 1, CV_8U); CvMat bad_dst_c1 = bad_dst_cpp1; - Mat bad_jac_cpp1(3, 1, CV_8U); CvMat bad_jac_c1 = bad_jac_cpp1; - Mat bad_jac_cpp2(3, 1, CV_32FC2); CvMat bad_jac_c2 = bad_jac_cpp2; - Mat bad_jac_cpp3(3, 1, CV_32F); CvMat bad_jac_c3 = bad_jac_cpp3; - - bad_caller = caller; - bad_caller.src = &bad_src_c1; - errors += run_test_case( CV_StsUnsupportedFormat, "Bad src formart", bad_caller ); - - bad_caller = caller; - bad_caller.dst = &bad_dst_c1; - errors += run_test_case( CV_StsUnmatchedFormats, "Bad dst formart", bad_caller ); - - bad_caller = caller; - bad_caller.jacobian = (CvMat*)zeros.ptr(); - errors += run_test_case( CV_StsBadArg, "Bad jacobian ", bad_caller ); - - bad_caller = caller; - bad_caller.jacobian = &bad_jac_c1; - errors += run_test_case( CV_StsUnmatchedFormats, "Bad jacobian format", bad_caller ); - - bad_caller = caller; - bad_caller.jacobian = &bad_jac_c2; - errors += run_test_case( CV_StsUnmatchedFormats, "Bad jacobian format", bad_caller ); - - bad_caller = caller; - bad_caller.jacobian = &bad_jac_c3; - errors += run_test_case( CV_StsBadSize, "Bad jacobian format", bad_caller ); - - Mat bad_src_cpp2(1, 1, CV_32F); CvMat bad_src_c2 = bad_src_cpp2; - - bad_caller = caller; - bad_caller.src = &bad_src_c2; - errors += run_test_case( CV_StsBadSize, "Bad src format", bad_caller ); - - Mat bad_dst_cpp2(2, 1, CV_32F); CvMat bad_dst_c2 = bad_dst_cpp2; - Mat bad_dst_cpp3(3, 2, CV_32F); CvMat bad_dst_c3 = bad_dst_cpp3; - Mat bad_dst_cpp4(3, 3, CV_32FC2); CvMat bad_dst_c4 = bad_dst_cpp4; - - bad_caller = caller; - bad_caller.dst = &bad_dst_c2; - errors += run_test_case( CV_StsBadSize, "Bad dst format", bad_caller ); - - bad_caller = caller; - bad_caller.dst = &bad_dst_c3; - errors += run_test_case( CV_StsBadSize, "Bad dst format", bad_caller ); - - bad_caller = caller; - bad_caller.dst = &bad_dst_c4; - errors += run_test_case( CV_StsBadSize, "Bad dst format", bad_caller ); - - - /********/ - src_cpp.create(3, 3, CV_32F); src_c = src_cpp; - dst_cpp.create(3, 1, CV_32F); dst_c = dst_cpp; - - - Mat bad_dst_cpp5(5, 5, CV_32F); CvMat bad_dst_c5 = bad_dst_cpp5; - - bad_caller = caller; - bad_caller.dst = &bad_dst_c5; - errors += run_test_case( CV_StsBadSize, "Bad dst format", bad_caller ); - - - if (errors) - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - else - ts->set_failed_test_info(CvTS::OK); - } -}; - -CV_Rodrigues2BadArgTest cv_rodrigues2_badarg_test; - - - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -class CV_ProjectPoints2BadArgTest : public CvBadArgTest -{ -public: - CV_ProjectPoints2BadArgTest() : CvBadArgTest("projectPoints-badarg", "cvProjectPoints2"), - camMat(3, 3), distCoeffs(1, 5) - { - Size imsSize(800, 600); - camMat << 300.f, 0.f, imsSize.width/2.f, 0, 300.f, imsSize.height/2.f, 0.f, 0.f, 1.f; - distCoeffs << 1.2f, 0.2f, 0.f, 0.f, 0.f; - }; - ~CV_ProjectPoints2BadArgTest() {} ; -protected: - void run_func(void) {}; - - Mat_ camMat; - Mat_ distCoeffs; - - struct C_Caller - { - CvMat* objectPoints; - CvMat* r_vec; - CvMat* t_vec; - CvMat* A; - CvMat* distCoeffs; - CvMat* imagePoints; - CvMat* dpdr; - CvMat* dpdt; - CvMat* dpdf; - CvMat* dpdc; - CvMat* dpdk; - double aspectRatio; - - void operator()() - { - cvProjectPoints2( objectPoints, r_vec, t_vec, A, distCoeffs, imagePoints, - dpdr, dpdt, dpdf, dpdc, dpdk, aspectRatio ); - } - }; - - void run(int /* start_from */ ) - { - CvMat zeros; - memset(&zeros, 0, sizeof(zeros)); - - C_Caller caller, bad_caller; - CvMat objectPoints_c, r_vec_c, t_vec_c, A_c, distCoeffs_c, imagePoints_c, - dpdr_c, dpdt_c, dpdf_c, dpdc_c, dpdk_c; - - const int n = 10; - - Mat imagePoints_cpp(1, n, CV_32FC2); imagePoints_c = imagePoints_cpp; - - Mat objectPoints_cpp(1, n, CV_32FC3); - randu(objectPoints_cpp, Scalar::all(1), Scalar::all(10)); - objectPoints_c = objectPoints_cpp; - - Mat t_vec_cpp(Mat::zeros(1, 3, CV_32F)); t_vec_c = t_vec_cpp; - Mat r_vec_cpp; - Rodrigues(Mat::eye(3, 3, CV_32F), r_vec_cpp); r_vec_c = r_vec_cpp; - - Mat A_cpp = camMat.clone(); A_c = A_cpp; - Mat distCoeffs_cpp = distCoeffs.clone(); distCoeffs_c = distCoeffs_cpp; - - Mat dpdr_cpp(2*n, 3, CV_32F); dpdr_c = dpdr_cpp; - Mat dpdt_cpp(2*n, 3, CV_32F); dpdt_c = dpdt_cpp; - Mat dpdf_cpp(2*n, 2, CV_32F); dpdf_c = dpdf_cpp; - Mat dpdc_cpp(2*n, 2, CV_32F); dpdc_c = dpdc_cpp; - Mat dpdk_cpp(2*n, 4, CV_32F); dpdk_c = dpdk_cpp; - - caller.aspectRatio = 1.0; - caller.objectPoints = &objectPoints_c; - caller.r_vec = &r_vec_c; - caller.t_vec = &t_vec_c; - caller.A = &A_c; - caller.distCoeffs = &distCoeffs_c; - caller.imagePoints = &imagePoints_c; - caller.dpdr = &dpdr_c; - caller.dpdt = &dpdt_c; - caller.dpdf = &dpdf_c; - caller.dpdc = &dpdc_c; - caller.dpdk = &dpdk_c; - - /********************/ - int errors = 0; - - - bad_caller = caller; - bad_caller.objectPoints = 0; - errors += run_test_case( CV_StsBadArg, "Zero objectPoints", bad_caller ); - - bad_caller = caller; - bad_caller.r_vec = 0; - errors += run_test_case( CV_StsBadArg, "Zero r_vec", bad_caller ); - - bad_caller = caller; - bad_caller.t_vec = 0; - errors += run_test_case( CV_StsBadArg, "Zero t_vec", bad_caller ); - - bad_caller = caller; - bad_caller.A = 0; - errors += run_test_case( CV_StsBadArg, "Zero camMat", bad_caller ); - - bad_caller = caller; - bad_caller.imagePoints = 0; - errors += run_test_case( CV_StsBadArg, "Zero imagePoints", bad_caller ); - - /****************************/ - Mat bad_r_vec_cpp1(r_vec_cpp.size(), CV_32S); CvMat bad_r_vec_c1 = bad_r_vec_cpp1; - Mat bad_r_vec_cpp2(2, 2, CV_32F); CvMat bad_r_vec_c2 = bad_r_vec_cpp2; - Mat bad_r_vec_cpp3(r_vec_cpp.size(), CV_32FC2); CvMat bad_r_vec_c3 = bad_r_vec_cpp3; - - bad_caller = caller; - bad_caller.r_vec = &bad_r_vec_c1; - errors += run_test_case( CV_StsBadArg, "Bad rvec format", bad_caller ); - - bad_caller = caller; - bad_caller.r_vec = &bad_r_vec_c2; - errors += run_test_case( CV_StsBadArg, "Bad rvec format", bad_caller ); - - bad_caller = caller; - bad_caller.r_vec = &bad_r_vec_c3; - errors += run_test_case( CV_StsBadArg, "Bad rvec format", bad_caller ); - - /****************************/ - Mat bad_t_vec_cpp1(t_vec_cpp.size(), CV_32S); CvMat bad_t_vec_c1 = bad_t_vec_cpp1; - Mat bad_t_vec_cpp2(2, 2, CV_32F); CvMat bad_t_vec_c2 = bad_t_vec_cpp2; - Mat bad_t_vec_cpp3(1, 1, CV_32FC2); CvMat bad_t_vec_c3 = bad_t_vec_cpp3; - - bad_caller = caller; - bad_caller.t_vec = &bad_t_vec_c1; - errors += run_test_case( CV_StsBadArg, "Bad tvec format", bad_caller ); - - bad_caller = caller; - bad_caller.t_vec = &bad_t_vec_c2; - errors += run_test_case( CV_StsBadArg, "Bad tvec format", bad_caller ); - - bad_caller = caller; - bad_caller.t_vec = &bad_t_vec_c3; - errors += run_test_case( CV_StsBadArg, "Bad tvec format", bad_caller ); - - /****************************/ - Mat bad_A_cpp1(A_cpp.size(), CV_32S); CvMat bad_A_c1 = bad_A_cpp1; - Mat bad_A_cpp2(2, 2, CV_32F); CvMat bad_A_c2 = bad_A_cpp2; - - bad_caller = caller; - bad_caller.A = &bad_A_c1; - errors += run_test_case( CV_StsBadArg, "Bad A format", bad_caller ); - - bad_caller = caller; - bad_caller.A = &bad_A_c2; - errors += run_test_case( CV_StsBadArg, "Bad A format", bad_caller ); - - /****************************/ - Mat bad_distCoeffs_cpp1(distCoeffs_cpp.size(), CV_32S); CvMat bad_distCoeffs_c1 = bad_distCoeffs_cpp1; - Mat bad_distCoeffs_cpp2(2, 2, CV_32F); CvMat bad_distCoeffs_c2 = bad_distCoeffs_cpp2; - Mat bad_distCoeffs_cpp3(1, 7, CV_32F); CvMat bad_distCoeffs_c3 = bad_distCoeffs_cpp3; - - bad_caller = caller; - bad_caller.distCoeffs = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs format", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c1; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs format", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c2; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs format", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = &bad_distCoeffs_c3; - errors += run_test_case( CV_StsBadArg, "Bad distCoeffs format", bad_caller ); - - - /****************************/ - Mat bad_dpdr_cpp1(dpdr_cpp.size(), CV_32S); CvMat bad_dpdr_c1 = bad_dpdr_cpp1; - Mat bad_dpdr_cpp2(dpdr_cpp.cols+1, 3, CV_32F); CvMat bad_dpdr_c2 = bad_dpdr_cpp2; - Mat bad_dpdr_cpp3(dpdr_cpp.cols, 7, CV_32F); CvMat bad_dpdr_c3 = bad_dpdr_cpp3; - - bad_caller = caller; - bad_caller.dpdr = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad dpdr format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdr = &bad_dpdr_c1; - errors += run_test_case( CV_StsBadArg, "Bad dpdr format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdr = &bad_dpdr_c2; - errors += run_test_case( CV_StsBadArg, "Bad dpdr format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdr = &bad_dpdr_c3; - errors += run_test_case( CV_StsBadArg, "Bad dpdr format", bad_caller ); - - /****************************/ - - bad_caller = caller; - bad_caller.dpdt = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad dpdt format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdt = &bad_dpdr_c1; - errors += run_test_case( CV_StsBadArg, "Bad dpdt format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdt = &bad_dpdr_c2; - errors += run_test_case( CV_StsBadArg, "Bad dpdt format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdt = &bad_dpdr_c3; - errors += run_test_case( CV_StsBadArg, "Bad dpdt format", bad_caller ); - - /****************************/ - - Mat bad_dpdf_cpp2(dpdr_cpp.cols+1, 2, CV_32F); CvMat bad_dpdf_c2 = bad_dpdf_cpp2; - - bad_caller = caller; - bad_caller.dpdf = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad dpdf format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdf = &bad_dpdr_c1; - errors += run_test_case( CV_StsBadArg, "Bad dpdf format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdf = &bad_dpdf_c2; - errors += run_test_case( CV_StsBadArg, "Bad dpdf format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdf = &bad_dpdr_c3; - errors += run_test_case( CV_StsBadArg, "Bad dpdf format", bad_caller ); - - /****************************/ - - bad_caller = caller; - bad_caller.dpdc = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad dpdc format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdc = &bad_dpdr_c1; - errors += run_test_case( CV_StsBadArg, "Bad dpdc format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdc = &bad_dpdf_c2; - errors += run_test_case( CV_StsBadArg, "Bad dpdc format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdc = &bad_dpdr_c3; - errors += run_test_case( CV_StsBadArg, "Bad dpdc format", bad_caller ); - - /****************************/ - - bad_caller = caller; - bad_caller.dpdk = &zeros; - errors += run_test_case( CV_StsBadArg, "Bad dpdk format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdk = &bad_dpdr_c1; - errors += run_test_case( CV_StsBadArg, "Bad dpdk format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdk = &bad_dpdf_c2; - errors += run_test_case( CV_StsBadArg, "Bad dpdk format", bad_caller ); - - bad_caller = caller; - bad_caller.dpdk = &bad_dpdr_c3; - errors += run_test_case( CV_StsBadArg, "Bad dpdk format", bad_caller ); - - bad_caller = caller; - bad_caller.distCoeffs = 0; - errors += run_test_case( CV_StsNullPtr, "distCoeffs is NULL while dpdk is not", bad_caller ); - - - if (errors) - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - else - ts->set_failed_test_info(CvTS::OK); - } -}; - -CV_ProjectPoints2BadArgTest projectPoints2_badarg_test; - - diff --git a/tests/cv/src/bchesscorners.cpp b/tests/cv/src/bchesscorners.cpp deleted file mode 100644 index 283f9ed..0000000 --- a/tests/cv/src/bchesscorners.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include "cvchessboardgenerator.h" - -#include - -using namespace std; -using namespace cv; - -class CV_ChessboardDetectorBadArgTest : public CvBadArgTest -{ -public: - CV_ChessboardDetectorBadArgTest(); -protected: - void run(int); - bool checkByGenerator(); - - bool cpp; - - /* cpp interface */ - Mat img; - Size pattern_size; - int flags; - vector corners; - - /* c interface */ - CvMat arr; - CvPoint2D32f* out_corners; - int* out_corner_count; - - - /* c interface draw corners */ - bool drawCorners; - CvMat drawCorImg; - bool was_found; - - void run_func() - { - if (cpp) - findChessboardCorners(img, pattern_size, corners, flags); - else - if (!drawCorners) - cvFindChessboardCorners( &arr, pattern_size, out_corners, out_corner_count, flags ); - else - cvDrawChessboardCorners( &drawCorImg, pattern_size, - (CvPoint2D32f*)&corners[0], (int)corners.size(), was_found); - } -}; - -CV_ChessboardDetectorBadArgTest::CV_ChessboardDetectorBadArgTest(): - CvBadArgTest( "chessboard-detector-badarg", "cvFindChessboardCorners" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -/* ///////////////////// chess_corner_test ///////////////////////// */ -void CV_ChessboardDetectorBadArgTest::run( int /*start_from */) -{ - Mat bg(800, 600, CV_8U, Scalar(0)); - Mat_ camMat(3, 3); - camMat << 300.f, 0.f, bg.cols/2.f, 0, 300.f, bg.rows/2.f, 0.f, 0.f, 1.f; - Mat_ distCoeffs(1, 5); - distCoeffs << 1.2f, 0.2f, 0.f, 0.f, 0.f; - - ChessBoardGenerator cbg(Size(8,6)); - vector exp_corn; - Mat cb = cbg(bg, camMat, distCoeffs, exp_corn); - - /* /*//*/ */ - int errors = 0; - flags = CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE; - cpp = true; - - img = cb.clone(); - pattern_size = Size(2,2); - errors += run_test_case( CV_StsOutOfRange, "Invlid pattern size" ); - - pattern_size = cbg.cornersSize(); - cb.convertTo(img, CV_32F); - errors += run_test_case( CV_StsUnsupportedFormat, "Not 8-bit image" ); - - cv::merge(vector(2, cb), img); - errors += run_test_case( CV_StsUnsupportedFormat, "2 channel image" ); - - cpp = false; - drawCorners = false; - - img = cb.clone(); - arr = img; - out_corner_count = 0; - out_corners = 0; - errors += run_test_case( CV_StsNullPtr, "Null pointer to corners" ); - - drawCorners = true; - Mat cvdrawCornImg(img.size(), CV_8UC2); - drawCorImg = cvdrawCornImg; - was_found = true; - errors += run_test_case( CV_StsUnsupportedFormat, "2 channel image" ); - - - if (errors) - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - else - ts->set_failed_test_info(CvTS::OK); -} - -CV_ChessboardDetectorBadArgTest chessboard_detector_arg_test; - -/* End of file. */ diff --git a/tests/cv/src/bundistort.cpp b/tests/cv/src/bundistort.cpp deleted file mode 100644 index 4439b44..0000000 --- a/tests/cv/src/bundistort.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ -#include "cvtest.h" - -class CV_UndistortPointsBadArgTest : public CvBadArgTest -{ -public: - CV_UndistortPointsBadArgTest(); -protected: - void run(int); - void run_func(); - -private: - //common - cv::Size img_size; - bool useCPlus; - //static const int N_POINTS = 1; - static const int N_POINTS2 = 2; - - //C - CvMat* _camera_mat; - CvMat* matR; - CvMat* matP; - CvMat* _distortion_coeffs; - CvMat* _src_points; - CvMat* _dst_points; - - - //C++ - cv::Mat camera_mat; - cv::Mat R; - cv::Mat P; - cv::Mat distortion_coeffs; - cv::Mat src_points; - std::vector dst_points; - -}; - -CV_UndistortPointsBadArgTest::CV_UndistortPointsBadArgTest (): - CvBadArgTest( "undistort-points-badarg", "cvUndistortPoints" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_UndistortPointsBadArgTest::run_func() -{ - if (useCPlus) - { - cv::undistortPoints(src_points,dst_points,camera_mat,distortion_coeffs,R,P); - } - else - { - cvUndistortPoints(_src_points,_dst_points,_camera_mat,_distortion_coeffs,matR,matP); - } -} - -void CV_UndistortPointsBadArgTest::run(int) -{ - //CvRNG* rng = ts->get_rng(); - int errcount = 0; - useCPlus = false; -//initializing - img_size.width = 800; - img_size.height = 600; - double cam[9] = {150.f, 0.f, img_size.width/2.f, 0, 300.f, img_size.height/2.f, 0.f, 0.f, 1.f}; - double dist[4] = {0.01,0.02,0.001,0.0005}; - double s_points[N_POINTS2] = {img_size.width/4,img_size.height/4}; - double d_points[N_POINTS2]; - double p[9] = {155.f, 0.f, img_size.width/2.f+img_size.width/50.f, 0, 310.f, img_size.height/2.f+img_size.height/50.f, 0.f, 0.f, 1.f}; - double r[9] = {1,0,0,0,1,0,0,0,1}; - - CvMat _camera_mat_orig = cvMat(3,3,CV_64F,cam); - CvMat _distortion_coeffs_orig = cvMat(1,4,CV_64F,dist); - CvMat _P_orig = cvMat(3,3,CV_64F,p); - CvMat _R_orig = cvMat(3,3,CV_64F,r); - CvMat _src_points_orig = cvMat(1,4,CV_64FC2,s_points); - CvMat _dst_points_orig = cvMat(1,4,CV_64FC2,d_points); - - _camera_mat = &_camera_mat_orig; - _distortion_coeffs = &_distortion_coeffs_orig; - matP = &_P_orig; - matR = &_R_orig; - _src_points = &_src_points_orig; - _dst_points = &_dst_points_orig; - -//tests - CvMat* temp1; - CvMat* temp; - IplImage* temp_img = cvCreateImage(cvSize(img_size.width,img_size.height),8,3); - -//----------- - temp = (CvMat*)temp_img; - _src_points = temp; - errcount += run_test_case( CV_StsAssert, "Input data is not CvMat*" ); - _src_points = &_src_points_orig; - - temp = (CvMat*)temp_img; - _dst_points = temp; - errcount += run_test_case( CV_StsAssert, "Output data is not CvMat*" ); - _dst_points = &_dst_points_orig; - - temp = cvCreateMat(2,3,CV_64F); - _src_points = temp; - errcount += run_test_case( CV_StsAssert, "Invalid input data matrix size" ); - _src_points = &_src_points_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(2,3,CV_64F); - _dst_points = temp; - errcount += run_test_case(CV_StsAssert, "Invalid output data matrix size" ); - _dst_points = &_dst_points_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(1,3,CV_64F); - temp1 = cvCreateMat(4,1,CV_64F); - _dst_points = temp; - _src_points = temp1; - errcount += run_test_case(CV_StsAssert, "Output and input data sizes mismatch" ); - _dst_points = &_dst_points_orig; - _src_points = &_src_points_orig; - cvReleaseMat(&temp); - cvReleaseMat(&temp1); - - temp = cvCreateMat(1,3,CV_32S); - _dst_points = temp; - errcount += run_test_case(CV_StsAssert, "Invalid output data matrix type" ); - _dst_points = &_dst_points_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(1,3,CV_32S); - _src_points = temp; - errcount += run_test_case(CV_StsAssert, "Invalid input data matrix type" ); - _src_points = &_src_points_orig; - cvReleaseMat(&temp); -//------------ - temp = cvCreateMat(2,3,CV_64F); - _camera_mat = temp; - errcount += run_test_case( CV_StsAssert, "Invalid camera data matrix size" ); - _camera_mat = &_camera_mat_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(3,4,CV_64F); - _camera_mat = temp; - errcount += run_test_case( CV_StsAssert, "Invalid camera data matrix size" ); - _camera_mat = &_camera_mat_orig; - cvReleaseMat(&temp); - - temp = (CvMat*)temp_img; - _camera_mat = temp; - errcount += run_test_case( CV_StsAssert, "Camera data is not CvMat*" ); - _camera_mat = &_camera_mat_orig; -//---------- - - temp = (CvMat*)temp_img; - _distortion_coeffs = temp; - errcount += run_test_case( CV_StsAssert, "Distortion coefficients data is not CvMat*" ); - _distortion_coeffs = &_distortion_coeffs_orig; - - temp = cvCreateMat(1,6,CV_64F); - _distortion_coeffs = temp; - errcount += run_test_case( CV_StsAssert, "Invalid distortion coefficients data matrix size" ); - _distortion_coeffs = &_distortion_coeffs_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(3,3,CV_64F); - _distortion_coeffs = temp; - errcount += run_test_case( CV_StsAssert, "Invalid distortion coefficients data matrix size" ); - _distortion_coeffs = &_distortion_coeffs_orig; - cvReleaseMat(&temp); -//---------- - temp = (CvMat*)temp_img; - matR = temp; - errcount += run_test_case( CV_StsAssert, "R data is not CvMat*" ); - matR = &_R_orig; - - temp = cvCreateMat(4,3,CV_64F); - matR = temp; - errcount += run_test_case( CV_StsAssert, "Invalid R data matrix size" ); - matR = &_R_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(3,2,CV_64F); - matR = temp; - errcount += run_test_case( CV_StsAssert, "Invalid R data matrix size" ); - matR = &_R_orig; - cvReleaseMat(&temp); - -//----------- - temp = (CvMat*)temp_img; - matP = temp; - errcount += run_test_case( CV_StsAssert, "P data is not CvMat*" ); - matP = &_P_orig; - - temp = cvCreateMat(4,3,CV_64F); - matP = temp; - errcount += run_test_case( CV_StsAssert, "Invalid P data matrix size" ); - matP = &_P_orig; - cvReleaseMat(&temp); - - temp = cvCreateMat(3,2,CV_64F); - matP = temp; - errcount += run_test_case( CV_StsAssert, "Invalid P data matrix size" ); - matP = &_P_orig; - cvReleaseMat(&temp); -//------------ - //C++ tests - useCPlus = true; - - camera_mat = cv::Mat(&_camera_mat_orig); - distortion_coeffs = cv::Mat(&_distortion_coeffs_orig); - P = cv::Mat(&_P_orig); - R = cv::Mat(&_R_orig); - src_points = cv::Mat(&_src_points_orig); - - temp = cvCreateMat(2,2,CV_32FC2); - src_points = cv::Mat(temp); - errcount += run_test_case( CV_StsAssert, "Invalid input data matrix size" ); - src_points = cv::Mat(&_src_points_orig); - cvReleaseMat(&temp); - - temp = cvCreateMat(1,4,CV_64FC2); - src_points = cv::Mat(temp); - errcount += run_test_case( CV_StsAssert, "Invalid input data matrix type" ); - src_points = cv::Mat(&_src_points_orig); - cvReleaseMat(&temp); - - src_points = cv::Mat(); - errcount += run_test_case( CV_StsAssert, "Input data matrix is not continuous" ); - src_points = cv::Mat(&_src_points_orig); - cvReleaseMat(&temp); - - - -//------------ - cvReleaseImage(&temp_img); - ts->set_failed_test_info(errcount > 0 ? CvTS::FAIL_BAD_ARG_CHECK : CvTS::OK); -} - -CV_UndistortPointsBadArgTest default_new_camera_matrix_badarg_test; -//========= -class CV_InitUndistortRectifyMapBadArgTest : public CvBadArgTest -{ -public: - CV_InitUndistortRectifyMapBadArgTest(); -protected: - void run(int); - void run_func(); - -private: - //common - cv::Size img_size; - bool useCPlus; - - //C - CvMat* _camera_mat; - CvMat* matR; - CvMat* _new_camera_mat; - CvMat* _distortion_coeffs; - CvMat* _mapx; - CvMat* _mapy; - - - //C++ - cv::Mat camera_mat; - cv::Mat R; - cv::Mat new_camera_mat; - cv::Mat distortion_coeffs; - cv::Mat mapx; - cv::Mat mapy; - int mat_type; - -}; - -CV_InitUndistortRectifyMapBadArgTest::CV_InitUndistortRectifyMapBadArgTest (): - CvBadArgTest( "undistort-undistort_rectify_map-badarg","cvInitUndistortRectifyMap" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_InitUndistortRectifyMapBadArgTest::run_func() -{ - if (useCPlus) - { - cv::initUndistortRectifyMap(camera_mat,distortion_coeffs,R,new_camera_mat,img_size,mat_type,mapx,mapy); - } - else - { - cvInitUndistortRectifyMap(_camera_mat,_distortion_coeffs,matR,_new_camera_mat,_mapx,_mapy); - } -} - -void CV_InitUndistortRectifyMapBadArgTest::run(int) -{ - int errcount = 0; -//initializing - img_size.width = 800; - img_size.height = 600; - double cam[9] = {150.f, 0.f, img_size.width/2.f, 0, 300.f, img_size.height/2.f, 0.f, 0.f, 1.f}; - double dist[4] = {0.01,0.02,0.001,0.0005}; - float* arr_mapx = new float[img_size.width*img_size.height]; - float* arr_mapy = new float[img_size.width*img_size.height]; - double arr_new_camera_mat[9] = {155.f, 0.f, img_size.width/2.f+img_size.width/50.f, 0, 310.f, img_size.height/2.f+img_size.height/50.f, 0.f, 0.f, 1.f}; - double r[9] = {1,0,0,0,1,0,0,0,1}; - - CvMat _camera_mat_orig = cvMat(3,3,CV_64F,cam); - CvMat _distortion_coeffs_orig = cvMat(1,4,CV_64F,dist); - CvMat _new_camera_mat_orig = cvMat(3,3,CV_64F,arr_new_camera_mat); - CvMat _R_orig = cvMat(3,3,CV_64F,r); - CvMat _mapx_orig = cvMat(img_size.height,img_size.width,CV_32FC1,arr_mapx); - CvMat _mapy_orig = cvMat(img_size.height,img_size.width,CV_32FC1,arr_mapy); - int mat_type_orig = CV_32FC1; - - _camera_mat = &_camera_mat_orig; - _distortion_coeffs = &_distortion_coeffs_orig; - _new_camera_mat = &_new_camera_mat_orig; - matR = &_R_orig; - _mapx = &_mapx_orig; - _mapy = &_mapy_orig; - mat_type = mat_type_orig; - -//tests - useCPlus = true; - CvMat* temp; - - //C++ tests - useCPlus = true; - - camera_mat = cv::Mat(&_camera_mat_orig); - distortion_coeffs = cv::Mat(&_distortion_coeffs_orig); - new_camera_mat = cv::Mat(&_new_camera_mat_orig); - R = cv::Mat(&_R_orig); - mapx = cv::Mat(&_mapx_orig); - mapy = cv::Mat(&_mapy_orig); - - - mat_type = CV_64F; - errcount += run_test_case( CV_StsAssert, "Invalid map matrix type" ); - mat_type = mat_type_orig; - - temp = cvCreateMat(3,2,CV_32FC1); - camera_mat = cv::Mat(temp); - errcount += run_test_case( CV_StsAssert, "Invalid camera data matrix size" ); - camera_mat = cv::Mat(&_camera_mat_orig); - cvReleaseMat(&temp); - - temp = cvCreateMat(4,3,CV_32FC1); - R = cv::Mat(temp); - errcount += run_test_case( CV_StsAssert, "Invalid R data matrix size" ); - R = cv::Mat(&_R_orig); - cvReleaseMat(&temp); - - temp = cvCreateMat(6,1,CV_32FC1); - distortion_coeffs = cv::Mat(temp); - errcount += run_test_case( CV_StsAssert, "Invalid distortion coefficients data matrix size" ); - distortion_coeffs = cv::Mat(&_distortion_coeffs_orig); - cvReleaseMat(&temp); - -//------------ - delete[] arr_mapx; - delete[] arr_mapy; - ts->set_failed_test_info(errcount > 0 ? CvTS::FAIL_BAD_ARG_CHECK : CvTS::OK); -} - -CV_InitUndistortRectifyMapBadArgTest init_undistort_rectify_map_badarg_test; - -//========= -class CV_UndistortBadArgTest : public CvBadArgTest -{ -public: - CV_UndistortBadArgTest(); -protected: - void run(int); - void run_func(); - -private: - //common - cv::Size img_size; - bool useCPlus; - - //C - CvMat* _camera_mat; - CvMat* _new_camera_mat; - CvMat* _distortion_coeffs; - CvMat* _src; - CvMat* _dst; - - - //C++ - cv::Mat camera_mat; - cv::Mat new_camera_mat; - cv::Mat distortion_coeffs; - cv::Mat src; - cv::Mat dst; - -}; - -CV_UndistortBadArgTest::CV_UndistortBadArgTest (): - CvBadArgTest( "undistort-badarg","cvUndistort2" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -void CV_UndistortBadArgTest::run_func() -{ - if (useCPlus) - { - cv::undistort(src,dst,camera_mat,distortion_coeffs,new_camera_mat); - } - else - { - cvUndistort2(_src,_dst,_camera_mat,_distortion_coeffs,_new_camera_mat); - } -} - -void CV_UndistortBadArgTest::run(int) -{ - int errcount = 0; -//initializing - img_size.width = 800; - img_size.height = 600; - double cam[9] = {150.f, 0.f, img_size.width/2.f, 0, 300.f, img_size.height/2.f, 0.f, 0.f, 1.f}; - double dist[4] = {0.01,0.02,0.001,0.0005}; - float* arr_src = new float[img_size.width*img_size.height]; - float* arr_dst = new float[img_size.width*img_size.height]; - double arr_new_camera_mat[9] = {155.f, 0.f, img_size.width/2.f+img_size.width/50.f, 0, 310.f, img_size.height/2.f+img_size.height/50.f, 0.f, 0.f, 1.f}; - - CvMat _camera_mat_orig = cvMat(3,3,CV_64F,cam); - CvMat _distortion_coeffs_orig = cvMat(1,4,CV_64F,dist); - CvMat _new_camera_mat_orig = cvMat(3,3,CV_64F,arr_new_camera_mat); - CvMat _src_orig = cvMat(img_size.height,img_size.width,CV_32FC1,arr_src); - CvMat _dst_orig = cvMat(img_size.height,img_size.width,CV_32FC1,arr_dst); - - _camera_mat = &_camera_mat_orig; - _distortion_coeffs = &_distortion_coeffs_orig; - _new_camera_mat = &_new_camera_mat_orig; - _src = &_src_orig; - _dst = &_dst_orig; - -//tests - useCPlus = true; - CvMat* temp; - CvMat* temp1; - -//C tests - useCPlus = false; - - temp = cvCreateMat(800,600,CV_32F); - temp1 = cvCreateMat(800,601,CV_32F); - _src = temp; - _dst = temp1; - errcount += run_test_case( CV_StsAssert, "Input and output data matrix sizes mismatch" ); - _src = &_src_orig; - _dst = &_dst_orig; - cvReleaseMat(&temp); - cvReleaseMat(&temp1); - - temp = cvCreateMat(800,600,CV_32F); - temp1 = cvCreateMat(800,600,CV_64F); - _src = temp; - _dst = temp1; - errcount += run_test_case( CV_StsAssert, "Input and output data matrix types mismatch" ); - _src = &_src_orig; - _dst = &_dst_orig; - cvReleaseMat(&temp); - cvReleaseMat(&temp1); - - //C++ tests - useCPlus = true; - - camera_mat = cv::Mat(&_camera_mat_orig); - distortion_coeffs = cv::Mat(&_distortion_coeffs_orig); - new_camera_mat = cv::Mat(&_new_camera_mat_orig); - src = cv::Mat(&_src_orig); - dst = cv::Mat(&_dst_orig); - -//------------ - delete[] arr_src; - delete[] arr_dst; - ts->set_failed_test_info(errcount > 0 ? CvTS::FAIL_BAD_ARG_CHECK : CvTS::OK); -} - -CV_UndistortBadArgTest undistort_badarg_test; - -/* End of file. */ diff --git a/tests/cv/src/cvchessboardgenerator.cpp b/tests/cv/src/cvchessboardgenerator.cpp deleted file mode 100644 index f26cf8f..0000000 --- a/tests/cv/src/cvchessboardgenerator.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// - // - // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. - // - // By downloading, copying, installing or using the software you agree to this license. - // If you do not agree to this license, do not download, install, - // copy or use the software. - // - // - // License Agreement - // For Open Source Computer Vision Library - // - // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. - // Copyright (C) 2009, Willow Garage Inc., all rights reserved. - // Third party copyrights are property of their respective owners. - // - // Redistribution and use in source and binary forms, with or without modification, - // are permitted provided that the following conditions are met: - // - // * Redistribution's of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistribution's in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * The name of the copyright holders may not be used to endorse or promote products - // derived from this software without specific prior written permission. - // - // This software is provided by the copyright holders and contributors "as is" and - // any express or implied warranties, including, but not limited to, the implied - // warranties of merchantability and fitness for a particular purpose are disclaimed. - // In no event shall the Intel Corporation or contributors be liable for any direct, - // indirect, incidental, special, exemplary, or consequential damages - // (including, but not limited to, procurement of substitute goods or services; - // loss of use, data, or profits; or business interruption) however caused - // and on any theory of liability, whether in contract, strict liability, - // or tort (including negligence or otherwise) arising in any way out of - // the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include "cvchessboardgenerator.h" - -#include -#include -#include - -using namespace cv; -using namespace std; - -ChessBoardGenerator::ChessBoardGenerator(const Size& _patternSize) : sensorWidth(32), sensorHeight(24), - squareEdgePointsNum(200), min_cos(sqrt(2.f)*0.5f), cov(0.5), - patternSize(_patternSize), rendererResolutionMultiplier(4), tvec(Mat::zeros(1, 3, CV_32F)) -{ - Rodrigues(Mat::eye(3, 3, CV_32F), rvec); -} - -void cv::ChessBoardGenerator::generateEdge(const Point3f& p1, const Point3f& p2, vector& out) const -{ - Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum); - for(size_t n = 0; n < squareEdgePointsNum; ++n) - out.push_back( p1 + step * (float)n); -} - -Size cv::ChessBoardGenerator::cornersSize() const -{ - return Size(patternSize.width-1, patternSize.height-1); -} - -struct Mult -{ - float m; - Mult(int mult) : m((float)mult) {} - Point2f operator()(const Point2f& p)const { return p * m; } -}; - -void cv::ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const -{ - RNG& rng = theRNG(); - - Vec3f n; - for(;;) - { - n[0] = rng.uniform(-1.f, 1.f); - n[1] = rng.uniform(-1.f, 1.f); - n[2] = rng.uniform(-1.f, 1.f); - float len = (float)norm(n); - n[0]/=len; - n[1]/=len; - n[2]/=len; - - if (n[2] > min_cos) - break; - } - - Vec3f n_temp = n; n_temp[0] += 100; - Vec3f b1 = n.cross(n_temp); - Vec3f b2 = n.cross(b1); - float len_b1 = (float)norm(b1); - float len_b2 = (float)norm(b2); - - pb1 = Point3f(b1[0]/len_b1, b1[1]/len_b1, b1[2]/len_b1); - pb2 = Point3f(b2[0]/len_b1, b2[1]/len_b2, b2[2]/len_b2); -} - - -Mat cv::ChessBoardGenerator::generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, - const Point3f& zero, const Point3f& pb1, const Point3f& pb2, - float sqWidth, float sqHeight, const vector& whole, - vector& corners) const -{ - vector< vector > squares_black; - for(int i = 0; i < patternSize.width; ++i) - for(int j = 0; j < patternSize.height; ++j) - if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) ) - { - vector pts_square3d; - vector pts_square2d; - - Point3f p1 = zero + (i + 0) * sqWidth * pb1 + (j + 0) * sqHeight * pb2; - Point3f p2 = zero + (i + 1) * sqWidth * pb1 + (j + 0) * sqHeight * pb2; - Point3f p3 = zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2; - Point3f p4 = zero + (i + 0) * sqWidth * pb1 + (j + 1) * sqHeight * pb2; - generateEdge(p1, p2, pts_square3d); - generateEdge(p2, p3, pts_square3d); - generateEdge(p3, p4, pts_square3d); - generateEdge(p4, p1, pts_square3d); - - projectPoints(Mat(pts_square3d), rvec, tvec, camMat, distCoeffs, pts_square2d); - squares_black.resize(squares_black.size() + 1); - vector temp; - approxPolyDP(Mat(pts_square2d), temp, 1.0, true); - transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier)); - } - - /* calculate corners */ - corners3d.clear(); - for(int j = 0; j < patternSize.height - 1; ++j) - for(int i = 0; i < patternSize.width - 1; ++i) - corners3d.push_back(zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2); - corners.clear(); - projectPoints(Mat(corners3d), rvec, tvec, camMat, distCoeffs, corners); - - vector whole3d; - vector whole2d; - generateEdge(whole[0], whole[1], whole3d); - generateEdge(whole[1], whole[2], whole3d); - generateEdge(whole[2], whole[3], whole3d); - generateEdge(whole[3], whole[0], whole3d); - projectPoints(Mat(whole3d), rvec, tvec, camMat, distCoeffs, whole2d); - vector temp_whole2d; - approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true); - - vector< vector > whole_contour(1); - transform(temp_whole2d.begin(), temp_whole2d.end(), - back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier)); - - Mat result; - if (rendererResolutionMultiplier == 1) - { - result = bg.clone(); - drawContours(result, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA); - drawContours(result, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA); - } - else - { - Mat tmp; - resize(bg, tmp, bg.size() * rendererResolutionMultiplier); - drawContours(tmp, whole_contour, -1, Scalar::all(255), CV_FILLED, CV_AA); - drawContours(tmp, squares_black, -1, Scalar::all(0), CV_FILLED, CV_AA); - resize(tmp, result, bg.size(), 0, 0, INTER_AREA); - } - - return result; -} - -Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector& corners) const -{ - cov = min(cov, 0.8); - double fovx, fovy, focalLen; - Point2d principalPoint; - double aspect; - calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight, - fovx, fovy, focalLen, principalPoint, aspect); - - RNG& rng = theRNG(); - - float d1 = static_cast(rng.uniform(0.1, 10.0)); - float ah = static_cast(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180); - float av = static_cast(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180); - - Point3f p; - p.z = cos(ah) * d1; - p.x = sin(ah) * d1; - p.y = p.z * tan(av); - - Point3f pb1, pb2; - generateBasis(pb1, pb2); - - float cbHalfWidth = static_cast(norm(p) * sin( min(fovx, fovy) * 0.5 * CV_PI / 180)); - float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width; - - float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; - float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; - - vector pts3d(4); - vector pts2d(4); - for(;;) - { - pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - - /* can remake with better perf */ - projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); - - bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0; - bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0; - bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0; - bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0; - - if (inrect1 && inrect2 && inrect3 && inrect4) - break; - - cbHalfWidth*=0.8f; - cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width; - - cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; - cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; - } - - Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; - float sqWidth = 2 * cbHalfWidth/patternSize.width; - float sqHeight = 2 * cbHalfHeight/patternSize.height; - - return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners); -} - - -Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, - const Size2f& squareSize, vector& corners) const -{ - cov = min(cov, 0.8); - double fovx, fovy, focalLen; - Point2d principalPoint; - double aspect; - calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight, - fovx, fovy, focalLen, principalPoint, aspect); - - RNG& rng = theRNG(); - - float d1 = static_cast(rng.uniform(0.1, 10.0)); - float ah = static_cast(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180); - float av = static_cast(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180); - - Point3f p; - p.z = cos(ah) * d1; - p.x = sin(ah) * d1; - p.y = p.z * tan(av); - - Point3f pb1, pb2; - generateBasis(pb1, pb2); - - float cbHalfWidth = squareSize.width * patternSize.width * 0.5f; - float cbHalfHeight = squareSize.height * patternSize.height * 0.5f; - - float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; - float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; - - vector pts3d(4); - vector pts2d(4); - for(;;) - { - pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - - /* can remake with better perf */ - projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); - - bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0; - bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0; - bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0; - bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0; - - if ( inrect1 && inrect2 && inrect3 && inrect4) - break; - - p.z *= 1.1f; - } - - Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; - - return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, - squareSize.width, squareSize.height, pts3d, corners); -} - -Mat cv::ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, - const Size2f& squareSize, const Point3f& pos, vector& corners) const -{ - cov = min(cov, 0.8); - Point3f p = pos; - Point3f pb1, pb2; - generateBasis(pb1, pb2); - - float cbHalfWidth = squareSize.width * patternSize.width * 0.5f; - float cbHalfHeight = squareSize.height * patternSize.height * 0.5f; - - float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width; - float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height; - - vector pts3d(4); - vector pts2d(4); - - pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2; - pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2; - - /* can remake with better perf */ - projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d); - - Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2; - - return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, - squareSize.width, squareSize.height, pts3d, corners); -} - diff --git a/tests/cv/src/cvchessboardgenerator.h b/tests/cv/src/cvchessboardgenerator.h deleted file mode 100644 index 681a4d3..0000000 --- a/tests/cv/src/cvchessboardgenerator.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef CV_CHESSBOARDGENERATOR_H143KJTVYM389YTNHKFDHJ89NYVMO3VLMEJNTBGUEIYVCM203P -#define CV_CHESSBOARDGENERATOR_H143KJTVYM389YTNHKFDHJ89NYVMO3VLMEJNTBGUEIYVCM203P - -#include "cv.h" - -namespace cv -{ - -class ChessBoardGenerator -{ -public: - double sensorWidth; - double sensorHeight; - size_t squareEdgePointsNum; - double min_cos; - mutable double cov; - Size patternSize; - int rendererResolutionMultiplier; - - ChessBoardGenerator(const Size& patternSize = Size(8, 6)); - Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector& corners) const; - Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, vector& corners) const; - Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, const Point3f& pos, vector& corners) const; - Size cornersSize() const; - - mutable vector corners3d; -private: - void generateEdge(const Point3f& p1, const Point3f& p2, vector& out) const; - Mat generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, - const Point3f& zero, const Point3f& pb1, const Point3f& pb2, - float sqWidth, float sqHeight, const vector& whole, vector& corners) const; - void generateBasis(Point3f& pb1, Point3f& pb2) const; - - Mat rvec, tvec; -}; - -}; - - -#endif diff --git a/tests/cv/src/cvtest.cpp b/tests/cv/src/cvtest.cpp deleted file mode 100644 index 50b16e0..0000000 --- a/tests/cv/src/cvtest.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -/* End of file. */ diff --git a/tests/cv/src/cvtest.h b/tests/cv/src/cvtest.h deleted file mode 100644 index 2cc7b19..0000000 --- a/tests/cv/src/cvtest.h +++ /dev/null @@ -1,72 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef _CVTEST_H_ -#define _CVTEST_H_ - -#if defined _MSC_VER && _MSC_VER >= 1200 -#pragma warning( disable: 4710 4711 4514 4996 ) -#endif - -#include "cxts.h" -#include "opencv2/legacy/legacy.hpp" -#include "opencv2/legacy/compat.hpp" -#include "opencv2/contrib/contrib.hpp" -#include "opencv2/core/core_c.h" -#include "opencv2/core/internal.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/video/tracking.hpp" -#include "opencv2/features2d/features2d.hpp" -#include "opencv2/objdetect/objdetect.hpp" - -#undef min -#undef max - -void cvTsCalcSobelKernel2D( int dx, int dy, int _aperture_size, int origin, CvMat* kernel ); -int cvTsRodrigues( const CvMat* src, CvMat* dst, CvMat* jacobian=0 ); -void cvTsConvertHomogeneous( const CvMat* src, CvMat* dst ); - -#endif /* _CVTEST_H_ */ - -/* End of file. */ diff --git a/tests/cv/src/detectors_test.cpp b/tests/cv/src/detectors_test.cpp deleted file mode 100644 index e714fc8..0000000 --- a/tests/cv/src/detectors_test.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -class CV_DetectorsTest : public CvTest -{ -public: - CV_DetectorsTest(); - ~CV_DetectorsTest(); -protected: - void run(int); - template bool testDetector(const Mat& img, const T& detector, vector& expected); - - void LoadExpected(const string& file, vector& out); -}; - -CV_DetectorsTest::CV_DetectorsTest(): CvTest( "feature-detectors", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_DetectorsTest::~CV_DetectorsTest() {} - -void getRotation(const Mat& img, Mat& aff, Mat& out) -{ - Point center(img.cols/2, img.rows/2); - aff = getRotationMatrix2D(center, 30, 1); - warpAffine( img, out, aff, img.size()); -} - -void getZoom(const Mat& img, Mat& aff, Mat& out) -{ - const double mult = 1.2; - - aff.create(2, 3, CV_64F); - double *data = aff.ptr(); - data[0] = mult; data[1] = 0; data[2] = 0; - data[3] = 0; data[4] = mult; data[5] = 0; - - warpAffine( img, out, aff, img.size()); -} - -void getBlur(const Mat& img, Mat& aff, Mat& out) -{ - aff.create(2, 3, CV_64F); - double *data = aff.ptr(); - data[0] = 1; data[1] = 0; data[2] = 0; - data[3] = 0; data[4] = 1; data[5] = 0; - - GaussianBlur(img, out, Size(5, 5), 2); -} - -void getBrightness(const Mat& img, Mat& aff, Mat& out) -{ - aff.create(2, 3, CV_64F); - double *data = aff.ptr(); - data[0] = 1; data[1] = 0; data[2] = 0; - data[3] = 0; data[4] = 1; data[5] = 0; - - add(img, Mat(img.size(), img.type(), Scalar(15)), out); -} - -void showOrig(const Mat& img, const vector& orig_pts) -{ - - Mat img_color; - cvtColor(img, img_color, CV_GRAY2BGR); - - for(size_t i = 0; i < orig_pts.size(); ++i) - circle(img_color, orig_pts[i].pt, (int)orig_pts[i].size/2, CV_RGB(0, 255, 0)); - - namedWindow("O"); imshow("O", img_color); -} - -void show(const string& name, const Mat& new_img, const vector& new_pts, const vector& transf_pts) -{ - - Mat new_img_color; - cvtColor(new_img, new_img_color, CV_GRAY2BGR); - - for(size_t i = 0; i < transf_pts.size(); ++i) - circle(new_img_color, transf_pts[i].pt, (int)transf_pts[i].size/2, CV_RGB(255, 0, 0)); - - for(size_t i = 0; i < new_pts.size(); ++i) - circle(new_img_color, new_pts[i].pt, (int)new_pts[i].size/2, CV_RGB(0, 0, 255)); - - namedWindow(name + "_T"); imshow(name + "_T", new_img_color); -} - -struct WrapPoint -{ - const double* R; - WrapPoint(const Mat& rmat) : R(rmat.ptr()) { }; - - KeyPoint operator()(const KeyPoint& kp) const - { - KeyPoint res = kp; - res.pt.x = static_cast(kp.pt.x * R[0] + kp.pt.y * R[1] + R[2]); - res.pt.y = static_cast(kp.pt.x * R[3] + kp.pt.y * R[4] + R[5]); - return res; - } -}; - -struct sortByR { bool operator()(const KeyPoint& kp1, const KeyPoint& kp2) { return norm(kp1.pt) < norm(kp2.pt); } }; - -template bool CV_DetectorsTest::testDetector(const Mat& img, const T& detector, vector& exp) -{ - vector orig_kpts; - detector(img, orig_kpts); - - typedef void (*TransfFunc )(const Mat&, Mat&, Mat& FransfFunc); - const TransfFunc transfFunc[] = { getRotation, getZoom, getBlur, getBrightness }; - //const string names[] = { "Rotation", "Zoom", "Blur", "Brightness" }; - const size_t case_num = sizeof(transfFunc)/sizeof(transfFunc[0]); - - vector affs(case_num); - vector new_imgs(case_num); - - vector< vector > new_kpts(case_num); - vector< vector > transf_kpts(case_num); - - //showOrig(img, orig_kpts); - for(size_t i = 0; i < case_num; ++i) - { - transfFunc[i](img, affs[i], new_imgs[i]); - detector(new_imgs[i], new_kpts[i]); - transform(orig_kpts.begin(), orig_kpts.end(), back_inserter(transf_kpts[i]), WrapPoint(affs[i])); - //show(names[i], new_imgs[i], new_kpts[i], transf_kpts[i]); - } - - const float thres = 3; - const float nthres = 3; - - vector result; - for(size_t i = 0; i < orig_kpts.size(); ++i) - { - const KeyPoint& okp = orig_kpts[i]; - int foundCounter = 0; - for(size_t j = 0; j < case_num; ++j) - { - const KeyPoint& tkp = transf_kpts[j][i]; - - size_t k = 0; - - for(; k < new_kpts[j].size(); ++k) - if (norm(new_kpts[j][k].pt - tkp.pt) < nthres && fabs(new_kpts[j][k].size - tkp.size) < thres) - break; - - if (k != new_kpts[j].size()) - ++foundCounter; - - } - if (foundCounter == (int)case_num) - result.push_back(okp); - } - - sort(result.begin(), result.end(), sortByR()); - sort(exp.begin(), exp.end(), sortByR()); - - if (result.size() != exp.size()) - { - ts->set_failed_test_info(CvTS::FAIL_INVALID_TEST_DATA); - return false; - } - - int foundCounter1 = 0; - for(size_t i = 0; i < exp.size(); ++i) - { - const KeyPoint& e = exp[i]; - size_t j = 0; - for(; j < result.size(); ++j) - { - const KeyPoint& r = result[i]; - if (norm(r.pt-e.pt) < nthres && fabs(r.size - e.size) < thres) - break; - } - if (j != result.size()) - ++foundCounter1; - } - - int foundCounter2 = 0; - for(size_t i = 0; i < result.size(); ++i) - { - const KeyPoint& r = result[i]; - size_t j = 0; - for(; j < exp.size(); ++j) - { - const KeyPoint& e = exp[i]; - if (norm(r.pt-e.pt) < nthres && fabs(r.size - e.size) < thres) - break; - } - if (j != exp.size()) - ++foundCounter2; - } - //showOrig(img, result); waitKey(); - - const float errorRate = 0.9f; - if (float(foundCounter1)/exp.size() < errorRate || float(foundCounter2)/result.size() < errorRate) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -struct SurfNoMaskWrap -{ - const SURF& detector; - SurfNoMaskWrap(const SURF& surf) : detector(surf) {} - SurfNoMaskWrap& operator=(const SurfNoMaskWrap&); - void operator()(const Mat& img, vector& kpts) const { detector(img, Mat(), kpts); } -}; - -void CV_DetectorsTest::LoadExpected(const string& file, vector& out) -{ - Mat mat_exp; - FileStorage fs(file, FileStorage::READ); - if (fs.isOpened()) - { - read( fs["ResultVectorData"], mat_exp, Mat() ); - out.resize(mat_exp.cols / sizeof(KeyPoint)); - copy(mat_exp.ptr(), mat_exp.ptr() + out.size(), out.begin()); - } - else - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA); - out.clear(); - } -} - -void CV_DetectorsTest::run( int /*start_from*/ ) -{ - Mat img = imread(string(ts->get_data_path()) + "shared/graffiti.png", 0); - - if (img.empty()) - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - Mat to_test(img.size() * 2, img.type(), Scalar(0)); - Mat roi = to_test(Rect(img.rows/2, img.cols/2, img.cols, img.rows)); - img.copyTo(roi); - GaussianBlur(to_test, to_test, Size(3, 3), 1.5); - - vector exp; - LoadExpected(string(ts->get_data_path()) + "detectors/surf.xml", exp); - if (exp.empty()) - return; - - if (!testDetector(to_test, SurfNoMaskWrap(SURF(1536+512+512, 2)), exp)) - return; - - LoadExpected(string(ts->get_data_path()) + "detectors/star.xml", exp); - if (exp.empty()) - return; - - if (!testDetector(to_test, StarDetector(45, 30, 10, 8, 5), exp)) - return; - - ts->set_failed_test_info( CvTS::OK); -} - - -CV_DetectorsTest Detectors_test; - - - diff --git a/tests/cv/src/fast.cpp b/tests/cv/src/fast.cpp deleted file mode 100644 index bf3a656..0000000 --- a/tests/cv/src/fast.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include "cvaux.h" - -using namespace cv; - -class CV_FastTest : public CvTest -{ -public: - CV_FastTest(); - ~CV_FastTest(); -protected: - void run(int); -}; - -CV_FastTest::CV_FastTest(): CvTest( "features-fast", "cv::FAST" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_FastTest::~CV_FastTest() {} - -void CV_FastTest::run( int ) -{ - Mat image1 = imread(string(ts->get_data_path()) + "inpaint/orig.jpg"); - Mat image2 = imread(string(ts->get_data_path()) + "cameracalibration/chess9.jpg"); - string xml = string(ts->get_data_path()) + "fast/result.xml"; - - if (image1.empty() || image2.empty()) - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - Mat gray1, gray2; - cvtColor(image1, gray1, CV_BGR2GRAY); - cvtColor(image2, gray2, CV_BGR2GRAY); - - vector keypoints1; - vector keypoints2; - FAST(gray1, keypoints1, 30); - FAST(gray2, keypoints2, 30); - - for(size_t i = 0; i < keypoints1.size(); ++i) - { - const KeyPoint& kp = keypoints1[i]; - cv::circle(image1, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0)); - } - - for(size_t i = 0; i < keypoints2.size(); ++i) - { - const KeyPoint& kp = keypoints2[i]; - cv::circle(image2, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0)); - } - - Mat kps1(1, (int)(keypoints1.size() * sizeof(KeyPoint)), CV_8U, &keypoints1[0]); - Mat kps2(1, (int)(keypoints2.size() * sizeof(KeyPoint)), CV_8U, &keypoints2[0]); - - FileStorage fs(xml, FileStorage::READ); - if (!fs.isOpened()) - { - fs.open(xml, FileStorage::WRITE); - fs << "exp_kps1" << kps1; - fs << "exp_kps2" << kps2; - fs.release(); - } - - if (!fs.isOpened()) - fs.open(xml, FileStorage::READ); - - Mat exp_kps1, exp_kps2; - read( fs["exp_kps1"], exp_kps1, Mat() ); - read( fs["exp_kps2"], exp_kps2, Mat() ); - fs.release(); - - if ( 0 != norm(exp_kps1, kps1, NORM_L2) || 0 != norm(exp_kps2, kps2, NORM_L2)) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return; - } - - /* cv::namedWindow("Img1"); cv::imshow("Img1", image1); - cv::namedWindow("Img2"); cv::imshow("Img2", image2); - cv::waitKey(0);*/ - - ts->set_failed_test_info(CvTS::OK); -} - -CV_FastTest fast_test; diff --git a/tests/cv/src/grabcut.cpp b/tests/cv/src/grabcut.cpp deleted file mode 100644 index 22e33ac..0000000 --- a/tests/cv/src/grabcut.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include - -using namespace std; -using namespace cv; - -class CV_GrabcutTest : public CvTest -{ -public: - CV_GrabcutTest(); - ~CV_GrabcutTest(); -protected: - bool verify(const Mat& mask, const Mat& exp); - void run(int); -}; - -CV_GrabcutTest::CV_GrabcutTest(): CvTest( "segmentation-grabcut", "cv::grabCut" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_GrabcutTest::~CV_GrabcutTest() {} - -bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp) -{ - const float maxDiffRatio = 0.005f; - int expArea = countNonZero( exp ); - int nonIntersectArea = countNonZero( mask != exp ); - - float curRatio = (float)nonIntersectArea / (float)expArea; - ts->printf( CvTS::LOG, "nonIntersectArea/expArea = %f\n", curRatio ); - return curRatio < maxDiffRatio; -} - -void CV_GrabcutTest::run( int /* start_from */) -{ - DefaultRngAuto defRng; - - Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); - Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); - Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); - Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); - - if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || - (!exp_mask1.empty() && img.size() != exp_mask1.size()) || - (!exp_mask2.empty() && img.size() != exp_mask2.size()) ) - { - ts->set_failed_test_info(CvTS::FAIL_MISSING_TEST_DATA); - return; - } - - Rect rect(Point(24, 126), Point(483, 294)); - Mat exp_bgdModel, exp_fgdModel; - - Mat mask; - mask = Scalar(0); - Mat bgdModel, fgdModel; - grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); - grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); - - // Multiply images by 255 for more visuality of test data. - if( mask_prob.empty() ) - { - mask.copyTo( mask_prob ); - imwrite(string(ts->get_data_path()) + "grabcut/mask_prob.png", mask_prob); - } - if( exp_mask1.empty() ) - { - exp_mask1 = (mask & 1) * 255; - imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); - } - - if (!verify((mask & 1) * 255, exp_mask1)) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return; - } - - mask = mask_prob; - bgdModel.release(); - fgdModel.release(); - rect = Rect(); - grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); - grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); - - if( exp_mask2.empty() ) - { - exp_mask2 = (mask & 1) * 255; - imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); - } - - if (!verify((mask & 1) * 255, exp_mask2)) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return; - } - ts->set_failed_test_info(CvTS::OK); -} - -CV_GrabcutTest grabcut_test; diff --git a/tests/cv/src/highguitest.cpp b/tests/cv/src/highguitest.cpp deleted file mode 100644 index f4b9843..0000000 --- a/tests/cv/src/highguitest.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -//#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -#if defined WIN32 || defined _WIN32 -//#if 0 - -#else - -#define MARKERS1 - -#ifdef MARKERS - #define marker(x) cout << (x) << endl -#else - #define marker(x) -#endif - -struct TempDirHolder -{ - string temp_folder; - TempDirHolder() - { - char* p = tmpnam(0); - if(p[0] == '\\') p++; - temp_folder = string(p); - exec_cmd("mkdir " + temp_folder); - } - ~TempDirHolder() { exec_cmd("rm -rf " + temp_folder); } - static void exec_cmd(const string& cmd) { marker(cmd); int res = system( cmd.c_str() ); (void)res; } - - TempDirHolder& operator=(const TempDirHolder&); -}; - - -class CV_HighGuiTest : public CvTest -{ -public: - CV_HighGuiTest(); - ~CV_HighGuiTest(); -protected: - void run(int); - - bool ImagesTest(const string& dir, const string& tmp); - bool VideoTest(const string& dir, const string& tmp, int fourcc); - - bool GuiTest(const string& dir, const string& tmp); -}; - -CV_HighGuiTest::CV_HighGuiTest(): CvTest( "z-highgui", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_HighGuiTest::~CV_HighGuiTest() {} - -double PSNR(const Mat& m1, const Mat& m2) -{ - Mat tmp; - absdiff( m1.reshape(1), m2.reshape(1), tmp); - multiply(tmp, tmp, tmp); - - double MSE = 1.0/(tmp.cols * tmp.rows) * sum(tmp)[0]; - - return 20 * log10(255.0 / sqrt(MSE)); -} - -bool CV_HighGuiTest::ImagesTest(const string& dir, const string& tmp) -{ - int code = CvTS::OK; - Mat image = imread(dir + "shared/baboon.jpg"); - - if (image.empty()) - { - ts->set_failed_test_info(CvTS::FAIL_MISSING_TEST_DATA); - return false; - } - - const string exts[] = {"png", "bmp", "tiff", "jpg", "jp2", "ppm", "ras"}; - const size_t ext_num = sizeof(exts)/sizeof(exts[0]); - - for(size_t i = 0; i < ext_num; ++i) - { - ts->printf(CvTS::LOG, "ext=%s\n", exts[i].c_str()); - string ext = exts[i]; - string full_name = tmp + "/img." + ext; - marker(exts[i]); - - imwrite(full_name, image); - Mat loaded = imread(full_name); - if (loaded.empty()) - { - ts->printf(CvTS::LOG, "Reading failed at fmt=%s\n", ext.c_str()); - code = CvTS::FAIL_MISMATCH; - continue; - } - - const double thresDbell = 20; - double psnr = PSNR(loaded, image); - if (psnr < thresDbell) - { - ts->printf(CvTS::LOG, "Reading image from file: too big difference (=%g) with fmt=%s\n", psnr, ext.c_str()); - code = CvTS::FAIL_BAD_ACCURACY; - continue; - } - - FILE *f = fopen(full_name.c_str(), "rb"); - fseek(f, 0, SEEK_END); - size_t len = ftell(f); - vector from_file(len); - fseek(f, 0, SEEK_SET); - size_t read = fread(&from_file[0], len, sizeof(vector::value_type), f); (void)read; - fclose(f); - - - vector buf; - imencode("." + exts[i], image, buf); - - if (buf != from_file) - { - ts->printf(CvTS::LOG, "Encoding failed with fmt=%s\n", ext.c_str()); - code = CvTS::FAIL_MISMATCH; - continue; - } - - Mat buf_loaded = imdecode(Mat(buf), 1); - if (buf_loaded.empty()) - { - ts->printf(CvTS::LOG, "Decoding failed with fmt=%s\n", ext.c_str()); - code = CvTS::FAIL_MISMATCH; - continue; - } - - - psnr = PSNR(buf_loaded, image); - if (psnr < thresDbell) - { - ts->printf(CvTS::LOG, "Decoding image from memory: too small PSNR (=%gdb) with fmt=%s\n", psnr, ext.c_str()); - code = CvTS::FAIL_MISMATCH; - continue; - } - } - ts->set_failed_test_info(code); - return code == CvTS::OK; -} - -bool CV_HighGuiTest::VideoTest(const string& dir, const string& tmp, int fourcc) -{ - string src_file = dir + "shared/video_for_test.avi"; - string tmp_name = tmp + "/video.avi"; - - CvCapture* cap = cvCaptureFromFile(src_file.c_str()); - - if (!cap) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - - CvVideoWriter* writer = 0; - - int counter = 0; - for(;;) - { - IplImage* img = cvQueryFrame( cap ); - - if (!img) - break; - - if (writer == 0) - { - writer = cvCreateVideoWriter(tmp_name.c_str(), fourcc, 24, cvGetSize(img)); - if (writer == 0) - { - marker("can't craete writer"); - cvReleaseCapture( &cap ); - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - } - - cvWriteFrame(writer, img); - } - - - cvReleaseVideoWriter( &writer ); - cvReleaseCapture( &cap ); - - marker("mid++"); - - cap = cvCaptureFromFile(src_file.c_str()); - marker("mid1"); - CvCapture *saved = cvCaptureFromFile(tmp_name.c_str()); - if (!saved) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - - - const double thresDbell = 20; - - bool error = false; - counter = 0; - for(;;) - { - - IplImage* ipl = cvQueryFrame( cap ); - IplImage* ipl1 = cvQueryFrame( saved ); - - - if (!ipl || !ipl1) - break; - - Mat img(ipl); - Mat img1(ipl1); - - if (PSNR(img1, img) < thresDbell) - { - error = true; - break; - } - } - - cvReleaseCapture( &cap ); - cvReleaseCapture( &saved ); - - if (error) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - - return true; -} - - -void CV_HighGuiTest::run( int /*start_from */) -{ - TempDirHolder th; - - if (!ImagesTest(ts->get_data_path(), th.temp_folder)) - return; - -#if defined WIN32 || defined __linux__ - -#if !defined HAVE_GSTREAMER || defined HAVE_GSTREAMER_APP - if (!VideoTest(ts->get_data_path(), th.temp_folder, CV_FOURCC_DEFAULT)) - return; - - - if (!VideoTest(ts->get_data_path(), th.temp_folder, CV_FOURCC('M', 'J', 'P', 'G'))) - return; - - - if (!VideoTest(ts->get_data_path(), th.temp_folder, CV_FOURCC('M', 'P', 'G', '2'))) - return; - -#endif - //if (!VideoTest(ts->get_data_path(), th.temp_folder, CV_FOURCC('D', 'X', '5', '0'))) return; -#endif - ts->set_failed_test_info(CvTS::OK); -} -CV_HighGuiTest HighGui_test; - - -#endif - diff --git a/tests/cv/src/highguitest_guionly.cpp b/tests/cv/src/highguitest_guionly.cpp deleted file mode 100644 index 3a593fa..0000000 --- a/tests/cv/src/highguitest_guionly.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -//#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 -#define MARKERS - -#ifdef MARKERS - #define marker(x) cout << (x) << endl -#else - #define marker(x) -#endif - - -class CV_HighGuiOnlyGuiTest : public CvTest -{ -public: - CV_HighGuiOnlyGuiTest(); - ~CV_HighGuiOnlyGuiTest(); -protected: - void run(int); -}; - -CV_HighGuiOnlyGuiTest::CV_HighGuiOnlyGuiTest(): CvTest( "z-highgui-gui-only", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_HighGuiOnlyGuiTest::~CV_HighGuiOnlyGuiTest() {} - -void Foo(int /*k*/, void* /*z*/) {} - -void CV_HighGuiOnlyGuiTest::run( int /*start_from */) -{ - cout << "GUI 1" << endl; - namedWindow("Win"); - cout << "GUI 2" << endl; - Mat m(30, 30, CV_8U); - m = Scalar(128); - cout << "GUI 3" << endl; - imshow("Win", m); - cout << "GUI 4" << endl; - int value = 50; - cout << "GUI 5" << endl; - createTrackbar( "trackbar", "Win", &value, 100, Foo, &value); - cout << "GUI 6" << endl; - getTrackbarPos( "trackbar", "Win" ); - cout << "GUI 7" << endl; - waitKey(500); - cout << "GUI 8" << endl; - cvDestroyAllWindows(); - cout << "GUI 9" << endl; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_HighGuiOnlyGuiTest highGuiOnlyGui_test; - - diff --git a/tests/cv/src/inpaint.cpp b/tests/cv/src/inpaint.cpp deleted file mode 100644 index 9cd2cba..0000000 --- a/tests/cv/src/inpaint.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include - -using namespace cv; - -class CV_InpaintTest : public CvTest -{ -public: - CV_InpaintTest(); - ~CV_InpaintTest(); -protected: - void run(int); -}; - -CV_InpaintTest::CV_InpaintTest(): CvTest( "inpaint", "cvInpaint" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_InpaintTest::~CV_InpaintTest() {} - -void CV_InpaintTest::run( int ) -{ - string folder = string(ts->get_data_path()) + "inpaint/"; - Mat orig = imread(folder + "orig.jpg"); - Mat exp1 = imread(folder + "exp1.png"); - Mat exp2 = imread(folder + "exp2.png"); - Mat mask = imread(folder + "mask.png"); - - if (orig.empty() || exp1.empty() || exp2.empty() || mask.empty()) - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - Mat inv_mask; - mask.convertTo(inv_mask, CV_8UC3, -1.0, 255.0); - - Mat mask1ch; - cv::cvtColor(mask, mask1ch, CV_BGR2GRAY); - - Mat test = orig.clone(); - test.setTo(Scalar::all(255), mask1ch); - - Mat res1, res2; - inpaint( test, mask1ch, res1, 5, CV_INPAINT_NS ); - inpaint( test, mask1ch, res2, 5, CV_INPAINT_TELEA ); - - imwrite("d:/exp1.png", res1); - imwrite("d:/exp2.png", res2); - - Mat diff1, diff2; - absdiff( orig, res1, diff1 ); - absdiff( orig, res2, diff2 ); - - double n1 = norm(diff1.reshape(1), NORM_INF, inv_mask.reshape(1)); - double n2 = norm(diff2.reshape(1), NORM_INF, inv_mask.reshape(1)); - - if (n1 != 0 || n2 != 0) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH ); - return; - } - - absdiff( exp1, res1, diff1 ); - absdiff( exp2, res2, diff2 ); - - n1 = norm(diff1.reshape(1), NORM_INF, mask.reshape(1)); - n2 = norm(diff2.reshape(1), NORM_INF, mask.reshape(1)); - - const int jpeg_thres = 3; - if (n1 > jpeg_thres || n2 > jpeg_thres) - { - ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); - return; - } - - ts->set_failed_test_info(CvTS::OK); -} - -CV_InpaintTest inpaint_test; diff --git a/tests/cv/src/latentsvmdetector.cpp b/tests/cv/src/latentsvmdetector.cpp deleted file mode 100644 index b374889..0000000 --- a/tests/cv/src/latentsvmdetector.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include - -#ifdef HAVE_TBB -#include "tbb/task_scheduler_init.h" -#endif - -using namespace cv; - -const int num_detections = 3; -const float true_scores[3] = {-0.383931f, -0.825876f, -0.959934f}; -const float score_thr = 0.05f; -const CvRect true_bounding_boxes[3] = {cvRect(0, 45, 362, 452), cvRect(304, 0, 64, 80), cvRect(236, 0, 108, 59)}; - -class CV_LatentSVMDetectorTest : public CvTest -{ -public: - CV_LatentSVMDetectorTest(); - ~CV_LatentSVMDetectorTest(); -protected: - void run(int); -private: - bool isEqual(CvRect r1, CvRect r2); -}; - -CV_LatentSVMDetectorTest::CV_LatentSVMDetectorTest(): CvTest( "latentsvmdetector", "cvLatentSvmDetectObjects" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -CV_LatentSVMDetectorTest::~CV_LatentSVMDetectorTest() {} - -bool CV_LatentSVMDetectorTest::isEqual(CvRect r1, CvRect r2) -{ - return ((r1.x == r2.x) && (r1.y == r2.y) && (r1.width == r2.width) && (r1.height == r2.height)); -} - -void CV_LatentSVMDetectorTest::run( int /* start_from */) -{ - int numThreads = -1; -#ifdef HAVE_TBB - numThreads = 2; - tbb::task_scheduler_init init(tbb::task_scheduler_init::deferred); - init.initialize(numThreads); -#endif - - IplImage* image = cvLoadImage(img_path.c_str()); - if (!image) - { - ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); - return; - } - - CvLatentSvmDetector* detector = cvLoadLatentSvmDetector(model_path.c_str()); - if (!detector) - { - ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); - cvReleaseImage(&image); - return; - } - - CvMemStorage* storage = cvCreateMemStorage(0); - CvSeq* detections = 0; - detections = cvLatentSvmDetectObjects(image, detector, storage, 0.5f, numThreads); - - if (detections->total != num_detections) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH ); - } - else - { - ts->set_failed_test_info(CvTS::OK); - for (int i = 0; i < detections->total; i++) - { - CvObjectDetection detection = *(CvObjectDetection*)cvGetSeqElem( detections, i ); - CvRect bounding_box = detection.rect; - float score = detection.score; - if ((!isEqual(bounding_box, true_bounding_boxes[i])) || (fabs(score - true_scores[i]) > score_thr)) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH ); - break; - } - } - } - -#ifdef HAVE_TBB - init.terminate(); -#endif - cvReleaseMemStorage( &storage ); - cvReleaseLatentSvmDetector( &detector ); - cvReleaseImage( &image ); -} - -CV_LatentSVMDetectorTest latentsvmdetector_test; diff --git a/tests/cv/src/operations.cpp b/tests/cv/src/operations.cpp deleted file mode 100644 index b23af63..0000000 --- a/tests/cv/src/operations.cpp +++ /dev/null @@ -1,829 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - - -class CV_OperationsTest : public CvTest -{ -public: - CV_OperationsTest(); - ~CV_OperationsTest(); -protected: - void run(int); - - struct test_excep - { - test_excep(const string& _s=string("")) : s(_s) {}; - string s; - }; - - bool SomeMatFunctions(); - bool TestMat(); - bool TestTemplateMat(); - bool TestMatND(); - bool TestSparseMat(); - bool operations1(); - - void checkDiff(const Mat& m1, const Mat& m2, const string& s) { if (norm(m1, m2, NORM_INF) != 0) throw test_excep(s); } - void checkDiffF(const Mat& m1, const Mat& m2, const string& s) { if (norm(m1, m2, NORM_INF) > 1e-5) throw test_excep(s); } - -}; - -CV_OperationsTest::CV_OperationsTest(): CvTest( "operations", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_OperationsTest::~CV_OperationsTest() {} - -#define STR(a) STR2(a) -#define STR2(a) #a - -#define CHECK_DIFF(a, b) checkDiff(a, b, "(" #a ") != (" #b ") at l." STR(__LINE__)) -#define CHECK_DIFF_FLT(a, b) checkDiffF(a, b, "(" #a ") !=(eps) (" #b ") at l." STR(__LINE__)) - -#if defined _MSC_VER && _MSC_VER < 1400 -#define MSVC_OLD 1 -#else -#define MSVC_OLD 0 -#endif - -bool CV_OperationsTest::TestMat() -{ - try - { - Mat one_3x1(3, 1, CV_32F, Scalar(1.0)); - Mat shi_3x1(3, 1, CV_32F, Scalar(1.2)); - Mat shi_2x1(2, 1, CV_32F, Scalar(-1)); - Scalar shift = Scalar::all(15); - - float data[] = { sqrt(2.f)/2, -sqrt(2.f)/2, 1.f, sqrt(2.f)/2, sqrt(2.f)/2, 10.f }; - Mat rot_2x3(2, 3, CV_32F, data); - - Mat res = one_3x1 + shi_3x1 + shi_3x1 + shi_3x1; - res = Mat(Mat(2 * rot_2x3) * res - shi_2x1) + shift; - - Mat tmp, res2; - add(one_3x1, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - gemm(rot_2x3, tmp, 2, shi_2x1, -1, res2, 0); - add(res2, Mat(2, 1, CV_32F, shift), res2); - - CHECK_DIFF(res, res2); - - Mat mat4x4(4, 4, CV_32F); - randu(mat4x4, Scalar(0), Scalar(10)); - - Mat roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2))); - Mat roi2 = mat4x4(Range(1, 3), Range(1, 3)); - - CHECK_DIFF(roi1, roi2); - CHECK_DIFF(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size()))); - - Mat intMat10(3, 3, CV_32S, Scalar(10)); - Mat intMat11(3, 3, CV_32S, Scalar(11)); - Mat resMat(3, 3, CV_8U, Scalar(255)); - - CHECK_DIFF(resMat, intMat10 == intMat10); - CHECK_DIFF(resMat, intMat10 < intMat11); - CHECK_DIFF(resMat, intMat11 > intMat10); - CHECK_DIFF(resMat, intMat10 <= intMat11); - CHECK_DIFF(resMat, intMat11 >= intMat10); - CHECK_DIFF(resMat, intMat11 != intMat10); - - CHECK_DIFF(resMat, intMat10 == 10.0); - CHECK_DIFF(resMat, 10.0 == intMat10); - CHECK_DIFF(resMat, intMat10 < 11.0); - CHECK_DIFF(resMat, 11.0 > intMat10); - CHECK_DIFF(resMat, 10.0 < intMat11); - CHECK_DIFF(resMat, 11.0 >= intMat10); - CHECK_DIFF(resMat, 10.0 <= intMat11); - CHECK_DIFF(resMat, 10.0 != intMat11); - CHECK_DIFF(resMat, intMat11 != 10.0); - - Mat eye = Mat::eye(3, 3, CV_16S); - Mat maskMat4(3, 3, CV_16S, Scalar(4)); - Mat maskMat1(3, 3, CV_16S, Scalar(1)); - Mat maskMat5(3, 3, CV_16S, Scalar(5)); - Mat maskMat0(3, 3, CV_16S, Scalar(0)); - - CHECK_DIFF(maskMat0, maskMat4 & maskMat1); - CHECK_DIFF(maskMat0, Scalar(1) & maskMat4); - CHECK_DIFF(maskMat0, maskMat4 & Scalar(1)); - - Mat m; - m = maskMat4.clone(); m &= maskMat1; CHECK_DIFF(maskMat0, m); - m = maskMat4.clone(); m &= maskMat1 | maskMat1; CHECK_DIFF(maskMat0, m); - m = maskMat4.clone(); m &= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat0, m); - - m = maskMat4.clone(); m &= Scalar(1); CHECK_DIFF(maskMat0, m); - m = maskMat4.clone(); m |= maskMat1; CHECK_DIFF(maskMat5, m); - m = maskMat5.clone(); m ^= maskMat1; CHECK_DIFF(maskMat4, m); - m = maskMat4.clone(); m |= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat5, m); - m = maskMat5.clone(); m ^= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat4, m); - - m = maskMat4.clone(); m |= Scalar(1); CHECK_DIFF(maskMat5, m); - m = maskMat5.clone(); m ^= Scalar(1); CHECK_DIFF(maskMat4, m); - - - - CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & (maskMat1 | maskMat1)); - CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & maskMat1); - CHECK_DIFF(maskMat0, maskMat4 & (maskMat1 | maskMat1)); - CHECK_DIFF(maskMat0, (maskMat1 | maskMat1) & Scalar(4)); - CHECK_DIFF(maskMat0, Scalar(4) & (maskMat1 | maskMat1)); - - CHECK_DIFF(maskMat0, maskMat5 ^ (maskMat4 | maskMat1)); - CHECK_DIFF(maskMat0, (maskMat4 | maskMat1) ^ maskMat5); - CHECK_DIFF(maskMat0, (maskMat4 + maskMat1) ^ (maskMat4 + maskMat1)); - CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 | Scalar(1))); - CHECK_DIFF(maskMat1, Scalar(5) ^ maskMat4); - CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 + maskMat1)); - CHECK_DIFF(maskMat5, Scalar(5) | (maskMat4 + maskMat1)); - CHECK_DIFF(maskMat0, (maskMat4 + maskMat1) ^ Scalar(5)); - - CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ maskMat1)); - CHECK_DIFF(maskMat5, (maskMat4 ^ maskMat1) | maskMat5); - CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ Scalar(1))); - CHECK_DIFF(maskMat5, (maskMat4 | maskMat4) | Scalar(1)); - CHECK_DIFF(maskMat5, Scalar(1) | (maskMat4 | maskMat4)); - CHECK_DIFF(maskMat5, Scalar(1) | maskMat4); - CHECK_DIFF(maskMat5, (maskMat5 | maskMat5) | (maskMat4 ^ maskMat1)); - - CHECK_DIFF(maskMat1, min(maskMat1, maskMat5)); - CHECK_DIFF(maskMat1, min(Mat(maskMat1 | maskMat1), maskMat5 | maskMat5)); - CHECK_DIFF(maskMat5, max(maskMat1, maskMat5)); - CHECK_DIFF(maskMat5, max(Mat(maskMat1 | maskMat1), maskMat5 | maskMat5)); - - CHECK_DIFF(maskMat1, min(maskMat1, maskMat5 | maskMat5)); - CHECK_DIFF(maskMat1, min(maskMat1 | maskMat1, maskMat5)); - CHECK_DIFF(maskMat5, max(maskMat1 | maskMat1, maskMat5)); - CHECK_DIFF(maskMat5, max(maskMat1, maskMat5 | maskMat5)); - - CHECK_DIFF(~maskMat1, maskMat1 ^ -1); - CHECK_DIFF(~(maskMat1 | maskMat1), maskMat1 ^ -1); - - CHECK_DIFF(maskMat1, maskMat4/4.0); - - ///////////////////////////// - - CHECK_DIFF(1.0 - (maskMat5 | maskMat5), -maskMat4); - CHECK_DIFF((maskMat4 | maskMat4) * 1.0 + 1.0, maskMat5); - CHECK_DIFF(1.0 + (maskMat4 | maskMat4) * 1.0, maskMat5); - CHECK_DIFF((maskMat5 | maskMat5) * 1.0 - 1.0, maskMat4); - CHECK_DIFF(5.0 - (maskMat4 | maskMat4) * 1.0, maskMat1); - CHECK_DIFF((maskMat4 | maskMat4) * 1.0 + 0.5 + 0.5, maskMat5); - CHECK_DIFF(0.5 + ((maskMat4 | maskMat4) * 1.0 + 0.5), maskMat5); - CHECK_DIFF(((maskMat4 | maskMat4) * 1.0 + 2.0) - 1.0, maskMat5); - CHECK_DIFF(5.0 - ((maskMat1 | maskMat1) * 1.0 + 3.0), maskMat1); - CHECK_DIFF( ( (maskMat1 | maskMat1) * 2.0 + 2.0) * 1.25, maskMat5); - CHECK_DIFF( 1.25 * ( (maskMat1 | maskMat1) * 2.0 + 2.0), maskMat5); - CHECK_DIFF( -( (maskMat1 | maskMat1) * (-2.0) + 1.0), maskMat1); - CHECK_DIFF( maskMat1 * 1.0 + maskMat4 * 0.5 + 2.0, maskMat5); - CHECK_DIFF( 1.0 + (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat5); - CHECK_DIFF( (maskMat1 * 1.0 + maskMat4 * 0.5 + 2.0) - 1.0, maskMat4); - CHECK_DIFF(5.0 - (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat1); - CHECK_DIFF((maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0)*1.25, maskMat5); - CHECK_DIFF(1.25 * (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat5); - CHECK_DIFF(-(maskMat1 * 2.0 + maskMat4 * (-1) + 1.0), maskMat1); - CHECK_DIFF((maskMat1 * 1.0 + maskMat4), maskMat5); - CHECK_DIFF((maskMat4 + maskMat1 * 1.0), maskMat5); - CHECK_DIFF((maskMat1 * 3.0 + 1.0) + maskMat1, maskMat5); - CHECK_DIFF(maskMat1 + (maskMat1 * 3.0 + 1.0), maskMat5); - CHECK_DIFF(maskMat1*4.0 + (maskMat1 | maskMat1), maskMat5); - CHECK_DIFF((maskMat1 | maskMat1) + maskMat1*4.0, maskMat5); - CHECK_DIFF((maskMat1*3.0 + 1.0) + (maskMat1 | maskMat1), maskMat5); - CHECK_DIFF((maskMat1 | maskMat1) + (maskMat1*3.0 + 1.0), maskMat5); - CHECK_DIFF(maskMat1*4.0 + maskMat4*2.0, maskMat1 * 12); - CHECK_DIFF((maskMat1*3.0 + 1.0) + maskMat4*2.0, maskMat1 * 12); - CHECK_DIFF(maskMat4*2.0 + (maskMat1*3.0 + 1.0), maskMat1 * 12); - CHECK_DIFF((maskMat1*3.0 + 1.0) + (maskMat1*2.0 + 2.0), maskMat1 * 8); - - CHECK_DIFF(maskMat5*1.0 - maskMat4, maskMat1); - CHECK_DIFF(maskMat5 - maskMat1 * 4.0, maskMat1); - CHECK_DIFF((maskMat4 * 1.0 + 4.0)- maskMat4, maskMat4); - CHECK_DIFF(maskMat5 - (maskMat1 * 2.0 + 2.0), maskMat1); - CHECK_DIFF(maskMat5*1.0 - (maskMat4 | maskMat4), maskMat1); - CHECK_DIFF((maskMat5 | maskMat5) - maskMat1 * 4.0, maskMat1); - CHECK_DIFF((maskMat4 * 1.0 + 4.0)- (maskMat4 | maskMat4), maskMat4); - CHECK_DIFF((maskMat5 | maskMat5) - (maskMat1 * 2.0 + 2.0), maskMat1); - CHECK_DIFF(maskMat1*5.0 - maskMat4 * 1.0, maskMat1); - CHECK_DIFF((maskMat1*5.0 + 3.0)- maskMat4 * 1.0, maskMat4); - CHECK_DIFF(maskMat4 * 2.0 - (maskMat1*4.0 + 3.0), maskMat1); - CHECK_DIFF((maskMat1 * 2.0 + 3.0) - (maskMat1*3.0 + 1.0), maskMat1); - - CHECK_DIFF((maskMat5 - maskMat4)* 4.0, maskMat4); - CHECK_DIFF(4.0 * (maskMat5 - maskMat4), maskMat4); - - CHECK_DIFF(-((maskMat4 | maskMat4) - (maskMat5 | maskMat5)), maskMat1); - - CHECK_DIFF(4.0 * (maskMat1 | maskMat1), maskMat4); - CHECK_DIFF((maskMat4 | maskMat4)/4.0, maskMat1); - -#if !MSVC_OLD - CHECK_DIFF(2.0 * (maskMat1 * 2.0) , maskMat4); -#endif - CHECK_DIFF((maskMat4 / 2.0) / 2.0 , maskMat1); - CHECK_DIFF(-(maskMat4 - maskMat5) , maskMat1); - CHECK_DIFF(-((maskMat4 - maskMat5) * 1.0), maskMat1); - - - ///////////////////////////// - CHECK_DIFF(maskMat4 / maskMat4, maskMat1); - - ///// Element-wise multiplication - - CHECK_DIFF(maskMat4.mul(maskMat4, 0.25), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat1 * 4, 0.25), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat4) * 0.25, maskMat4); - CHECK_DIFF(0.25 * maskMat4.mul(maskMat4), maskMat4); - - ////// Element-wise division - - CHECK_DIFF(maskMat4 / maskMat4, maskMat1); - CHECK_DIFF((maskMat4 & maskMat4) / (maskMat1 * 4), maskMat1); - - CHECK_DIFF((maskMat4 & maskMat4) / maskMat4, maskMat1); - CHECK_DIFF(maskMat4 / (maskMat4 & maskMat4), maskMat1); - CHECK_DIFF((maskMat1 * 4) / maskMat4, maskMat1); - - CHECK_DIFF(maskMat4 / (maskMat1 * 4), maskMat1); - CHECK_DIFF((maskMat4 * 0.5 )/ (maskMat1 * 2), maskMat1); - - CHECK_DIFF(maskMat4 / maskMat4.mul(maskMat1), maskMat1); - CHECK_DIFF((maskMat4 & maskMat4) / maskMat4.mul(maskMat1), maskMat1); - - CHECK_DIFF(4.0 / maskMat4, maskMat1); - CHECK_DIFF(4.0 / (maskMat4 | maskMat4), maskMat1); - CHECK_DIFF(4.0 / (maskMat1 * 4.0), maskMat1); - CHECK_DIFF(4.0 / (maskMat4 / maskMat1), maskMat1); - - m = maskMat4.clone(); m/=4.0; CHECK_DIFF(m, maskMat1); - m = maskMat4.clone(); m/=maskMat4; CHECK_DIFF(m, maskMat1); - m = maskMat4.clone(); m/=(maskMat1 * 4.0); CHECK_DIFF(m, maskMat1); - m = maskMat4.clone(); m/=(maskMat4 / maskMat1); CHECK_DIFF(m, maskMat1); - - ///////////////////////////// - float matrix_data[] = { 3, 1, -4, -5, 1, 0, 0, 1.1f, 1.5f}; - Mat mt(3, 3, CV_32F, matrix_data); - Mat mi = mt.inv(); - Mat d1 = Mat::eye(3, 3, CV_32F); - Mat d2 = d1 * 2; - MatExpr mt_tr = mt.t(); - MatExpr mi_tr = mi.t(); - Mat mi2 = mi * 2; - - - CHECK_DIFF_FLT( mi2 * mt, d2 ); - CHECK_DIFF_FLT( mi * mt, d1 ); - CHECK_DIFF_FLT( mt_tr * mi_tr, d1 ); - - m = mi.clone(); m*=mt; CHECK_DIFF_FLT(m, d1); - m = mi.clone(); m*= (2 * mt - mt) ; CHECK_DIFF_FLT(m, d1); - - m = maskMat4.clone(); m+=(maskMat1 * 1.0); CHECK_DIFF(m, maskMat5); - m = maskMat5.clone(); m-=(maskMat1 * 4.0); CHECK_DIFF(m, maskMat1); - - m = maskMat1.clone(); m+=(maskMat1 * 3.0 + 1.0); CHECK_DIFF(m, maskMat5); - m = maskMat5.clone(); m-=(maskMat1 * 3.0 + 1.0); CHECK_DIFF(m, maskMat1); -#if !MSVC_OLD - m = mi.clone(); m+=(3.0 * mi * mt + d1); CHECK_DIFF_FLT(m, mi + d1 * 4); - m = mi.clone(); m-=(3.0 * mi * mt + d1); CHECK_DIFF_FLT(m, mi - d1 * 4); - m = mi.clone(); m*=(mt * 1.0); CHECK_DIFF_FLT(m, d1); - m = mi.clone(); m*=(mt * 1.0 + Mat::eye(m.size(), m.type())); CHECK_DIFF_FLT(m, d1 + mi); - m = mi.clone(); m*=mt_tr.t(); CHECK_DIFF_FLT(m, d1); - - CHECK_DIFF_FLT( (mi * 2) * mt, d2); - CHECK_DIFF_FLT( mi * (2 * mt), d2); - CHECK_DIFF_FLT( mt.t() * mi_tr, d1 ); - CHECK_DIFF_FLT( mt_tr * mi.t(), d1 ); - CHECK_DIFF_FLT( (mi * 0.4) * (mt * 5), d2); - - CHECK_DIFF_FLT( mt.t() * (mi_tr * 2), d2 ); - CHECK_DIFF_FLT( (mt_tr * 2) * mi.t(), d2 ); - - CHECK_DIFF_FLT(mt.t() * mi.t(), d1); - CHECK_DIFF_FLT( (mi * mt) * 2.0, d2); - CHECK_DIFF_FLT( 2.0 * (mi * mt), d2); - CHECK_DIFF_FLT( -(mi * mt), -d1); - - CHECK_DIFF_FLT( (mi * mt) / 2.0, d1 / 2); - - Mat mt_mul_2_plus_1; - gemm(mt, d1, 2, Mat::ones(3, 3, CV_32F), 1, mt_mul_2_plus_1); - - CHECK_DIFF( (mt * 2.0 + 1.0) * mi, mt_mul_2_plus_1 * mi); // (A*alpha + beta)*B - CHECK_DIFF( mi * (mt * 2.0 + 1.0), mi * mt_mul_2_plus_1); // A*(B*alpha + beta) - CHECK_DIFF( (mt * 2.0 + 1.0) * (mi * 2), mt_mul_2_plus_1 * mi2); // (A*alpha + beta)*(B*gamma) - CHECK_DIFF( (mi *2)* (mt * 2.0 + 1.0), mi2 * mt_mul_2_plus_1); // (A*gamma)*(B*alpha + beta) - CHECK_DIFF_FLT( (mt * 2.0 + 1.0) * mi.t(), mt_mul_2_plus_1 * mi_tr); // (A*alpha + beta)*B^t - CHECK_DIFF_FLT( mi.t() * (mt * 2.0 + 1.0), mi_tr * mt_mul_2_plus_1); // A^t*(B*alpha + beta) - - CHECK_DIFF_FLT( (mi * mt + d2)*5, d1 * 3 * 5); - CHECK_DIFF_FLT( mi * mt + d2, d1 * 3); - CHECK_DIFF_FLT( -(mi * mt) + d2, d1); - CHECK_DIFF_FLT( (mi * mt) + d1, d2); - CHECK_DIFF_FLT( d1 + (mi * mt), d2); - CHECK_DIFF_FLT( (mi * mt) - d2, -d1); - CHECK_DIFF_FLT( d2 - (mi * mt), d1); - - CHECK_DIFF_FLT( (mi * mt) + d2 * 0.5, d2); - CHECK_DIFF_FLT( d2 * 0.5 + (mi * mt), d2); - CHECK_DIFF_FLT( (mi * mt) - d1 * 2, -d1); - CHECK_DIFF_FLT( d1 * 2 - (mi * mt), d1); - - CHECK_DIFF_FLT( (mi * mt) + mi.t(), mi_tr + d1); - CHECK_DIFF_FLT( mi.t() + (mi * mt), mi_tr + d1); - CHECK_DIFF_FLT( (mi * mt) - mi.t(), d1 - mi_tr); - CHECK_DIFF_FLT( mi.t() - (mi * mt), mi_tr - d1); - - CHECK_DIFF_FLT( 2.0 *(mi * mt + d2), d1 * 6); - CHECK_DIFF_FLT( -(mi * mt + d2), d1 * -3); - - CHECK_DIFF_FLT(mt.inv() * mt, d1); - - CHECK_DIFF_FLT(mt.inv() * (2*mt - mt), d1); -#endif - } - catch (const test_excep& e) - { - ts->printf(CvTS::LOG, "%s\n", e.s.c_str()); - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -bool CV_OperationsTest::SomeMatFunctions() -{ - try - { - Mat rgba( 10, 10, CV_8UC4, Scalar(1,2,3,4) ); - Mat bgr( rgba.rows, rgba.cols, CV_8UC3 ); - Mat alpha( rgba.rows, rgba.cols, CV_8UC1 ); - Mat out[] = { bgr, alpha }; - // rgba[0] -> bgr[2], rgba[1] -> bgr[1], - // rgba[2] -> bgr[0], rgba[3] -> alpha[0] - int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; - mixChannels( &rgba, 1, out, 2, from_to, 4 ); - - Mat bgr_exp( rgba.size(), CV_8UC3, Scalar(3,2,1)); - Mat alpha_exp( rgba.size(), CV_8UC1, Scalar(4)); - - CHECK_DIFF(bgr_exp, bgr); - CHECK_DIFF(alpha_exp, alpha); - } - catch (const test_excep& e) - { - ts->printf(CvTS::LOG, "%s\n", e.s.c_str()); - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; - -} - - -bool CV_OperationsTest::TestTemplateMat() -{ - try - { - Mat_ one_3x1(3, 1, 1.0f); - Mat_ shi_3x1(3, 1, 1.2f); - Mat_ shi_2x1(2, 1, -2); - Scalar shift = Scalar::all(15); - - float data[] = { sqrt(2.f)/2, -sqrt(2.f)/2, 1.f, sqrt(2.f)/2, sqrt(2.f)/2, 10.f }; - Mat_ rot_2x3(2, 3, data); - - Mat_ res = Mat(Mat(2 * rot_2x3) * Mat(one_3x1 + shi_3x1 + shi_3x1 + shi_3x1) - shi_2x1) + shift; - Mat_ resS = rot_2x3 * one_3x1; - - Mat_ tmp, res2, resS2; - add(one_3x1, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - gemm(rot_2x3, tmp, 2, shi_2x1, -1, res2, 0); - add(res2, Mat(2, 1, CV_32F, shift), res2); - - gemm(rot_2x3, one_3x1, 1, shi_2x1, 0, resS2, 0); - CHECK_DIFF(res, res2); - CHECK_DIFF(resS, resS2); - - - Mat_ mat4x4(4, 4); - randu(mat4x4, Scalar(0), Scalar(10)); - - Mat_ roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2))); - Mat_ roi2 = mat4x4(Range(1, 3), Range(1, 3)); - - CHECK_DIFF(roi1, roi2); - CHECK_DIFF(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size()))); - - Mat_ intMat10(3, 3, 10); - Mat_ intMat11(3, 3, 11); - Mat_ resMat(3, 3, 255); - - CHECK_DIFF(resMat, intMat10 == intMat10); - CHECK_DIFF(resMat, intMat10 < intMat11); - CHECK_DIFF(resMat, intMat11 > intMat10); - CHECK_DIFF(resMat, intMat10 <= intMat11); - CHECK_DIFF(resMat, intMat11 >= intMat10); - - CHECK_DIFF(resMat, intMat10 == 10.0); - CHECK_DIFF(resMat, intMat10 < 11.0); - CHECK_DIFF(resMat, intMat11 > 10.0); - CHECK_DIFF(resMat, intMat10 <= 11.0); - CHECK_DIFF(resMat, intMat11 >= 10.0); - - Mat_ maskMat4(3, 3, 4); - Mat_ maskMat1(3, 3, 1); - Mat_ maskMat5(3, 3, 5); - Mat_ maskMat0(3, 3, (uchar)0); - - CHECK_DIFF(maskMat0, maskMat4 & maskMat1); - CHECK_DIFF(maskMat0, Scalar(1) & maskMat4); - CHECK_DIFF(maskMat0, maskMat4 & Scalar(1)); - - Mat_ m; - m = maskMat4.clone(); m&=maskMat1; CHECK_DIFF(maskMat0, m); - m = maskMat4.clone(); m&=Scalar(1); CHECK_DIFF(maskMat0, m); - - m = maskMat4.clone(); m|=maskMat1; CHECK_DIFF(maskMat5, m); - m = maskMat4.clone(); m^=maskMat1; CHECK_DIFF(maskMat5, m); - - CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & (maskMat1 | maskMat1)); - CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & maskMat1); - CHECK_DIFF(maskMat0, maskMat4 & (maskMat1 | maskMat1)); - - CHECK_DIFF(maskMat0, maskMat5 ^ (maskMat4 | maskMat1)); - CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 | Scalar(1))); - - CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ maskMat1)); - CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ Scalar(1))); - - CHECK_DIFF(~maskMat1, maskMat1 ^ 0xFF); - CHECK_DIFF(~(maskMat1 | maskMat1), maskMat1 ^ 0xFF); - - CHECK_DIFF(maskMat1 + maskMat4, maskMat5); - CHECK_DIFF(maskMat1 + Scalar(4), maskMat5); - CHECK_DIFF(Scalar(4) + maskMat1, maskMat5); - CHECK_DIFF(Scalar(4) + (maskMat1 & maskMat1), maskMat5); - - CHECK_DIFF(maskMat1 + 4.0, maskMat5); - CHECK_DIFF((maskMat1 & 0xFF) + 4.0, maskMat5); - CHECK_DIFF(4.0 + maskMat1, maskMat5); - - m = maskMat4.clone(); m+=Scalar(1); CHECK_DIFF(m, maskMat5); - m = maskMat4.clone(); m+=maskMat1; CHECK_DIFF(m, maskMat5); - m = maskMat4.clone(); m+=(maskMat1 | maskMat1); CHECK_DIFF(m, maskMat5); - - CHECK_DIFF(maskMat5 - maskMat1, maskMat4); - CHECK_DIFF(maskMat5 - Scalar(1), maskMat4); - CHECK_DIFF((maskMat5 | maskMat5) - Scalar(1), maskMat4); - CHECK_DIFF(maskMat5 - 1, maskMat4); - CHECK_DIFF((maskMat5 | maskMat5) - 1, maskMat4); - CHECK_DIFF((maskMat5 | maskMat5) - (maskMat1 | maskMat1), maskMat4); - - CHECK_DIFF(maskMat1, min(maskMat1, maskMat5)); - CHECK_DIFF(maskMat5, max(maskMat1, maskMat5)); - - m = maskMat5.clone(); m-=Scalar(1); CHECK_DIFF(m, maskMat4); - m = maskMat5.clone(); m-=maskMat1; CHECK_DIFF(m, maskMat4); - m = maskMat5.clone(); m-=(maskMat1 | maskMat1); CHECK_DIFF(m, maskMat4); - - m = maskMat4.clone(); m |= Scalar(1); CHECK_DIFF(maskMat5, m); - m = maskMat5.clone(); m ^= Scalar(1); CHECK_DIFF(maskMat4, m); - - CHECK_DIFF(maskMat1, maskMat4/4.0); - - Mat_ negf(3, 3, -3.0); - Mat_ posf = -negf; - Mat_ posf2 = posf * 2; - Mat_ negi(3, 3, -3); - - CHECK_DIFF(abs(negf), -negf); - CHECK_DIFF(abs(posf - posf2), -negf); - CHECK_DIFF(abs(negi), -(negi & negi)); - - CHECK_DIFF(5.0 - maskMat4, maskMat1); - - - CHECK_DIFF(maskMat4.mul(maskMat4, 0.25), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat1 * 4, 0.25), maskMat4); - CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4); - - - ////// Element-wise division - - CHECK_DIFF(maskMat4 / maskMat4, maskMat1); - CHECK_DIFF(4.0 / maskMat4, maskMat1); - m = maskMat4.clone(); m/=4.0; CHECK_DIFF(m, maskMat1); - - //////////////////////////////// - - typedef Mat_ TestMat_t; - - const TestMat_t cnegi = negi.clone(); - - TestMat_t::iterator beg = negi.begin(); - TestMat_t::iterator end = negi.end(); - - TestMat_t::const_iterator cbeg = cnegi.begin(); - TestMat_t::const_iterator cend = cnegi.end(); - - int sum = 0; - for(; beg!=end; ++beg) - sum+=*beg; - - for(; cbeg!=cend; ++cbeg) - sum-=*cbeg; - - if (sum != 0) throw test_excep(); - - CHECK_DIFF(negi.col(1), negi.col(2)); - CHECK_DIFF(negi.row(1), negi.row(2)); - CHECK_DIFF(negi.col(1), negi.diag()); - - if (Mat_(1, 1).elemSize1() != sizeof(float)) throw test_excep(); - if (Mat_(1, 1).elemSize() != 2 * sizeof(float)) throw test_excep(); - if (Mat_(1, 1).depth() != CV_32F) throw test_excep(); - if (Mat_(1, 1).depth() != CV_32F) throw test_excep(); - if (Mat_(1, 1).depth() != CV_32S) throw test_excep(); - if (Mat_(1, 1).depth() != CV_64F) throw test_excep(); - if (Mat_(1, 1).depth() != CV_64F) throw test_excep(); - if (Mat_(1, 1).depth() != CV_8S) throw test_excep(); - if (Mat_(1, 1).depth() != CV_16U) throw test_excep(); - if (Mat_(1, 1).channels() != 1) throw test_excep(); - if (Mat_(1, 1).channels() != 2) throw test_excep(); - if (Mat_(1, 1).channels() != 3) throw test_excep(); - if (Mat_(1, 1).channels() != 3) throw test_excep(); - - Mat_ eye = Mat_::zeros(2, 2); CHECK_DIFF(Mat_::zeros(Size(2, 2)), eye); - eye.at(Point(0,0)) = 1; eye.at(1, 1) = 1; - - CHECK_DIFF(Mat_::eye(2, 2), eye); - CHECK_DIFF(eye, Mat_::eye(Size(2,2))); - - Mat_ ones(2, 2, (uchar)1); - CHECK_DIFF(ones, Mat_::ones(Size(2,2))); - CHECK_DIFF(Mat_::ones(2, 2), ones); - - Mat_ pntMat(2, 2, Point2f(1, 0)); - if(pntMat.stepT() != 2) throw test_excep(); - - uchar uchar_data[] = {1, 0, 0, 1}; - - Mat_ matFromData(1, 4, uchar_data); - const Mat_ mat2 = matFromData.clone(); - CHECK_DIFF(matFromData, eye.reshape(1)); - if (matFromData(Point(0,0)) != uchar_data[0])throw test_excep(); - if (mat2(Point(0,0)) != uchar_data[0]) throw test_excep(); - - if (matFromData(0,0) != uchar_data[0])throw test_excep(); - if (mat2(0,0) != uchar_data[0]) throw test_excep(); - - Mat_ rect(eye, Rect(0, 0, 1, 1)); - if (rect.cols != 1 || rect.rows != 1 || rect(0,0) != uchar_data[0]) throw test_excep(); - - //cv::Mat_<_Tp>::adjustROI(int,int,int,int) - //cv::Mat_<_Tp>::cross(const Mat_&) const - //cv::Mat_<_Tp>::Mat_(const vector<_Tp>&,bool) - //cv::Mat_<_Tp>::Mat_(int,int,_Tp*,size_t) - //cv::Mat_<_Tp>::Mat_(int,int,const _Tp&) - //cv::Mat_<_Tp>::Mat_(Size,const _Tp&) - //cv::Mat_<_Tp>::mul(const Mat_<_Tp>&,double) const - //cv::Mat_<_Tp>::mul(const MatExpr_,double,Mat_<_Tp>,MatOp_DivRS_ >,Mat_<_Tp> >&,double) const - //cv::Mat_<_Tp>::mul(const MatExpr_,double,Mat_<_Tp>,MatOp_Scale_ >,Mat_<_Tp> >&,double) const - //cv::Mat_<_Tp>::operator Mat_() const - //cv::Mat_<_Tp>::operator MatExpr_,Mat_<_Tp> >() const - //cv::Mat_<_Tp>::operator()(const Range&,const Range&) const - //cv::Mat_<_Tp>::operator()(const Rect&) const - - //cv::Mat_<_Tp>::operator=(const MatExpr_Base&) - //cv::Mat_<_Tp>::operator[](int) const - - - /////////////////////////////// - - float matrix_data[] = { 3, 1, -4, -5, 1, 0, 0, 1.1f, 1.5f}; - Mat_ mt(3, 3, matrix_data); - Mat_ mi = mt.inv(); - Mat_ d1 = Mat_::eye(3, 3); - Mat_ d2 = d1 * 2; - Mat_ mt_tr = mt.t(); - Mat_ mi_tr = mi.t(); - Mat_ mi2 = mi * 2; - - CHECK_DIFF_FLT( mi2 * mt, d2 ); - CHECK_DIFF_FLT( mi * mt, d1 ); - CHECK_DIFF_FLT( mt_tr * mi_tr, d1 ); - - Mat_ mf; - mf = mi.clone(); mf*=mt; CHECK_DIFF_FLT(mf, d1); - - ////// typedefs ////// - - if (Mat1b(1, 1).elemSize() != sizeof(uchar)) throw test_excep(); - if (Mat2b(1, 1).elemSize() != 2 * sizeof(uchar)) throw test_excep(); - if (Mat3b(1, 1).elemSize() != 3 * sizeof(uchar)) throw test_excep(); - if (Mat1f(1, 1).elemSize() != sizeof(float)) throw test_excep(); - if (Mat2f(1, 1).elemSize() != 2 * sizeof(float)) throw test_excep(); - if (Mat3f(1, 1).elemSize() != 3 * sizeof(float)) throw test_excep(); - if (Mat1f(1, 1).depth() != CV_32F) throw test_excep(); - if (Mat3f(1, 1).depth() != CV_32F) throw test_excep(); - if (Mat3f(1, 1).type() != CV_32FC3) throw test_excep(); - if (Mat1i(1, 1).depth() != CV_32S) throw test_excep(); - if (Mat1d(1, 1).depth() != CV_64F) throw test_excep(); - if (Mat1b(1, 1).depth() != CV_8U) throw test_excep(); - if (Mat3b(1, 1).type() != CV_8UC3) throw test_excep(); - if (Mat1w(1, 1).depth() != CV_16U) throw test_excep(); - if (Mat1s(1, 1).depth() != CV_16S) throw test_excep(); - if (Mat1f(1, 1).channels() != 1) throw test_excep(); - if (Mat1b(1, 1).channels() != 1) throw test_excep(); - if (Mat1i(1, 1).channels() != 1) throw test_excep(); - if (Mat1w(1, 1).channels() != 1) throw test_excep(); - if (Mat1s(1, 1).channels() != 1) throw test_excep(); - if (Mat2f(1, 1).channels() != 2) throw test_excep(); - if (Mat2b(1, 1).channels() != 2) throw test_excep(); - if (Mat2i(1, 1).channels() != 2) throw test_excep(); - if (Mat2w(1, 1).channels() != 2) throw test_excep(); - if (Mat2s(1, 1).channels() != 2) throw test_excep(); - if (Mat3f(1, 1).channels() != 3) throw test_excep(); - if (Mat3b(1, 1).channels() != 3) throw test_excep(); - if (Mat3i(1, 1).channels() != 3) throw test_excep(); - if (Mat3w(1, 1).channels() != 3) throw test_excep(); - if (Mat3s(1, 1).channels() != 3) throw test_excep(); - - } - catch (const test_excep& e) - { - ts->printf(CvTS::LOG, "%s\n", e.s.c_str()); - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -bool CV_OperationsTest::TestMatND() -{ - int sizes[] = { 3, 3, 3}; - cv::MatND nd(3, sizes, CV_32F); - - return true; -} - -bool CV_OperationsTest::TestSparseMat() -{ - try - { - int sizes[] = { 10, 10, 10}; - int dims = sizeof(sizes)/sizeof(sizes[0]); - SparseMat mat(dims, sizes, CV_32FC2); - - if (mat.dims() != dims) throw test_excep(); - if (mat.channels() != 2) throw test_excep(); - if (mat.depth() != CV_32F) throw test_excep(); - - SparseMat mat2 = mat.clone(); - } - catch (const test_excep&) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -bool CV_OperationsTest::operations1() -{ - try - { - Point3d p1(1, 1, 1), p2(2, 2, 2), p4(4, 4, 4); - p1*=2; - if (!(p1 == p2)) throw test_excep(); - if (!(p2 * 2 == p4)) throw test_excep(); - if (!(p2 * 2.f == p4)) throw test_excep(); - if (!(p2 * 2.f == p4)) throw test_excep(); - - Point2d pi1(1, 1), pi2(2, 2), pi4(4, 4); - pi1*=2; - if (!(pi1 == pi2)) throw test_excep(); - if (!(pi2 * 2 == pi4)) throw test_excep(); - if (!(pi2 * 2.f == pi4)) throw test_excep(); - if (!(pi2 * 2.f == pi4)) throw test_excep(); - - Vec2d v12(1, 1), v22(2, 2); - v12*=2.0; - if (!(v12 == v22)) throw test_excep(); - - Vec3d v13(1, 1, 1), v23(2, 2, 2); - v13*=2.0; - if (!(v13 == v23)) throw test_excep(); - - Vec4d v14(1, 1, 1, 1), v24(2, 2, 2, 2); - v14*=2.0; - if (!(v14 == v24)) throw test_excep(); - - Size sz(10, 20); - if (sz.area() != 200) throw test_excep(); - if (sz.width != 10 || sz.height != 20) throw test_excep(); - if (((CvSize)sz).width != 10 || ((CvSize)sz).height != 20) throw test_excep(); - - Vec v5d(1, 1, 1, 1, 1); - Vec v6d(1, 1, 1, 1, 1, 1); - Vec v7d(1, 1, 1, 1, 1, 1, 1); - Vec v8d(1, 1, 1, 1, 1, 1, 1, 1); - Vec v9d(1, 1, 1, 1, 1, 1, 1, 1, 1); - Vec v10d(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - - Vec v10dzero; - for (int ii = 0; ii < 10; ++ii) { - if (!v10dzero[ii] == 0.0) - throw test_excep(); - } - } - catch(const test_excep&) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - -void CV_OperationsTest::run( int /* start_from */) -{ - if (!TestMat()) - return; - - if (!SomeMatFunctions()) - return; - - if (!TestTemplateMat()) - return; - - /* if (!TestMatND()) - return;*/ - - if (!TestSparseMat()) - return; - - if (!operations1()) - return; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_OperationsTest cv_Operations_test; diff --git a/tests/cv/src/optflow.cpp b/tests/cv/src/optflow.cpp deleted file mode 100644 index e4e0d1b..0000000 --- a/tests/cv/src/optflow.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include -#include -#include -#include -#include -#include "cvaux.h" - -using namespace cv; -using namespace std; - -class CV_OptFlowTest : public CvTest -{ -public: - CV_OptFlowTest(); - ~CV_OptFlowTest(); -protected: - void run(int); - - bool runDense(const Point& shift = Point(3, 0)); - bool runSparse(); -}; - -CV_OptFlowTest::CV_OptFlowTest(): CvTest( "optflow-all", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_OptFlowTest::~CV_OptFlowTest() {} - - -Mat copnvert2flow(const Mat& velx, const Mat& vely) -{ - Mat flow(velx.size(), CV_32FC2); - for(int y = 0 ; y < flow.rows; ++y) - for(int x = 0 ; x < flow.cols; ++x) - flow.at(y, x) = Point2f(velx.at(y, x), vely.at(y, x)); - return flow; -} - -void calcOpticalFlowLK( const Mat& prev, const Mat& curr, Size winSize, Mat& flow ) -{ - Mat velx(prev.size(), CV_32F), vely(prev.size(), CV_32F); - CvMat cvvelx = velx; CvMat cvvely = vely; - CvMat cvprev = prev; CvMat cvcurr = curr; - cvCalcOpticalFlowLK( &cvprev, &cvcurr, winSize, &cvvelx, &cvvely ); - flow = copnvert2flow(velx, vely); -} - -void calcOpticalFlowBM( const Mat& prev, const Mat& curr, Size bSize, Size shiftSize, Size maxRange, int usePrevious, Mat& flow ) -{ - Size sz((curr.cols - bSize.width)/shiftSize.width, (curr.rows - bSize.height)/shiftSize.height); - Mat velx(sz, CV_32F), vely(sz, CV_32F); - - CvMat cvvelx = velx; CvMat cvvely = vely; - CvMat cvprev = prev; CvMat cvcurr = curr; - cvCalcOpticalFlowBM( &cvprev, &cvcurr, bSize, shiftSize, maxRange, usePrevious, &cvvelx, &cvvely); - flow = copnvert2flow(velx, vely); -} - -void calcOpticalFlowHS( const Mat& prev, const Mat& curr, int usePrevious, double lambda, TermCriteria criteria, Mat& flow) -{ - Mat velx(prev.size(), CV_32F), vely(prev.size(), CV_32F); - CvMat cvvelx = velx; CvMat cvvely = vely; - CvMat cvprev = prev; CvMat cvcurr = curr; - cvCalcOpticalFlowHS( &cvprev, &cvcurr, usePrevious, &cvvelx, &cvvely, lambda, criteria ); - flow = copnvert2flow(velx, vely); -} - -void calcAffineFlowPyrLK( const Mat& prev, const Mat& curr, - const vector& prev_features, vector& curr_features, - vector& status, vector& track_error, vector& matrices, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS,30, 0.01), - Size win_size = Size(15, 15), int level = 3, int flags = 0) -{ - CvMat cvprev = prev; - CvMat cvcurr = curr; - - size_t count = prev_features.size(); - curr_features.resize(count); - status.resize(count); - track_error.resize(count); - matrices.resize(count * 6); - - cvCalcAffineFlowPyrLK( &cvprev, &cvcurr, 0, 0, - (const CvPoint2D32f*)&prev_features[0], (CvPoint2D32f*)&curr_features[0], &matrices[0], - (int)count, win_size, level, (char*)&status[0], &track_error[0], criteria, flags ); -} - -double showFlowAndCalcError(const string& name, const Mat& gray, const Mat& flow, - const Rect& where, const Point& d, - bool showImages = false, bool writeError = false) -{ - const int mult = 16; - - if (showImages) - { - Mat tmp, cflow; - resize(gray, tmp, gray.size() * mult, 0, 0, INTER_NEAREST); - cvtColor(tmp, cflow, CV_GRAY2BGR); - - const float m2 = 0.3f; - const float minVel = 0.1f; - - for(int y = 0; y < flow.rows; ++y) - for(int x = 0; x < flow.cols; ++x) - { - Point2f f = flow.at(y, x); - - if (f.x * f.x + f.y * f.y > minVel * minVel) - { - Point p1 = Point(x, y) * mult; - Point p2 = Point(cvRound((x + f.x*m2) * mult), cvRound((y + f.y*m2) * mult)); - - line(cflow, p1, p2, CV_RGB(0, 255, 0)); - circle(cflow, Point(x, y) * mult, 2, CV_RGB(255, 0, 0)); - } - } - - rectangle(cflow, (where.tl() + d) * mult, (where.br() + d - Point(1,1)) * mult, CV_RGB(0, 0, 255)); - namedWindow(name, 1); imshow(name, cflow); - } - - double angle = atan2((float)d.y, (float)d.x); - double error = 0; - - bool all = true; - Mat inner = flow(where); - for(int y = 0; y < inner.rows; ++y) - for(int x = 0; x < inner.cols; ++x) - { - const Point2f f = inner.at(y, x); - - if (f.x == 0 && f.y == 0) - continue; - - all = false; - - double a = atan2(f.y, f.x); - error += fabs(angle - a); - } - double res = all ? numeric_limits::max() : error / (inner.cols * inner.rows); - - if (writeError) - cout << "Error " + name << " = " << res << endl; - - return res; -} - - -Mat generateImage(const Size& sz, bool doBlur = true) -{ - RNG rng; - Mat mat(sz, CV_8U); - mat = Scalar(0); - for(int y = 0; y < mat.rows; ++y) - for(int x = 0; x < mat.cols; ++x) - mat.at(y, x) = (uchar)rng; - if (doBlur) - blur(mat, mat, Size(3, 3)); - return mat; -} - -Mat generateSample(const Size& sz) -{ - Mat smpl(sz, CV_8U); - smpl = Scalar(0); - Point sc(smpl.cols/2, smpl.rows/2); - rectangle(smpl, Point(0,0), sc - Point(1,1), Scalar(255), CV_FILLED); - rectangle(smpl, sc, Point(smpl.cols, smpl.rows), Scalar(255), CV_FILLED); - return smpl; -} - -bool CV_OptFlowTest::runDense(const Point& d) -{ - Size matSize(40, 40); - Size movSize(8, 8); - - Mat smpl = generateSample(movSize); - Mat prev = generateImage(matSize); - Mat curr = prev.clone(); - - Rect rect(Point(prev.cols/2, prev.rows/2) - Point(movSize.width/2, movSize.height/2), movSize); - - Mat flowLK, flowBM, flowHS, flowFB, flowFB_G, flowBM_received, m1; - - m1 = prev(rect); smpl.copyTo(m1); - m1 = curr(Rect(rect.tl() + d, rect.br() + d)); smpl.copyTo(m1); - - calcOpticalFlowLK( prev, curr, Size(15, 15), flowLK); - calcOpticalFlowBM( prev, curr, Size(15, 15), Size(1, 1), Size(15, 15), 0, flowBM_received); - calcOpticalFlowHS( prev, curr, 0, 5, TermCriteria(TermCriteria::MAX_ITER, 400, 0), flowHS); - calcOpticalFlowFarneback( prev, curr, flowFB, 0.5, 3, std::max(d.x, d.y) + 10, 100, 6, 2, 0); - calcOpticalFlowFarneback( prev, curr, flowFB_G, 0.5, 3, std::max(d.x, d.y) + 10, 100, 6, 2, OPTFLOW_FARNEBACK_GAUSSIAN); - - flowBM.create(prev.size(), CV_32FC2); - flowBM = Scalar(0); - Point origin((flowBM.cols - flowBM_received.cols)/2, (flowBM.rows - flowBM_received.rows)/2); - Mat wcp = flowBM(Rect(origin, flowBM_received.size())); - flowBM_received.copyTo(wcp); - - double errorLK = showFlowAndCalcError("LK", prev, flowLK, rect, d); - double errorBM = showFlowAndCalcError("BM", prev, flowBM, rect, d); - double errorFB = showFlowAndCalcError("FB", prev, flowFB, rect, d); - double errorFBG = showFlowAndCalcError("FBG", prev, flowFB_G, rect, d); - double errorHS = showFlowAndCalcError("HS", prev, flowHS, rect, d); (void)errorHS; - //waitKey(); - - const double thres = 0.2; - if (errorLK > thres || errorBM > thres || errorFB > thres || errorFBG > thres /*|| errorHS > thres */) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - return true; -} - - -bool CV_OptFlowTest::runSparse() -{ - Mat prev = imread(string(ts->get_data_path()) + "optflow/rock_1.bmp", 0); - Mat next = imread(string(ts->get_data_path()) + "optflow/rock_2.bmp", 0); - - if (prev.empty() || next.empty()) - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return false; - } - - Mat cprev, cnext; - cvtColor(prev, cprev, CV_GRAY2BGR); - cvtColor(next, cnext, CV_GRAY2BGR); - - vector prev_pts; - vector next_ptsOpt; - vector next_ptsAff; - vector status_Opt; - vector status_Aff; - vector error; - vector matrices; - - Size netSize(10, 10); - Point2f center = Point(prev.cols/2, prev.rows/2); - - for(int i = 0 ; i < netSize.width; ++i) - for(int j = 0 ; j < netSize.width; ++j) - { - Point2f p(i * float(prev.cols)/netSize.width, j * float(prev.rows)/netSize.height); - prev_pts.push_back((p - center) * 0.5f + center); - } - - calcOpticalFlowPyrLK( prev, next, prev_pts, next_ptsOpt, status_Opt, error ); - calcAffineFlowPyrLK ( prev, next, prev_pts, next_ptsAff, status_Aff, error, matrices); - - const double expected_shift = 25; - const double thres = 1; - for(size_t i = 0; i < prev_pts.size(); ++i) - { - circle(cprev, prev_pts[i], 2, CV_RGB(255, 0, 0)); - - if (status_Opt[i]) - { - circle(cnext, next_ptsOpt[i], 2, CV_RGB(0, 0, 255)); - Point2f shift = prev_pts[i] - next_ptsOpt[i]; - - double n = sqrt(shift.ddot(shift)); - if (fabs(n - expected_shift) > thres) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - } - - if (status_Aff[i]) - { - circle(cnext, next_ptsAff[i], 4, CV_RGB(0, 255, 0)); - Point2f shift = prev_pts[i] - next_ptsAff[i]; - - double n = sqrt(shift.ddot(shift)); - if (fabs(n - expected_shift) > thres) - { - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; - } - } - - } - - /*namedWindow("P"); imshow("P", cprev); - namedWindow("N"); imshow("N", cnext); - waitKey();*/ - - return true; -} - - -void CV_OptFlowTest::run( int /* start_from */) -{ - - if (!runDense(Point(3, 0))) - return; - - if (!runDense(Point(0, 3))) - return; - - //if (!runDense(Point(3, 3))) return; //probably LK works incorrectly in this case. - - if (!runSparse()) - return; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_OptFlowTest optFlow_test; - diff --git a/tests/cv/src/tabruteforcematcher.cpp b/tests/cv/src/tabruteforcematcher.cpp deleted file mode 100644 index f43ee33..0000000 --- a/tests/cv/src/tabruteforcematcher.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "cvtest.h" - -using namespace cv; - -class BruteForceMatcherTest : public CvTest -{ -public: - BruteForceMatcherTest(); -protected: - void run( int ); -}; - -struct CV_EXPORTS L2Fake : public L2 -{ -}; - -BruteForceMatcherTest::BruteForceMatcherTest() : CvTest( "BruteForceMatcher", "BruteForceMatcher::matchImpl") -{ - support_testing_modes = CvTS::TIMING_MODE; -} - -void BruteForceMatcherTest::run( int ) -{ - const int dimensions = 64; - const int descriptorsNumber = 5000; - - Mat train = Mat( descriptorsNumber, dimensions, CV_32FC1); - Mat query = Mat( descriptorsNumber, dimensions, CV_32FC1); - - Mat permutation( 1, descriptorsNumber, CV_32SC1 ); - for( int i=0;i( 0, i ) = i; - - //RNG rng = RNG( cvGetTickCount() ); - RNG rng = RNG( *ts->get_rng() ); - randShuffle( permutation, 1, &rng ); - - float boundary = 500.f; - for( int row=0;row( permutation.at( 0, row ), col ) = bit*boundary + rng.uniform( 0.f, boundary ); - query.at( row, col ) = bit*boundary + rng.uniform( 0.f, boundary ); - } - } - - vector specMatches, genericMatches; - BruteForceMatcher > specMatcher; - BruteForceMatcher genericMatcher; - - int64 time0 = cvGetTickCount(); - specMatcher.match( query, train, specMatches ); - int64 time1 = cvGetTickCount(); - genericMatcher.match( query, train, genericMatches ); - int64 time2 = cvGetTickCount(); - - float specMatcherTime = float(time1 - time0)/(float)cvGetTickFrequency(); - ts->printf( CvTS::LOG, "Matching by matrix multiplication time s: %f, us per pair: %f\n", - specMatcherTime*1e-6, specMatcherTime/( descriptorsNumber*descriptorsNumber ) ); - - float genericMatcherTime = float(time2 - time1)/(float)cvGetTickFrequency(); - ts->printf( CvTS::LOG, "Matching without matrix multiplication time s: %f, us per pair: %f\n", - genericMatcherTime*1e-6, genericMatcherTime/( descriptorsNumber*descriptorsNumber ) ); - - if( (int)specMatches.size() != descriptorsNumber || (int)genericMatches.size() != descriptorsNumber ) - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - for( int i=0;i( 0, i ) ) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH ); - break; - } - } - - - //Test mask - Mat mask( query.rows, train.rows, CV_8UC1 ); - rng.fill( mask, RNG::UNIFORM, 0, 2 ); - - - time0 = cvGetTickCount(); - specMatcher.match( query, train, specMatches, mask ); - time1 = cvGetTickCount(); - genericMatcher.match( query, train, genericMatches, mask ); - time2 = cvGetTickCount(); - - specMatcherTime = float(time1 - time0)/(float)cvGetTickFrequency(); - ts->printf( CvTS::LOG, "Matching by matrix multiplication time with mask s: %f, us per pair: %f\n", - specMatcherTime*1e-6, specMatcherTime/( descriptorsNumber*descriptorsNumber ) ); - - genericMatcherTime = float(time2 - time1)/(float)cvGetTickFrequency(); - ts->printf( CvTS::LOG, "Matching without matrix multiplication time with mask s: %f, us per pair: %f\n", - genericMatcherTime*1e-6, genericMatcherTime/( descriptorsNumber*descriptorsNumber ) ); - - if( specMatches.size() != genericMatches.size() ) - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - - for( size_t i=0;iset_failed_test_info( CvTS::FAIL_MISMATCH ); - break; - } - } -} - -BruteForceMatcherTest taBruteForceMatcherTest; diff --git a/tests/cv/src/tchesscorners.cpp b/tests/cv/src/tchesscorners.cpp deleted file mode 100644 index 68acef1..0000000 --- a/tests/cv/src/tchesscorners.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -class CV_ChessboardDetectorTimingTest : public CvTest -{ -public: - CV_ChessboardDetectorTimingTest(); -protected: - void run(int); -}; - - -CV_ChessboardDetectorTimingTest::CV_ChessboardDetectorTimingTest(): - CvTest( "chessboard-detector-timing", "cvFindChessboardCorners" ) -{ - support_testing_modes = CvTS::TIMING_MODE; -} - -/* ///////////////////// chess_corner_test ///////////////////////// */ -void CV_ChessboardDetectorTimingTest::run( int start_from ) -{ - int code = CvTS::OK; - - /* test parameters */ - char filepath[1000]; - char filename[1000]; - - CvMat* _v = 0; - CvPoint2D32f* v; - - IplImage* img = 0; - IplImage* gray = 0; - IplImage* thresh = 0; - - int idx, max_idx; - int progress = 0; - - sprintf( filepath, "%scameracalibration/", ts->get_data_path() ); - sprintf( filename, "%schessboard_timing_list.dat", filepath ); - printf("Reading file %s\n", filename); - CvFileStorage* fs = cvOpenFileStorage( filename, 0, CV_STORAGE_READ ); - CvFileNode* board_list = fs ? cvGetFileNodeByName( fs, 0, "boards" ) : 0; - - if( !fs || !board_list || !CV_NODE_IS_SEQ(board_list->tag) || - board_list->data.seq->total % 4 != 0 ) - { - ts->printf( CvTS::LOG, "chessboard_timing_list.dat can not be readed or is not valid" ); - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - - max_idx = board_list->data.seq->total/4; - - for( idx = start_from; idx < max_idx; idx++ ) - { - int count0 = -1; - int count = 0; - CvSize pattern_size; - int result, result1 = 0; - - const char* imgname = cvReadString((CvFileNode*)cvGetSeqElem(board_list->data.seq,idx*4), "dummy.txt"); - int is_chessboard = cvReadInt((CvFileNode*)cvGetSeqElem(board_list->data.seq,idx*4+1), 0); - pattern_size.width = cvReadInt((CvFileNode*)cvGetSeqElem(board_list->data.seq,idx*4 + 2), -1); - pattern_size.height = cvReadInt((CvFileNode*)cvGetSeqElem(board_list->data.seq,idx*4 + 3), -1); - - ts->update_context( this, idx-1, true ); - - /* read the image */ - sprintf( filename, "%s%s", filepath, imgname ); - - img = cvLoadImage( filename ); - - if( !img ) - { - ts->printf( CvTS::LOG, "one of chessboard images can't be read: %s\n", filename ); - if( max_idx == 1 ) - { - code = CvTS::FAIL_MISSING_TEST_DATA; - goto _exit_; - } - continue; - } - - ts->printf(CvTS::LOG, "%s: chessboard %d:\n", imgname, is_chessboard); - - gray = cvCreateImage( cvSize( img->width, img->height ), IPL_DEPTH_8U, 1 ); - thresh = cvCreateImage( cvSize( img->width, img->height ), IPL_DEPTH_8U, 1 ); - cvCvtColor( img, gray, CV_BGR2GRAY ); - - - count0 = pattern_size.width*pattern_size.height; - - /* allocate additional buffers */ - _v = cvCreateMat(1, count0, CV_32FC2); - count = count0; - - v = (CvPoint2D32f*)_v->data.fl; - - int64 _time0 = cvGetTickCount(); - result = cvCheckChessboard(gray, pattern_size); - int64 _time01 = cvGetTickCount(); - - OPENCV_CALL( result1 = cvFindChessboardCorners( - gray, pattern_size, v, &count, 15 )); - int64 _time1 = cvGetTickCount(); - - if( result != is_chessboard ) - { - ts->printf( CvTS::LOG, "Error: chessboard was %sdetected in the image %s\n", - result ? "" : "not ", imgname ); - code = CvTS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - if(result != result1) - { - ts->printf( CvTS::LOG, "Warning: results differ cvCheckChessboard %d, cvFindChessboardCorners %d\n", - result, result1); - } - - int num_pixels = gray->width*gray->height; - float check_chessboard_time = float(_time01 - _time0)/(float)cvGetTickFrequency(); // in us - ts->printf(CvTS::LOG, " cvCheckChessboard time s: %f, us per pixel: %f\n", - check_chessboard_time*1e-6, check_chessboard_time/num_pixels); - - float find_chessboard_time = float(_time1 - _time01)/(float)cvGetTickFrequency(); - ts->printf(CvTS::LOG, " cvFindChessboard time s: %f, us per pixel: %f\n", - find_chessboard_time*1e-6, find_chessboard_time/num_pixels); - - cvReleaseMat( &_v ); - cvReleaseImage( &img ); - cvReleaseImage( &gray ); - cvReleaseImage( &thresh ); - progress = update_progress( progress, idx-1, max_idx, 0 ); - } - -_exit_: - - /* release occupied memory */ - cvReleaseMat( &_v ); - cvReleaseFileStorage( &fs ); - cvReleaseImage( &img ); - cvReleaseImage( &gray ); - cvReleaseImage( &thresh ); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -CV_ChessboardDetectorTimingTest chessboard_detector_timing_test; - -/* End of file. */ diff --git a/tests/cv/src/tsysa.cpp b/tests/cv/src/tsysa.cpp deleted file mode 100644 index 5c0cb89..0000000 --- a/tests/cv/src/tsysa.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" - -CvTS test_system("cv"); - -const char* blacklist[] = -{ - "calibrate-camera-artificial", //ticket 472 - "inpaint", //ticket 570 - "warp-resize", //ticket 429 - "_3d-rodrigues", //ticket 435 - 0 -}; - -int main(int argC,char *argV[]) -{ - return test_system.run( argC, argV, blacklist ); -} - -/* End of file. */ diff --git a/tests/cv/src/watershed.cpp b/tests/cv/src/watershed.cpp deleted file mode 100644 index 08c02a1..0000000 --- a/tests/cv/src/watershed.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cvtest.h" -#include - -using namespace cv; - -class CV_WatershedTest : public CvTest -{ -public: - CV_WatershedTest(); - ~CV_WatershedTest(); -protected: - void run(int); -}; - -CV_WatershedTest::CV_WatershedTest(): CvTest( "segmentation-watershed", "cvWatershed" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_WatershedTest::~CV_WatershedTest() {} - -void CV_WatershedTest::run( int /* start_from */) -{ - string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png"; - Mat exp = imread(exp_path, 0); - Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.jpg"); - FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ); - - if (orig.empty() || !fs.isOpened()) - { - ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); - return; - } - - CvSeq* cnts = (CvSeq*)fs["contours"].readObj(); - - Mat markers(orig.size(), CV_32SC1); - markers = Scalar(0); - IplImage iplmrks = markers; - - vector colors(1); - for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i ) - { - cvDrawContours( &iplmrks, cnts, Scalar::all(i + 1), Scalar::all(i + 1), -1, CV_FILLED); - Point* p = (Point*)cvGetSeqElem(cnts, 0); - - //expected image was added with 1 in order to save to png - //so now we substract 1 to get real color - if(exp.data) - colors.push_back(exp.ptr(p->y)[p->x] - 1); - } - fs.release(); - const int compNum = (int)(colors.size() - 1); - - watershed(orig, markers); - - for(int j = 0; j < markers.rows; ++j) - { - int* line = markers.ptr(j); - for(int i = 0; i < markers.cols; ++i) - { - int& pixel = line[i]; - - if (pixel == -1) // border - continue; - - if (pixel <= 0 || pixel > compNum) - continue; // bad result, doing nothing and going to get error latter; - - // repaint in saved color to compare with expected; - if(exp.data) - pixel = colors[pixel]; - } - } - - Mat markers8U; - markers.convertTo(markers8U, CV_8U, 1, 1); - - if( exp.empty() || orig.size() != exp.size() ) - { - imwrite(exp_path, markers8U); - exp = markers8U; - } - - if (0 != norm(markers8U, exp, NORM_INF)) - { - ts->set_failed_test_info( CvTS::FAIL_MISMATCH ); - return; - } - ts->set_failed_test_info(CvTS::OK); -} - -CV_WatershedTest watershed_test; diff --git a/tests/cxcore/CMakeLists.txt b/tests/cxcore/CMakeLists.txt deleted file mode 100644 index 6d137e4..0000000 --- a/tests/cxcore/CMakeLists.txt +++ /dev/null @@ -1,53 +0,0 @@ -# ---------------------------------------------------------------------------- -# CMake file for cxcoretest. See root CMakeLists.txt -# -# ---------------------------------------------------------------------------- -project(opencv_test_core) - -file(GLOB test_srcs "src/*.cpp") -source_group("Src" FILES ${test_srcs}) -file(GLOB test_hdrs "src/*.h*") -source_group("Include" FILES ${test_hdrs}) - -include_directories("${CMAKE_SOURCE_DIR}/include/opencv" - "${CMAKE_SOURCE_DIR}/modules/core/include" - "${CMAKE_CURRENT_SOURCE_DIR}/src" - "${CMAKE_CURRENT_BINARY_DIR}") - -include_directories(../cxts) - -set(the_target "opencv_test_core") - -add_executable(${the_target} ${test_srcs} ${test_hdrs}) - -if(PCHSupport_FOUND) - set(pch_header ${CMAKE_SOURCE_DIR}/tests/cxcore/src/cxcoretest.h) - if(${CMAKE_GENERATOR} MATCHES "Visual*" OR ${CMAKE_GENERATOR} MATCHES "Xcode*") - if(${CMAKE_GENERATOR} MATCHES "Visual*") - set(${the_target}_pch "src/precomp.cpp") - endif() - add_native_precompiled_header(${the_target} ${pch_header}) - elseif(CMAKE_COMPILER_IS_GNUCXX AND ${CMAKE_GENERATOR} MATCHES ".*Makefiles") - add_precompiled_header(${the_target} ${pch_header}) - endif() -endif() - -# Additional target properties -set_target_properties(${the_target} PROPERTIES - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/" - ) - - -add_dependencies(${the_target} opencv_ts opencv_core) - -# Add the required libraries for linking: -target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} opencv_ts opencv_core) - -enable_testing() -get_target_property(LOC ${the_target} LOCATION) -add_test(${the_target} "${LOC}") - -if(WIN32) -install(TARGETS ${the_target} RUNTIME DESTINATION bin COMPONENT main) -endif() diff --git a/tests/cxcore/src/aarithm.cpp b/tests/cxcore/src/aarithm.cpp deleted file mode 100644 index 844a46b..0000000 --- a/tests/cxcore/src/aarithm.cpp +++ /dev/null @@ -1,3560 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -////////////////////////////////////////////////////////////////////////////////////////// -////////////////// tests for arithmetic, logic and statistical functions ///////////////// -////////////////////////////////////////////////////////////////////////////////////////// - -#include "cxcoretest.h" -#include - -static const CvSize arithm_sizes[] = {{10,10}, {100,100}, {720,480}, {-1,-1}}; -static const CvSize arithm_whole_sizes[] = {{10,10}, {720,480}, {720,480}, {-1,-1}}; -static const int arithm_depths[] = { CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F, -1 }; -static const int arithm_channels[] = { 1, 2, 3, 4, -1 }; -static const char* arithm_mask_param_names[] = { "size", "channels", "depth", "use_mask", 0 }; -static const char* arithm_param_names[] = { "size", "channels", "depth", 0 }; -static const char* minmax_param_names[] = { "size", "depth", 0 }; - -class CxCore_ArithmTestImpl : public CvArrTest -{ -public: - CxCore_ArithmTestImpl( const char* test_name, const char* test_funcs, - int _generate_scalars=0, bool _allow_mask=true, bool _calc_abs=false ); -protected: - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int /*test_case_idx*/, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); - void generate_scalars( int depth ); - void finalize_scalar( CvScalar& s ); - CvScalar alpha, beta, gamma; - int gen_scalars; - bool calc_abs; - bool test_nd; -}; - - -CxCore_ArithmTestImpl::CxCore_ArithmTestImpl( const char* test_name, const char* test_funcs, - int _generate_scalars, bool _allow_mask, bool _calc_abs ) - : CvArrTest( test_name, test_funcs, "" ), - gen_scalars(_generate_scalars), calc_abs(_calc_abs) -{ - test_array[INPUT].push(NULL); - test_array[INPUT].push(NULL); - optional_mask = _allow_mask; - - if( optional_mask ) - { - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[MASK].push(NULL); - } - else - { - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - } - alpha = beta = gamma = cvScalarAll(0); - - size_list = arithm_sizes; - whole_size_list = arithm_whole_sizes; - depth_list = arithm_depths; - cn_list = arithm_channels; - test_nd = false; -} - - -void CxCore_ArithmTestImpl::generate_scalars( int depth ) -{ - bool is_timing = ts->get_testing_mode() == CvTS::TIMING_MODE; - double ab_min_val = -1.; - double ab_max_val = 1.; - double gamma_min_val = depth == CV_8U ? -100 : depth < CV_32F ? -10000 : -1e6; - double gamma_max_val = depth == CV_8U ? 100 : depth < CV_32F ? 10000 : 1e6; - - if( gen_scalars ) - { - CvRNG* rng = ts->get_rng(); - int i; - double m = 3.; - for( i = 0; i < 4; i++ ) - { - if( gen_scalars & 1 ) - { - alpha.val[i] = exp((cvTsRandReal(rng)-0.5)*m*2*CV_LOG2); - alpha.val[i] *= (cvTsRandInt(rng) & 1) ? 1 : -1; - if( is_timing ) - { - alpha.val[i] = MAX( alpha.val[i], ab_min_val ); - alpha.val[i] = MIN( alpha.val[i], ab_max_val ); - } - } - if( gen_scalars & 2 ) - { - beta.val[i] = exp((cvTsRandReal(rng)-0.5)*m*2*CV_LOG2); - beta.val[i] *= (cvTsRandInt(rng) & 1) ? 1 : -1; - if( is_timing ) - { - beta.val[i] = MAX( beta.val[i], ab_min_val ); - beta.val[i] = MIN( beta.val[i], ab_max_val ); - } - } - if( gen_scalars & 4 ) - { - gamma.val[i] = exp((cvTsRandReal(rng)-0.5)*m*2*CV_LOG2); - gamma.val[i] *= (cvTsRandInt(rng) & 1) ? 1 : -1; - if( is_timing ) - { - gamma.val[i] = MAX( gamma.val[i], gamma_min_val ); - gamma.val[i] = MIN( gamma.val[i], gamma_max_val ); - } - } - } - } - - if( depth == CV_32F ) - { - CvMat fl = cvMat( 1, 4, CV_32F, buf ); - CvMat db = cvMat( 1, 4, CV_64F, 0 ); - - db.data.db = alpha.val; - cvTsConvert( &db, &fl ); - cvTsConvert( &fl, &db ); - - db.data.db = beta.val; - cvTsConvert( &db, &fl ); - cvTsConvert( &fl, &db ); - - db.data.db = gamma.val; - cvTsConvert( &db, &fl ); - cvTsConvert( &fl, &db ); - } -} - -void CxCore_ArithmTestImpl::finalize_scalar( CvScalar& s ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - if( depth < CV_32F ) - s = cvScalar(cvRound(s.val[0]), cvRound(s.val[1]), cvRound(s.val[2]), cvRound(s.val[3])); -} - -void CxCore_ArithmTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng)%(CV_64F+1); - int cn = cvTsRandInt(rng) % 4 + 1; - int i, j; - depth += depth == CV_8S; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - generate_scalars( depth ); - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - int type = i != MASK ? CV_MAKETYPE(depth, cn) : CV_8UC1; - for( j = 0; j < count; j++ ) - { - types[i][j] = type; - } - } - test_nd = cvTsRandInt(rng)%3 == 0; -} - - -void CxCore_ArithmTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - generate_scalars( types[INPUT][0] ); - test_nd = false; -} - - -void CxCore_ArithmTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - const CvMat* mask = test_array[MASK].size() > 0 && test_array[MASK][0] ? &test_mat[MASK][0] : 0; - CvMat* output = test_array[REF_INPUT_OUTPUT].size() > 0 ? - &test_mat[REF_INPUT_OUTPUT][0] : &test_mat[REF_OUTPUT][0]; - CvMat* temp_dst = mask ? &test_mat[TEMP][0] : output; - cvTsAdd( &test_mat[INPUT][0], alpha, - test_array[INPUT].size() > 1 ? &test_mat[INPUT][1] : 0, beta, - gamma, temp_dst, calc_abs ); - if( mask ) - cvTsCopy( temp_dst, output, mask ); -} - - -CxCore_ArithmTestImpl arithm( "arithm", "", 0, false ); - - -class CxCore_ArithmTest : public CxCore_ArithmTestImpl -{ -public: - CxCore_ArithmTest( const char* test_name, const char* test_funcs, - int _generate_scalars=0, bool _allow_mask=true, bool _calc_abs=false ); -}; - - -CxCore_ArithmTest::CxCore_ArithmTest( const char* test_name, const char* test_funcs, - int _generate_scalars, bool _allow_mask, bool _calc_abs ) : - CxCore_ArithmTestImpl( test_name, test_funcs, _generate_scalars, _allow_mask, _calc_abs ) -{ - default_timing_param_names = optional_mask ? arithm_mask_param_names : arithm_param_names; - - // inherit the default parameters from arithmetical test - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -////////////////////////////// add ///////////////////////////// - -class CxCore_AddTest : public CxCore_ArithmTest -{ -public: - CxCore_AddTest(); -protected: - void run_func(); -}; - -CxCore_AddTest::CxCore_AddTest() - : CxCore_ArithmTest( "arithm-add", "cvAdd", 0, true ) -{ - alpha = beta = cvScalarAll(1.); -} - -void CxCore_AddTest::run_func() -{ - if(!test_nd) - { - cvAdd( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[INPUT][1]); - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - if( !test_array[MASK][0] ) - cv::add(a, b, c); - else - cv::add(a, b, c, cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_AddTest add_test; - -////////////////////////////// sub ///////////////////////////// - -class CxCore_SubTest : public CxCore_ArithmTest -{ -public: - CxCore_SubTest(); -protected: - void run_func(); -}; - -CxCore_SubTest::CxCore_SubTest() - : CxCore_ArithmTest( "arithm-sub", "cvSub", 0, true ) -{ - alpha = cvScalarAll(1.); - beta = cvScalarAll(-1.); -} - -void CxCore_SubTest::run_func() -{ - if(!test_nd) - { - cvSub( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[INPUT][1]); - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - if( !test_array[MASK][0] ) - cv::subtract(a, b, c); - else - cv::subtract(a, b, c, cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_SubTest sub_test; - - -////////////////////////////// adds ///////////////////////////// - -class CxCore_AddSTest : public CxCore_ArithmTest -{ -public: - CxCore_AddSTest(); -protected: - void run_func(); -}; - -CxCore_AddSTest::CxCore_AddSTest() - : CxCore_ArithmTest( "arithm-adds", "cvAddS", 4, true ) -{ - test_array[INPUT].pop(); - alpha = cvScalarAll(1.); -} - -void CxCore_AddSTest::run_func() -{ - finalize_scalar(gamma); - if(!test_nd) - { - if( test_mat[INPUT][0].cols % 2 == 0 ) - cvAddS( test_array[INPUT][0], gamma, - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - else - { - cv::Mat a = cv::cvarrToMat(test_array[INPUT][0]), - c = cv::cvarrToMat(test_array[INPUT_OUTPUT][0]); - cv::subtract(a, -cv::Scalar(gamma), c, test_array[MASK][0] ? - cv::cvarrToMat(test_array[MASK][0]) : cv::Mat()); - } - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::add( cv::cvarrToMatND(test_array[INPUT][0]), - gamma, c, test_array[MASK][0] ? - cv::cvarrToMatND(test_array[MASK][0]) : cv::MatND()); - } -} - -CxCore_AddSTest adds_test; - -////////////////////////////// subrs ///////////////////////////// - -class CxCore_SubRSTest : public CxCore_ArithmTest -{ -public: - CxCore_SubRSTest(); -protected: - void run_func(); -}; - -CxCore_SubRSTest::CxCore_SubRSTest() - : CxCore_ArithmTest( "arithm-subrs", "cvSubRS", 4, true ) -{ - test_array[INPUT].pop(); - alpha = cvScalarAll(-1.); -} - -void CxCore_SubRSTest::run_func() -{ - finalize_scalar(gamma); - if(!test_nd) - { - cvSubRS( test_array[INPUT][0], gamma, - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::subtract( gamma, - cv::cvarrToMatND(test_array[INPUT][0]), - c, test_array[MASK][0] ? - cv::cvarrToMatND(test_array[MASK][0]) : cv::MatND()); - } -} - -CxCore_SubRSTest subrs_test; - -////////////////////////////// addweighted ///////////////////////////// - -class CxCore_AddWeightedTest : public CxCore_ArithmTest -{ -public: - CxCore_AddWeightedTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); -}; - -CxCore_AddWeightedTest::CxCore_AddWeightedTest() - : CxCore_ArithmTest( "arithm-addweighted", "cvAddWeighted", 7, false ) -{ -} - -void CxCore_AddWeightedTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CxCore_ArithmTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - alpha = cvScalarAll(alpha.val[0]); - beta = cvScalarAll(beta.val[0]); - gamma = cvScalarAll(gamma.val[0]); -} - - -double CxCore_AddWeightedTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int type = cvGetElemType(test_array[i][j]), depth = CV_MAT_DEPTH(type); - if( depth <= CV_32S ) - return 2; - if( depth == CV_32F ) - { - CvScalar low=cvScalarAll(0), high=low; - get_minmax_bounds(i,j,type, &low, &high); - double a = (fabs(alpha.val[0])+fabs(beta.val[0]))*(fabs(low.val[0])+fabs(high.val[0])); - double b = fabs(gamma.val[0]); - return (a+b)*500*FLT_EPSILON; - } - return CvArrTest::get_success_error_level( test_case_idx, i, j ); -} - - -void CxCore_AddWeightedTest::run_func() -{ - if(!test_nd) - { - cvAddWeighted( test_array[INPUT][0], alpha.val[0], - test_array[INPUT][1], beta.val[0], - gamma.val[0], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::addWeighted(cv::cvarrToMatND(test_array[INPUT][0]), - alpha.val[0], - cv::cvarrToMatND(test_array[INPUT][1]), - beta.val[0], gamma.val[0], c); - } -} - -CxCore_AddWeightedTest addweighted_test; - - -////////////////////////////// absdiff ///////////////////////////// - -class CxCore_AbsDiffTest : public CxCore_ArithmTest -{ -public: - CxCore_AbsDiffTest(); -protected: - void run_func(); -}; - -CxCore_AbsDiffTest::CxCore_AbsDiffTest() - : CxCore_ArithmTest( "arithm-absdiff", "cvAbsDiff", 0, false, true ) -{ - alpha = cvScalarAll(1.); - beta = cvScalarAll(-1.); -} - -void CxCore_AbsDiffTest::run_func() -{ - if(!test_nd) - { - cvAbsDiff( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::absdiff(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c ); - } -} - -CxCore_AbsDiffTest absdiff_test; - -////////////////////////////// absdiffs ///////////////////////////// - -class CxCore_AbsDiffSTest : public CxCore_ArithmTest -{ -public: - CxCore_AbsDiffSTest(); -protected: - void run_func(); -}; - -CxCore_AbsDiffSTest::CxCore_AbsDiffSTest() - : CxCore_ArithmTest( "arithm-absdiffs", "cvAbsDiffS", 4, false, true ) -{ - alpha = cvScalarAll(-1.); - test_array[INPUT].pop(); -} - -void CxCore_AbsDiffSTest::run_func() -{ - finalize_scalar(gamma); - if(!test_nd) - { - cvAbsDiffS( test_array[INPUT][0], test_array[OUTPUT][0], gamma ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::absdiff(cv::cvarrToMatND(test_array[INPUT][0]), - gamma, c); - } -} - -CxCore_AbsDiffSTest absdiffs_test; - - -////////////////////////////// mul ///////////////////////////// - -static const char* mul_param_names[] = { "size", "scale", "channels", "depth", 0 }; -static const char* mul_scale_flags[] = { "scale==1", "scale!=1", 0 }; - -class CxCore_MulTest : public CxCore_ArithmTest -{ -public: - CxCore_MulTest(); -protected: - void run_func(); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void prepare_to_validation( int test_case_idx ); - int write_default_params( CvFileStorage* fs ); -}; - - -CxCore_MulTest::CxCore_MulTest() - : CxCore_ArithmTest( "arithm-mul", "cvMul", 4, false, false ) -{ - default_timing_param_names = mul_param_names; -} - - -int CxCore_MulTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_ArithmTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "scale", mul_scale_flags ); - return code; -} - - -void CxCore_MulTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_ArithmTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* scale_flag_str = cvReadString( find_timing_param( "scale" ), "scale==1" ); - if( strstr( scale_flag_str, "==1" ) ) - alpha.val[0] = 1.; - else - { - double val = alpha.val[0]; - int depth = CV_MAT_DEPTH(types[INPUT][0]); - if( val == 1. ) - val = 1./CV_PI; - if( depth == CV_16U || depth == CV_16S || depth == CV_32S ) - { - double minmax = 1./cvTsMaxVal(depth); - if( val < -minmax ) - val = -minmax; - else if( val > minmax ) - val = minmax; - if( depth == CV_16U && val < 0 ) - val = -val; - } - alpha.val[0] = val; - ts->printf( CvTS::LOG, "alpha = %g\n", alpha.val[0] ); - } -} - - -void CxCore_MulTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", alpha.val[0] == 1. ? "scale==1" : "scale!=1" ); - ptr += strlen(ptr); - params_left--; - CxCore_ArithmTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_MulTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - if( CV_MAT_DEPTH(cvGetElemType(test_array[i][j])) <= CV_32S ) - { - return gamma.val[0] != cvRound(gamma.val[0]); - } - else - return CvArrTest::get_success_error_level( test_case_idx, i, j ); -} - - -void CxCore_MulTest::run_func() -{ - if(!test_nd) - { - cvMul( test_array[INPUT][0], test_array[INPUT][1], - test_array[OUTPUT][0], alpha.val[0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::multiply(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c, alpha.val[0]); - } -} - -void CxCore_MulTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsMul( &test_mat[INPUT][0], &test_mat[INPUT][1], - cvScalarAll(alpha.val[0]), - &test_mat[REF_OUTPUT][0] ); -} - -CxCore_MulTest mul_test; - -////////////////////////////// div ///////////////////////////// - -class CxCore_DivTest : public CxCore_ArithmTest -{ -public: - CxCore_DivTest(); -protected: - void run_func(); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void prepare_to_validation( int /*test_case_idx*/ ); -}; - -CxCore_DivTest::CxCore_DivTest() - : CxCore_ArithmTest( "arithm-div", "cvDiv", 4, false, false ) -{ -} - -void CxCore_DivTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "s*A(i)/B(i)," ); - ptr += strlen(ptr); - params_left--; - CxCore_ArithmTest::print_timing_params( test_case_idx, ptr, params_left ); -} - -void CxCore_DivTest::run_func() -{ - if(!test_nd) - { - cvDiv( test_array[INPUT][0], test_array[INPUT][1], - test_array[OUTPUT][0], alpha.val[0] ); - } - else - { - cv::MatND b = cv::cvarrToMatND(test_array[INPUT][1]); - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::divide(cv::cvarrToMatND(test_array[INPUT][0]), - b, c, alpha.val[0]); - } -} - -void CxCore_DivTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsDiv( &test_mat[INPUT][0], &test_mat[INPUT][1], - cvScalarAll(alpha.val[0]), - &test_mat[REF_OUTPUT][0] ); -} - -CxCore_DivTest div_test; - -////////////////////////////// recip ///////////////////////////// - -class CxCore_RecipTest : public CxCore_ArithmTest -{ -public: - CxCore_RecipTest(); -protected: - void run_func(); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void prepare_to_validation( int /*test_case_idx*/ ); -}; - -CxCore_RecipTest::CxCore_RecipTest() - : CxCore_ArithmTest( "arithm-recip", "cvDiv", 4, false, false ) -{ - test_array[INPUT].pop(); -} - -void CxCore_RecipTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "s/B(i)," ); - ptr += strlen(ptr); - params_left--; - CxCore_ArithmTest::print_timing_params( test_case_idx, ptr, params_left ); -} - -void CxCore_RecipTest::run_func() -{ - if(!test_nd) - { - cvDiv( 0, test_array[INPUT][0], - test_array[OUTPUT][0], gamma.val[0] ); - } - else - { - cv::MatND b = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::divide(gamma.val[0], b, c); - } -} - -void CxCore_RecipTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsDiv( 0, &test_mat[INPUT][0], - cvScalarAll(gamma.val[0]), - &test_mat[REF_OUTPUT][0] ); -} - -CxCore_RecipTest recip_test; - - -///////////////// matrix copy/initializing/permutations ///////////////////// - -class CxCore_MemTestImpl : public CxCore_ArithmTestImpl -{ -public: - CxCore_MemTestImpl( const char* test_name, const char* test_funcs, - int _generate_scalars=0, bool _allow_mask=true ); -protected: - double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); -}; - -CxCore_MemTestImpl::CxCore_MemTestImpl( const char* test_name, const char* test_funcs, - int _generate_scalars, bool _allow_mask ) : - CxCore_ArithmTestImpl( test_name, test_funcs, _generate_scalars, _allow_mask, false ) -{ -} - -double CxCore_MemTestImpl::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - -CxCore_MemTestImpl mem_test( "mem", "", 0, false ); - - -class CxCore_MemTest : public CxCore_MemTestImpl -{ -public: - CxCore_MemTest( const char* test_name, const char* test_funcs, - int _generate_scalars=0, bool _allow_mask=true ); -}; - -CxCore_MemTest::CxCore_MemTest( const char* test_name, const char* test_funcs, - int _generate_scalars, bool _allow_mask ) : - CxCore_MemTestImpl( test_name, test_funcs, _generate_scalars, _allow_mask ) -{ - default_timing_param_names = optional_mask ? arithm_mask_param_names : arithm_param_names; - - // inherit the default parameters from arithmerical test - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -///////////////// setidentity ///////////////////// - -class CxCore_SetIdentityTest : public CxCore_MemTest -{ -public: - CxCore_SetIdentityTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_SetIdentityTest::CxCore_SetIdentityTest() : - CxCore_MemTest( "mem-setidentity", "cvSetIdentity", 4, false ) -{ - test_array[INPUT].clear(); -} - - -void CxCore_SetIdentityTest::run_func() -{ - if(!test_nd) - cvSetIdentity(test_array[OUTPUT][0], gamma); - else - { - cv::Mat a = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::setIdentity(a, gamma); - } -} - - -void CxCore_SetIdentityTest::prepare_to_validation( int ) -{ - cvTsSetIdentity( &test_mat[REF_OUTPUT][0], gamma ); -} - -CxCore_SetIdentityTest setidentity_test; - - -///////////////// SetZero ///////////////////// - -class CxCore_SetZeroTest : public CxCore_MemTest -{ -public: - CxCore_SetZeroTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_SetZeroTest::CxCore_SetZeroTest() : - CxCore_MemTest( "mem-setzero", "cvSetZero", 0, false ) -{ - test_array[INPUT].clear(); -} - - -void CxCore_SetZeroTest::run_func() -{ - if(!test_nd) - cvSetZero(test_array[OUTPUT][0]); - else - { - cv::MatND a = cv::cvarrToMatND(test_array[OUTPUT][0]); - a.setTo(cv::Scalar()); - } -} - - -void CxCore_SetZeroTest::prepare_to_validation( int ) -{ - cvTsZero( &test_mat[REF_OUTPUT][0] ); -} - -CxCore_SetZeroTest setzero_test; - - -///////////////// Set ///////////////////// - -class CxCore_FillTest : public CxCore_MemTest -{ -public: - CxCore_FillTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_FillTest::CxCore_FillTest() : - CxCore_MemTest( "mem-fill", "cvSet", 4, true ) -{ - test_array[INPUT].clear(); -} - - -void CxCore_FillTest::run_func() -{ - const CvArr* mask = test_array[MASK][0]; - if(!test_nd) - cvSet(test_array[INPUT_OUTPUT][0], gamma, mask); - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - a.setTo(gamma, mask ? cv::cvarrToMatND(mask) : cv::MatND()); - } -} - - -void CxCore_FillTest::prepare_to_validation( int ) -{ - if( test_array[MASK][0] ) - { - cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), gamma, &test_mat[TEMP][0], 0 ); - cvTsCopy( &test_mat[TEMP][0], &test_mat[REF_INPUT_OUTPUT][0], &test_mat[MASK][0] ); - } - else - { - cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), gamma, &test_mat[REF_INPUT_OUTPUT][0], 0 ); - } -} - -CxCore_FillTest fill_test; - - -///////////////// Copy ///////////////////// - -class CxCore_CopyTest : public CxCore_MemTest -{ -public: - CxCore_CopyTest(); -protected: - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_CopyTest::CxCore_CopyTest() : - CxCore_MemTest( "mem-copy", "cvCopy", 0, true ) -{ - test_array[INPUT].pop(); -} - - -double CxCore_CopyTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CxCore_CopyTest::run_func() -{ - const CvArr* mask = test_array[MASK][0]; - if(!test_nd) - cvCopy(test_array[INPUT][0], test_array[INPUT_OUTPUT][0], mask); - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - if(!mask) - a.copyTo(c); - else - a.copyTo(c, cv::cvarrToMatND(mask)); - } -} - - -void CxCore_CopyTest::prepare_to_validation( int ) -{ - cvTsCopy( &test_mat[INPUT][0], &test_mat[REF_INPUT_OUTPUT][0], - test_array[MASK].size() > 0 && test_array[MASK][0] ? &test_mat[MASK][0] : 0 ); -} - -CxCore_CopyTest copy_test; - -///////////////// Transpose ///////////////////// - -class CxCore_TransposeTest : public CxCore_MemTest -{ -public: - CxCore_TransposeTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - bool inplace; -}; - - -CxCore_TransposeTest::CxCore_TransposeTest() : - CxCore_MemTest( "mem-transpose", "cvTranspose", 0, false ), inplace(false) -{ - test_array[INPUT].pop(); -} - - -void CxCore_TransposeTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - int bits = cvTsRandInt(ts->get_rng()); - CxCore_MemTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - inplace = false; - if( bits & 1 ) - { - sizes[INPUT][0].height = sizes[INPUT][0].width; - inplace = (bits & 2) != 0; - } - - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(sizes[INPUT][0].height, sizes[INPUT][0].width ); -} - - -void CxCore_TransposeTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MemTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - CvSize size = sizes[INPUT][0]; - if( size.width != size.height ) - { - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = - whole_sizes[OUTPUT][0] = whole_sizes[REF_OUTPUT][0] = cvSize(size.height,size.width); - } -} - - -int CxCore_TransposeTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MemTest::prepare_test_case( test_case_idx ); - if( inplace && code > 0 ) - cvTsCopy( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ); - return code; -} - -void CxCore_TransposeTest::run_func() -{ - cvTranspose( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], test_array[OUTPUT][0]); -} - - -void CxCore_TransposeTest::prepare_to_validation( int ) -{ - cvTsTranspose( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0] ); -} - -CxCore_TransposeTest transpose_test; - - -///////////////// Flip ///////////////////// - -static const int flip_codes[] = { 0, 1, -1, INT_MIN }; -static const char* flip_strings[] = { "center", "vert", "horiz", 0 }; -static const char* flip_param_names[] = { "size", "flip_op", "channels", "depth", 0 }; - -class CxCore_FlipTest : public CxCore_MemTest -{ -public: - CxCore_FlipTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int write_default_params( CvFileStorage* fs ); - int flip_type; - bool inplace; -}; - - -CxCore_FlipTest::CxCore_FlipTest() : - CxCore_MemTest( "mem-flip", "cvFlip", 0, false ), flip_type(0), inplace(false) -{ - test_array[INPUT].pop(); - default_timing_param_names = flip_param_names; -} - - -int CxCore_FlipTest::write_default_params( CvFileStorage* fs ) -{ - int i, code = CxCore_MemTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - start_write_param( fs ); - cvStartWriteStruct( fs, "flip_op", CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; flip_codes[i] != INT_MIN; i++ ) - cvWriteString( fs, 0, flip_strings[flip_codes[i]+1] ); - cvEndWriteStruct(fs); - return code; -} - - -void CxCore_FlipTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - int bits = cvTsRandInt(ts->get_rng()); - CxCore_MemTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - flip_type = (bits & 3) - 2; - flip_type += flip_type == -2; - inplace = (bits & 4) != 0; -} - - -void CxCore_FlipTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MemTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* flip_op_str = cvReadString( find_timing_param( "flip_op" ), "center" ); - if( strcmp( flip_op_str, "vert" ) == 0 ) - flip_type = 0; - else if( strcmp( flip_op_str, "horiz" ) == 0 ) - flip_type = 1; - else - flip_type = -1; -} - - -void CxCore_FlipTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", flip_type > 0 ? "horiz" : flip_type < 0 ? "center" : "vert" ); - ptr += strlen(ptr); - params_left--; - CxCore_MemTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_FlipTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MemTest::prepare_test_case( test_case_idx ); - if( inplace && code > 0 ) - cvTsCopy( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ); - return code; -} - - -void CxCore_FlipTest::run_func() -{ - cvFlip(inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], test_array[OUTPUT][0], flip_type); -} - - -void CxCore_FlipTest::prepare_to_validation( int ) -{ - cvTsFlip( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], flip_type ); -} - -CxCore_FlipTest flip_test; - - -///////////////// Split/Merge ///////////////////// - -static const char* split_merge_types[] = { "all", "single", 0 }; -static int split_merge_channels[] = { 2, 3, 4, -1 }; -static const char* split_merge_param_names[] = { "size", "planes", "channels", "depth", 0 }; - -class CxCore_SplitMergeBaseTest : public CxCore_MemTest -{ -public: - CxCore_SplitMergeBaseTest( const char* test_name, const char* test_funcs, int _is_split ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void prepare_to_validation( int test_case_idx ); - int write_default_params( CvFileStorage* fs ); - bool are_images; - int is_split, coi; - void* hdrs[4]; -}; - - -CxCore_SplitMergeBaseTest::CxCore_SplitMergeBaseTest( const char* test_name, - const char* test_funcs, int _is_split ) - : CxCore_MemTest( test_name, test_funcs, 0, false ), are_images(false), is_split(_is_split), coi(0) -{ - test_array[INPUT].pop(); - if( is_split ) - ; - else - { - test_array[OUTPUT].clear(); - test_array[REF_OUTPUT].clear(); - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - } - memset( hdrs, 0, sizeof(hdrs) ); - - default_timing_param_names = split_merge_param_names; - cn_list = split_merge_channels; -} - - -int CxCore_SplitMergeBaseTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MemTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "planes", split_merge_types ); - return code; -} - - -void CxCore_SplitMergeBaseTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - int cn, depth; - CvRNG* rng = ts->get_rng(); - CxCore_MemTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - cn = cvTsRandInt(rng)%3 + 2; - depth = CV_MAT_DEPTH(types[INPUT][0]); - - if( is_split ) - { - types[INPUT][0] = CV_MAKETYPE(depth, cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = depth; - } - else - { - types[INPUT][0] = depth; - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(depth, cn); - } - - if( (cvTsRandInt(rng) & 3) != 0 ) - { - coi = cvTsRandInt(rng) % cn; - } - else - { - CvSize size = sizes[INPUT][0]; - size.height *= cn; - - if( is_split ) - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = size; - else - sizes[INPUT][0] = size; - coi = -1; - } - - are_images = cvTsRandInt(rng)%2 != 0; -} - - -void CxCore_SplitMergeBaseTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* _are_images ) -{ - CxCore_MemTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, _are_images ); - const char* split_merge_type = cvReadString( find_timing_param( "planes" ), "all" ); - int type0 = types[INPUT][0]; - int depth = CV_MAT_DEPTH(type0); - int cn = CV_MAT_CN(type0); - CvSize size = sizes[INPUT][0]; - - if( strcmp( split_merge_type, "single" ) == 0 ) - coi = cvTsRandInt(ts->get_rng()) % cn; - else - { - coi = -1; - size.height *= cn; - } - - if( is_split ) - { - types[OUTPUT][0] = types[REF_OUTPUT][0] = depth; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = size; - - // planes are put into separate arrays, not ROI's - whole_sizes[OUTPUT][0] = whole_sizes[REF_OUTPUT][0] = size; - } - else - { - types[INPUT][0] = depth; - sizes[INPUT][0] = size; - - // planes are put into separate arrays, not ROI's - whole_sizes[INPUT][0] = size; - } - - are_images = false; -} - - -void CxCore_SplitMergeBaseTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - int i; - - sprintf( ptr, "%s,", coi >= 0 ? "single" : "all" ); - ptr += strlen(ptr); - params_left--; - - // at once, delete the headers, though is not very good from structural point of view ... - for( i = 0; i < 4; i++ ) - cvRelease( &hdrs[i] ); - - CxCore_MemTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_SplitMergeBaseTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MemTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - CvMat* input = &test_mat[INPUT][0]; - CvMat* output = &test_mat[is_split ? OUTPUT : INPUT_OUTPUT][0]; - CvMat* merged = is_split ? input : output; - CvMat* planes = is_split ? output : input; - int depth = CV_MAT_DEPTH(merged->type); - int i, cn = CV_MAT_CN(merged->type), y = 0; - CvSize sz = cvGetMatSize(merged); - - for( i = 0; i < cn; i++ ) - { - if( coi < 0 || coi == i ) - { - if( are_images ) - hdrs[i] = cvCreateImageHeader( sz, cvIplDepth(depth), 1 ); - else - hdrs[i] = cvCreateMatHeader( sz.height, sz.width, depth ); - cvSetData( hdrs[i], planes->data.ptr + planes->step*y, planes->step ); - y += sz.height; - } - } - } - - return code; -} - - -void CxCore_SplitMergeBaseTest::prepare_to_validation( int ) -{ - CvMat* input = &test_mat[INPUT][0]; - CvMat* output = &test_mat[is_split ? REF_OUTPUT : REF_INPUT_OUTPUT][0]; - CvMat* merged = is_split ? input : output; - CvMat* planes = is_split ? output : input; - int i, cn = CV_MAT_CN(merged->type), y = 0; - CvSize sz = cvGetSize(merged); - - for( i = 0; i < cn; i++ ) - { - if( coi < 0 || coi == i ) - { - CvMat stub, *h; - cvSetData( hdrs[i], planes->data.ptr + planes->step*y, planes->step ); - h = cvGetMat( hdrs[i], &stub ); - if( is_split ) - cvTsExtract( input, h, i ); - else - cvTsInsert( h, output, i ); - cvSetData( hdrs[i], 0, 0 ); - cvRelease( &hdrs[i] ); - y += sz.height; - } - } -} - - -class CxCore_SplitTest : public CxCore_SplitMergeBaseTest -{ -public: - CxCore_SplitTest(); -protected: - void run_func(); -}; - - -CxCore_SplitTest::CxCore_SplitTest() : - CxCore_SplitMergeBaseTest( "mem-split", "cvSplit", 1 ) -{ -} - - -void CxCore_SplitTest::run_func() -{ - int i, nz = (hdrs[0] != 0) + (hdrs[1] != 0) + (hdrs[2] != 0) + (hdrs[3] != 0); - - if(!test_nd || nz != CV_MAT_CN(test_mat[INPUT][0].type)) - cvSplit( test_array[INPUT][0], hdrs[0], hdrs[1], hdrs[2], hdrs[3] ); - else - { - cv::MatND _hdrs[4]; - for( i = 0; i < nz; i++ ) - _hdrs[i] = cv::cvarrToMatND(hdrs[i]); - cv::split(cv::cvarrToMatND(test_array[INPUT][0]), _hdrs); - } -} - -CxCore_SplitTest split_test; - -class CxCore_MergeTest : public CxCore_SplitMergeBaseTest -{ -public: - CxCore_MergeTest(); -protected: - void run_func(); -}; - - -CxCore_MergeTest::CxCore_MergeTest() : - CxCore_SplitMergeBaseTest( "mem-merge", "cvMerge", 0 ) -{ -} - - -void CxCore_MergeTest::run_func() -{ - int i, nz = (hdrs[0] != 0) + (hdrs[1] != 0) + (hdrs[2] != 0) + (hdrs[3] != 0); - - if(!test_nd || nz != CV_MAT_CN(test_mat[INPUT_OUTPUT][0].type)) - cvMerge( hdrs[0], hdrs[1], hdrs[2], hdrs[3], test_array[INPUT_OUTPUT][0] ); - else - { - cv::MatND _hdrs[4], dst = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - for( i = 0; i < nz; i++ ) - _hdrs[i] = cv::cvarrToMatND(hdrs[i]); - cv::merge(_hdrs, nz, dst); - } -} - -CxCore_MergeTest merge_test; - -///////////////// CompleteSymm ///////////////////// - -class CxCore_CompleteSymm : public CvArrTest -{ -public: - CxCore_CompleteSymm(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int LtoR; //flags -}; - -CxCore_CompleteSymm::CxCore_CompleteSymm() : - CvArrTest("matrix-symm", "cvCompleteSymm", "Test of cvCompleteSymm function") -{ - /*Generates 1 input and 1 outputs (by default we have 2 inputs and 1 output)*/ - test_array[INPUT].clear(); - test_array[INPUT].push(NULL); - test_array[OUTPUT].clear(); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].clear(); - test_array[REF_OUTPUT].push(NULL); -} - - -void CxCore_CompleteSymm::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] =sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(sizes[INPUT][0].height, sizes[INPUT][0].height ); - - /*Making input and output matrixes one-channel*/ - int type; - switch (test_case_idx % 3) - { - case 0: - type = CV_32FC1; - break; - case 1: - type = CV_32SC1; - break; - default: - type = CV_64FC1; - } - types[OUTPUT][0] = types[INPUT][0] = types[REF_OUTPUT][0] = type; -} - -int CxCore_CompleteSymm::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if (code) - { - CvRNG* rng = ts->get_rng(); - unsigned val = cvRandInt(rng); - LtoR = val % 2; - cvConvert(&test_mat[INPUT][0], &test_mat[OUTPUT][0]); - } - return code; -} - -void CxCore_CompleteSymm::run_func() -{ - cvCompleteSymm(&test_mat[OUTPUT][0],LtoR); -} - -void CxCore_CompleteSymm::prepare_to_validation( int ) -{ - CvMat* ref_output = cvCreateMat(test_mat[OUTPUT][0].rows, test_mat[OUTPUT][0].cols, CV_64F); - CvMat* input = cvCreateMat(test_mat[INPUT][0].rows, test_mat[INPUT][0].cols, CV_64F); - cvConvert(&test_mat[INPUT][0], input); - - for (int i=0;irows;i++) - { - ref_output->data.db[i*input->cols+i]=input->data.db[i*input->cols+i]; - if (LtoR) - { - for (int j=0;jdata.db[j*input->cols+i] = ref_output->data.db[i*input->cols+j]=input->data.db[i*input->cols+j]; - } - - } - else - { - for (int j=0;jdata.db[j*input->cols+i] = ref_output->data.db[i*input->cols+j]=input->data.db[j*input->cols+i]; - } - } - } - - cvConvert(ref_output, &test_mat[REF_OUTPUT][0]); - cvReleaseMat(&input); - cvReleaseMat(&ref_output); -} - -CxCore_CompleteSymm complete_symm; - - -////////////////////////////// Sort ///////////////////////////////// - -class CxCore_SortTest : public CxCore_MemTest -{ -public: - CxCore_SortTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int flags; //flags for sorting -private: - static int compareIndexes (const void * a, const void * b); // comparing two elements of the matrix with pointers sorting - static int compare(const void * a, const void * b); // comparing two elements of the matrix with pointers sorting - bool useIndexMatrix; - bool useInPlaceSort; - CvMat* input; - -}; - -CxCore_SortTest::CxCore_SortTest() : - CxCore_MemTest( "matrix-sort", "cvSort", 0, false ) -{ - /*Generates 1 input and 2 outputs (by default we have 2 inputs and 1 output)*/ - test_array[INPUT].clear(); - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); -} - - -void CxCore_SortTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CxCore_MemTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = cvSize(sizes[INPUT][0].height, sizes[INPUT][0].width ); - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_32SC1; - - /*Making input and output matrixes one-channel*/ - types[OUTPUT][0] = types[INPUT][0] = CV_MAKETYPE(CV_MAT_DEPTH(types[INPUT][0]), 1); - types[REF_OUTPUT][0] = CV_MAKETYPE(CV_MAT_DEPTH(types[REF_OUTPUT][0]), 1); -} - -int CxCore_SortTest::prepare_test_case( int test_case_idx ) -{ - if (test_case_idx==0) - { - useIndexMatrix=true; - useInPlaceSort=false; - } - int code = CxCore_MemTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - //Copying input data - input = cvCreateMat(test_mat[INPUT][0].rows, test_mat[INPUT][0].cols, CV_64F); - cvConvert(&test_mat[INPUT][0], input); - CvRNG* rng = ts->get_rng(); - unsigned val = cvRandInt(rng); - // Setting up flags - switch (val%4) - { - case 0: - flags = CV_SORT_EVERY_ROW + CV_SORT_DESCENDING; - break; - case 1: - flags = CV_SORT_EVERY_ROW + CV_SORT_ASCENDING; - break; - case 2: - flags = CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING; - break; - case 3: - flags = CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING; - break; - } - if (val%3) - useIndexMatrix = !useIndexMatrix; - - if (val%5) - useInPlaceSort = !useInPlaceSort; - - } - return code; -} - -void CxCore_SortTest::run_func() -{ - //test_mat[OUTPUT][0] is sorted matrix - //test_mat[OUTPUT][1] is index matrix - if (useInPlaceSort) - { - cvConvert(&test_mat[INPUT][0], &test_mat[OUTPUT][0]); - if (useIndexMatrix) - cvSort(&(test_mat[OUTPUT][0]),&(test_mat[OUTPUT][0]),&(test_mat[OUTPUT][1]),flags); - else - { - cvSort(&(test_mat[OUTPUT][0]),&(test_mat[OUTPUT][0]),0,flags); - } - - } - else - { - if (useIndexMatrix) - cvSort(&(test_mat[INPUT][0]),&(test_mat[OUTPUT][0]),&(test_mat[OUTPUT][1]),flags); - else - { - cvSort(&(test_mat[INPUT][0]),&(test_mat[OUTPUT][0]),0,flags); - } - } -} - -int CxCore_SortTest::compareIndexes (const void * a, const void * b) -{ - double zero = 1e-30; - double res=(**((double**)a)-**((double**)b)); - return res<-zero?-1:(res>zero?1:0); -} -int CxCore_SortTest::compare (const void * a, const void * b) -{ - return *((int*)a)-*((int*)b); -} - -void CxCore_SortTest::prepare_to_validation(int) -{ - /*Creating matrixes copies to work with*/ - CvMat* ref_indexes = cvCreateMat(test_mat[REF_OUTPUT][1].rows, test_mat[REF_OUTPUT][1].cols, CV_32SC1); - CvMat* indexes = cvCreateMat(test_mat[OUTPUT][1].rows, test_mat[OUTPUT][1].cols, CV_32SC1); - CvMat* ref_output = cvCreateMat(test_mat[OUTPUT][0].rows, test_mat[OUTPUT][0].cols,CV_64F); - - /*Copying data*/ - cvConvert(&test_mat[REF_OUTPUT][1], ref_indexes); - cvConvert(&test_mat[OUTPUT][1], indexes); - - /*Following block generates REF_OUTPUT indexes matrix*/ - if ((flags == (CV_SORT_EVERY_ROW+CV_SORT_ASCENDING)) ||(flags == (CV_SORT_EVERY_ROW+CV_SORT_DESCENDING))) - for (int i=0;idata.i[ref_indexes->cols*i + j]=j; - else - for (int i=0;idata.i[ref_indexes->cols*i + j]=i; - cvConvert(ref_indexes, &test_mat[REF_OUTPUT][1]); - /*End of block*/ - - /* Matrix User's Sorting Algorithm */ - int order = -1; // order of sorting (ASCENDING or DESCENDING) - //// Following to variables are for sorting rows or cols in one block without any conditions (if statements) - short rowsSort=0; - short colsSort=0; - if ((flags == CV_SORT_EVERY_ROW+CV_SORT_ASCENDING)||(flags == CV_SORT_EVERY_COLUMN+CV_SORT_ASCENDING)) order=1; - if ((flags == CV_SORT_EVERY_ROW+CV_SORT_ASCENDING)||(flags == CV_SORT_EVERY_ROW+CV_SORT_DESCENDING)) rowsSort=1; - else colsSort=1; - int i,j; - - // For accessing [i,j] element using index matrix we can use following formula - // input->data.db[(input->cols*i+ref_indexes->cols*i+j)*rowsSort+(cols*(ref_indexes->cols*i+j)+j)*colsSort]; - - if ((flags == CV_SORT_EVERY_ROW+CV_SORT_ASCENDING)||(flags == CV_SORT_EVERY_ROW+CV_SORT_DESCENDING)) - { - double** row = new double*[input->cols]; - for (i=0;irows; i++) - { - for (int j=0;jcols;j++) - row[j]=&(input->data.db[(input->cols*i+j)]); - qsort(row,input->cols,sizeof(row[0]),&CxCore_SortTest::compareIndexes); - for (int j=0;jcols;j++) - { - if (order==1) - ref_indexes->data.i[ref_indexes->cols*i+j]=(int)(row[j]-&(input->data.db[input->cols*i])); - else - ref_indexes->data.i[ref_indexes->cols*(i+1)-1-j]=(int)(row[j]-&(input->data.db[input->cols*i])); - } - } - delete[] row; - } - else - { - double** col = new double*[input->rows]; - for (j=0;jcols; j++) - { - for (int i=0;irows;i++) - col[i]=&(input->data.db[(input->cols*i+j)]); - qsort(col,input->rows,sizeof(col[0]),&CxCore_SortTest::compareIndexes); - for (int i=0;irows;i++) - { - if (order==1) - ref_indexes->data.i[ref_indexes->cols*i+j]=(int)((col[i]-&(input->data.db[j]))/(ref_output->cols)); - else - ref_indexes->data.i[ref_indexes->cols*(ref_indexes->rows-1-i)+j]=(int)(col[i]-&(input->data.db[j]))/(ref_output->cols); - } - } - delete[] col; - } - - /*End of Sort*/ - - int n; - for (i=0;irows;i++) - for (j=0;jcols;j++) - { - n=(input->cols*i+ref_indexes->data.i[ref_indexes->cols*i+j])*rowsSort+ - (input->cols*(ref_indexes->data.i[ref_indexes->cols*i+j])+j)*colsSort; - ref_output->data.db[ref_output->cols*i+j] = input->data.db[n]; - } - - if (useIndexMatrix) - { - /* Comparing indexes matrixes */ - if ((flags == CV_SORT_EVERY_ROW+CV_SORT_ASCENDING)||(flags == CV_SORT_EVERY_ROW+CV_SORT_DESCENDING)) - { - int begin=0,end=0; - double temp; - for (i=0;irows;i++) - { - for (j=0;jcols-1;j++) - if (ref_output->data.db[ref_output->cols*i+j]==ref_output->data.db[ref_output->cols*i+j+1]) - { - temp=ref_output->data.db[ref_output->cols*i+j]; - begin=j++; - while ((jcols)&&(temp==ref_output->data.db[ref_output->cols*i+j])) j++; - end=--j; - int* row = new int[end-begin+1]; - int* row1 = new int[end-begin+1]; - - for (int k=0;k<=end-begin;k++) - { - row[k]=ref_indexes->data.i[ref_indexes->cols*i+k+begin]; - row1[k]=indexes->data.i[indexes->cols*i+k+begin]; - } - qsort(row,end-begin+1,sizeof(row[0]),&CxCore_SortTest::compare); - qsort(row1,end-begin+1,sizeof(row1[0]),&CxCore_SortTest::compare); - for (int k=0;k<=end-begin;k++) - { - ref_indexes->data.i[ref_indexes->cols*i+k+begin]=row[k]; - indexes->data.i[indexes->cols*i+k+begin]=row1[k]; - } - delete[] row; - delete[] row1; - } - } - } - else - { - int begin=0,end=0; - double temp; - for (j=0;jcols;j++) - { - for (i=0;irows-1;i++) - if (ref_output->data.db[ref_output->cols*i+j]==ref_output->data.db[ref_output->cols*(i+1)+j]) - { - temp=ref_output->data.db[ref_output->cols*i+j]; - begin=i++; - while ((irows)&&(temp==ref_output->data.db[ref_output->cols*i+j])) i++; - end=--i; - - int* col = new int[end-begin+1]; - int* col1 = new int[end-begin+1]; - - for (int k=0;k<=end-begin;k++) - { - col[k]=ref_indexes->data.i[ref_indexes->cols*(k+begin)+j]; - col1[k]=indexes->data.i[indexes->cols*(k+begin)+j]; - } - qsort(col,end-begin+1,sizeof(col[0]),&CxCore_SortTest::compare); - qsort(col1,end-begin+1,sizeof(col1[0]),&CxCore_SortTest::compare); - for (int k=0;k<=end-begin;k++) - { - ref_indexes->data.i[ref_indexes->cols*(k+begin)+j]=col[k]; - indexes->data.i[indexes->cols*(k+begin)+j]=col1[k]; - } - delete[] col; - delete[] col1; - } - } - } - /* End of compare*/ - cvConvert(ref_indexes, &test_mat[REF_OUTPUT][1]); - cvConvert(indexes, &test_mat[OUTPUT][1]); - } - else - { - cvConvert(ref_indexes, &test_mat[REF_OUTPUT][1]); - cvConvert(ref_indexes, &test_mat[OUTPUT][1]); - } - - cvConvert(ref_output, &test_mat[REF_OUTPUT][0]); - - /*releasing matrixes*/ - cvReleaseMat(&ref_output); - cvReleaseMat(&input); - cvReleaseMat(&indexes); - cvReleaseMat(&ref_indexes); -} - -CxCore_SortTest sort_test; - -////////////////////////////// min/max ///////////////////////////// - -class CxCore_MinMaxBaseTest : public CxCore_ArithmTest -{ -public: - CxCore_MinMaxBaseTest( const char* test_name, const char* test_funcs, - int _op_type, int _generate_scalars=0 ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); - void prepare_to_validation( int /*test_case_idx*/ ); - int op_type; -}; - -CxCore_MinMaxBaseTest::CxCore_MinMaxBaseTest( const char* test_name, const char* test_funcs, - int _op_type, int _generate_scalars ) - : CxCore_ArithmTest( test_name, test_funcs, _generate_scalars, false, false ), op_type(_op_type) -{ - if( _generate_scalars ) - test_array[INPUT].pop(); - default_timing_param_names = minmax_param_names; -} - -double CxCore_MinMaxBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - -void CxCore_MinMaxBaseTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - int i, j; - CxCore_ArithmTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - for( j = 0; j < count; j++ ) - { - types[i][j] &= ~CV_MAT_CN_MASK; - } - } -} - -void CxCore_MinMaxBaseTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - if( !gen_scalars ) - cvTsMinMax( &test_mat[INPUT][0], &test_mat[INPUT][1], - &test_mat[REF_OUTPUT][0], op_type ); - else - cvTsMinMaxS( &test_mat[INPUT][0], gamma.val[0], - &test_mat[REF_OUTPUT][0], op_type ); -} - - -class CxCore_MinTest : public CxCore_MinMaxBaseTest -{ -public: - CxCore_MinTest(); -protected: - void run_func(); -}; - - -CxCore_MinTest::CxCore_MinTest() - : CxCore_MinMaxBaseTest( "arithm-min", "cvMin", CV_TS_MIN, 0 ) -{ -} - -void CxCore_MinTest::run_func() -{ - if(!test_nd) - { - cvMin( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::min(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), c); - } -} - -CxCore_MinTest min_test; - - -////////////////////////////// max ///////////////////////////// - -class CxCore_MaxTest : public CxCore_MinMaxBaseTest -{ -public: - CxCore_MaxTest(); -protected: - void run_func(); -}; - -CxCore_MaxTest::CxCore_MaxTest() - : CxCore_MinMaxBaseTest( "arithm-max", "cvMax", CV_TS_MAX, 0 ) -{ -} - -void CxCore_MaxTest::run_func() -{ - if(!test_nd) - { - cvMax( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::max(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), c); - } -} - -CxCore_MaxTest max_test; - - -////////////////////////////// mins ///////////////////////////// - -class CxCore_MinSTest : public CxCore_MinMaxBaseTest -{ -public: - CxCore_MinSTest(); -protected: - void run_func(); -}; - -CxCore_MinSTest::CxCore_MinSTest() - : CxCore_MinMaxBaseTest( "arithm-mins", "cvMinS", CV_TS_MIN, 4 ) -{ -} - -void CxCore_MinSTest::run_func() -{ - if(!test_nd) - { - cvMinS( test_array[INPUT][0], gamma.val[0], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::min(cv::cvarrToMatND(test_array[INPUT][0]), - gamma.val[0], c); - } -} - -CxCore_MinSTest mins_test; - -////////////////////////////// maxs ///////////////////////////// - -class CxCore_MaxSTest : public CxCore_MinMaxBaseTest -{ -public: - CxCore_MaxSTest(); -protected: - void run_func(); -}; - -CxCore_MaxSTest::CxCore_MaxSTest() - : CxCore_MinMaxBaseTest( "arithm-maxs", "cvMaxS", CV_TS_MAX, 4 ) -{ -} - -void CxCore_MaxSTest::run_func() -{ - if(!test_nd) - { - cvMaxS( test_array[INPUT][0], gamma.val[0], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::max(cv::cvarrToMatND(test_array[INPUT][0]), - gamma.val[0], c); - } -} - -CxCore_MaxSTest maxs_test; - - -//////////////////////////////// logic /////////////////////////////////////// - -class CxCore_LogicTestImpl : public CxCore_ArithmTestImpl -{ -public: - CxCore_LogicTestImpl( const char* test_name, const char* test_funcs, int _logic_op, - int _generate_scalars=0, bool _allow_mask=true ); -protected: - void prepare_to_validation( int test_case_idx ); - int logic_op; -}; - -CxCore_LogicTestImpl::CxCore_LogicTestImpl( const char* test_name, const char* test_funcs, - int _logic_op, int _generate_scalars, bool _allow_mask ) - : CxCore_ArithmTestImpl( test_name, test_funcs, _generate_scalars, _allow_mask, false ), - logic_op(_logic_op) -{ - if( _generate_scalars ) - test_array[INPUT].pop(); -} - -void CxCore_LogicTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - int ref_output_idx = optional_mask ? REF_INPUT_OUTPUT : REF_OUTPUT; - int output_idx = optional_mask ? INPUT_OUTPUT : OUTPUT; - const CvMat* mask = test_array[MASK].size() > 0 && test_array[MASK][0] ? &test_mat[MASK][0] : 0; - CvMat* dst = mask ? &test_mat[TEMP][0] : &test_mat[ref_output_idx][0]; - int i; - if( test_array[INPUT].size() > 1 ) - { - cvTsLogic( &test_mat[INPUT][0], &test_mat[INPUT][1], dst, logic_op ); - } - else - { - cvTsLogicS( &test_mat[INPUT][0], gamma, dst, logic_op ); - } - if( mask ) - cvTsCopy( dst, &test_mat[ref_output_idx][0], mask ); - - for( i = 0; i < 2; i++ ) - { - dst = i == 0 ? &test_mat[ref_output_idx][0] : &test_mat[output_idx][0]; - - if( CV_IS_MAT(dst) ) - { - CvMat* mat = (CvMat*)dst; - mat->cols *= CV_ELEM_SIZE(mat->type); - mat->type = (mat->type & ~CV_MAT_TYPE_MASK) | CV_8UC1; - } - else - { - IplImage* img = (IplImage*)dst; - int elem_size; - - assert( CV_IS_IMAGE(dst) ); - elem_size = ((img->depth & 255)>>3)*img->nChannels; - img->width *= elem_size; - - if( img->roi ) - { - img->roi->xOffset *= elem_size; - img->roi->width *= elem_size; - } - img->depth = IPL_DEPTH_8U; - img->nChannels = 1; - } - } -} - -CxCore_LogicTestImpl logic_test("logic", "", -1, 0, false ); - -class CxCore_LogicTest : public CxCore_LogicTestImpl -{ -public: - CxCore_LogicTest( const char* test_name, const char* test_funcs, int _logic_op, - int _generate_scalars=0, bool _allow_mask=true ); -}; - -CxCore_LogicTest::CxCore_LogicTest( const char* test_name, const char* test_funcs, - int _logic_op, int _generate_scalars, bool _allow_mask ) - : CxCore_LogicTestImpl( test_name, test_funcs, _logic_op, _generate_scalars, _allow_mask ) -{ - default_timing_param_names = optional_mask ? arithm_mask_param_names : arithm_param_names; - - // inherit the default parameters from arithmerical test - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -///////////////////////// and ////////////////////////// - -class CxCore_AndTest : public CxCore_LogicTest -{ -public: - CxCore_AndTest(); -protected: - void run_func(); -}; - -CxCore_AndTest::CxCore_AndTest() - : CxCore_LogicTest( "logic-and", "cvAnd", CV_TS_LOGIC_AND ) -{ -} - -void CxCore_AndTest::run_func() -{ - if(!test_nd) - { - cvAnd( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_and(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c, cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_AndTest and_test; - - -class CxCore_AndSTest : public CxCore_LogicTest -{ -public: - CxCore_AndSTest(); -protected: - void run_func(); -}; - -CxCore_AndSTest::CxCore_AndSTest() - : CxCore_LogicTest( "logic-ands", "cvAndS", CV_TS_LOGIC_AND, 4 ) -{ -} - -void CxCore_AndSTest::run_func() -{ - if(!test_nd) - { - cvAndS( test_array[INPUT][0], gamma, - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_and(cv::cvarrToMatND(test_array[INPUT][0]), - gamma, c, - cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_AndSTest ands_test; - - -///////////////////////// or ///////////////////////// - -class CxCore_OrTest : public CxCore_LogicTest -{ -public: - CxCore_OrTest(); -protected: - void run_func(); -}; - -CxCore_OrTest::CxCore_OrTest() - : CxCore_LogicTest( "logic-or", "cvOr", CV_TS_LOGIC_OR ) -{ -} - -void CxCore_OrTest::run_func() -{ - if(!test_nd) - { - cvOr( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_or(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c, cv::cvarrToMatND(test_array[MASK][0])); - } - -} - -CxCore_OrTest or_test; - - -class CxCore_OrSTest : public CxCore_LogicTest -{ -public: - CxCore_OrSTest(); -protected: - void run_func(); -}; - -CxCore_OrSTest::CxCore_OrSTest() - : CxCore_LogicTest( "logic-ors", "cvOrS", CV_TS_LOGIC_OR, 4 ) -{ -} - -void CxCore_OrSTest::run_func() -{ - if(!test_nd) - { - cvOrS( test_array[INPUT][0], gamma, - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_or(cv::cvarrToMatND(test_array[INPUT][0]), - gamma, c, - cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_OrSTest ors_test; - - -////////////////////////// xor //////////////////////////// - -class CxCore_XorTest : public CxCore_LogicTest -{ -public: - CxCore_XorTest(); -protected: - void run_func(); -}; - -CxCore_XorTest::CxCore_XorTest() - : CxCore_LogicTest( "logic-xor", "cvXor", CV_TS_LOGIC_XOR ) -{ -} - -void CxCore_XorTest::run_func() -{ - if(!test_nd) - { - cvXor( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_xor(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c, cv::cvarrToMatND(test_array[MASK][0])); - } - -} - -CxCore_XorTest xor_test; - - -class CxCore_XorSTest : public CxCore_LogicTest -{ -public: - CxCore_XorSTest(); -protected: - void run_func(); -}; - -CxCore_XorSTest::CxCore_XorSTest() - : CxCore_LogicTest( "logic-xors", "cvXorS", CV_TS_LOGIC_XOR, 4 ) -{ -} - -void CxCore_XorSTest::run_func() -{ - if(!test_nd) - { - cvXorS( test_array[INPUT][0], gamma, - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[INPUT_OUTPUT][0]); - cv::bitwise_xor(cv::cvarrToMatND(test_array[INPUT][0]), - gamma, c, - cv::cvarrToMatND(test_array[MASK][0])); - } -} - -CxCore_XorSTest xors_test; - - -////////////////////////// not //////////////////////////// - -class CxCore_NotTest : public CxCore_LogicTest -{ -public: - CxCore_NotTest(); -protected: - void run_func(); -}; - -CxCore_NotTest::CxCore_NotTest() - : CxCore_LogicTest( "logic-not", "cvNot", CV_TS_LOGIC_NOT, 4, false ) -{ -} - -void CxCore_NotTest::run_func() -{ - if(!test_nd) - { - cvNot( test_array[INPUT][0], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::bitwise_not(cv::cvarrToMatND(test_array[INPUT][0]), c); - } -} - -CxCore_NotTest nots_test; - -///////////////////////// cmp ////////////////////////////// - -static int cmp_op_values[] = { CV_CMP_GE, CV_CMP_EQ, CV_CMP_NE, -1 }; - -class CxCore_CmpBaseTestImpl : public CxCore_ArithmTestImpl -{ -public: - CxCore_CmpBaseTestImpl( const char* test_name, const char* test_funcs, - int in_range, int _generate_scalars=0 ); -protected: - double get_success_error_level( int test_case_idx, int i, int j ); - void get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, - int** types, CvSize** whole_sizes, bool* are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void prepare_to_validation( int test_case_idx ); - int write_default_params( CvFileStorage* fs ); - int in_range; - int cmp_op; - enum { CMP_OP_COUNT=6 }; - const char* cmp_op_strings[CMP_OP_COUNT]; -}; - -CxCore_CmpBaseTestImpl::CxCore_CmpBaseTestImpl( const char* test_name, const char* test_funcs, - int _in_range, int _generate_scalars ) - : CxCore_ArithmTestImpl( test_name, test_funcs, _generate_scalars, 0, 0 ), in_range(_in_range) -{ - static const char* cmp_param_names[] = { "size", "cmp_op", "depth", 0 }; - static const char* inrange_param_names[] = { "size", "channels", "depth", 0 }; - - if( in_range ) - { - test_array[INPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - if( !gen_scalars ) - test_array[TEMP].push(NULL); - } - if( gen_scalars ) - test_array[INPUT].pop(); - - default_timing_param_names = in_range == 1 ? inrange_param_names : cmp_param_names; - - cmp_op_strings[CV_CMP_EQ] = "eq"; - cmp_op_strings[CV_CMP_LT] = "lt"; - cmp_op_strings[CV_CMP_LE] = "le"; - cmp_op_strings[CV_CMP_GE] = "ge"; - cmp_op_strings[CV_CMP_GT] = "gt"; - cmp_op_strings[CV_CMP_NE] = "ne"; - - cmp_op = -1; -} - -double CxCore_CmpBaseTestImpl::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CxCore_CmpBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - int j, count; - CxCore_ArithmTestImpl::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_8UC1; - if( in_range == 0 ) - { - // for cmp tests make all the input arrays single-channel - count = test_array[INPUT].size(); - for( j = 0; j < count; j++ ) - types[INPUT][j] &= ~CV_MAT_CN_MASK; - - cmp_op = cvTsRandInt(ts->get_rng()) % 6; // == > >= < <= != - } - else if( in_range == 1 ) - { - types[TEMP][0] = CV_8UC1; - types[TEMP][1] &= ~CV_MAT_CN_MASK; - if( !gen_scalars ) - types[TEMP][2] &= ~CV_MAT_CN_MASK; - } -} - - -int CxCore_CmpBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_ArithmTestImpl::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - if( in_range == 0 ) - { - start_write_param( fs ); - int i; - cvStartWriteStruct( fs, "cmp_op", CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; cmp_op_values[i] >= 0; i++ ) - cvWriteString( fs, 0, cmp_op_strings[cmp_op_values[i]] ); - cvEndWriteStruct(fs); - } - return code; -} - - -void CxCore_CmpBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_ArithmTestImpl::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - types[OUTPUT][0] = CV_8UC1; - if( in_range == 0 ) - { - const char* cmp_op_str = cvReadString( find_timing_param( "cmp_op" ), "ge" ); - int i; - cmp_op = CV_CMP_GE; - for( i = 0; i < CMP_OP_COUNT; i++ ) - if( strcmp( cmp_op_str, cmp_op_strings[i] ) == 0 ) - { - cmp_op = i; - break; - } - } -} - - -void CxCore_CmpBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - if( in_range == 0 ) - { - sprintf( ptr, "%s,", cmp_op_strings[cmp_op] ); - ptr += strlen(ptr); - params_left--; - } - CxCore_ArithmTestImpl::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CxCore_CmpBaseTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* dst = &test_mat[REF_OUTPUT][0]; - if( !in_range ) - { - if( test_array[INPUT].size() > 1 ) - { - cvTsCmp( &test_mat[INPUT][0], &test_mat[INPUT][1], dst, cmp_op ); - } - else - { - cvTsCmpS( &test_mat[INPUT][0], gamma.val[0], dst, cmp_op ); - } - } - else - { - int el_type = CV_MAT_TYPE( test_mat[INPUT][0].type ); - int i, cn = CV_MAT_CN(el_type); - CvMat* tdst = dst; - - for( i = 0; i < cn*2; i++ ) - { - int coi = i / 2, is_lower = (i % 2) == 0; - int cmp_op = is_lower ? CV_CMP_GE : CV_CMP_LT; - const CvMat* src = &test_mat[INPUT][0]; - const CvMat* lu = gen_scalars ? 0 : &test_mat[INPUT][is_lower?1:2]; - double luS = is_lower ? alpha.val[coi] : gamma.val[coi]; - - if( cn > 1 ) - { - cvTsExtract( src, &test_mat[TEMP][1], coi ); - src = &test_mat[TEMP][1]; - - if( !gen_scalars ) - { - cvTsExtract( lu, &test_mat[TEMP][2], coi ); - lu = &test_mat[TEMP][2]; - } - } - - if( !gen_scalars ) - cvTsCmp( src, lu, tdst, cmp_op ); - else - cvTsCmpS( src, luS, tdst, cmp_op ); - if( i > 0 ) - cvTsLogic( tdst, dst, dst, CV_TS_LOGIC_AND ); - tdst = &test_mat[TEMP][0]; - } - } -} - - -CxCore_CmpBaseTestImpl cmpbase_test( "cmp", "", -1 ); - - -class CxCore_CmpBaseTest : public CxCore_CmpBaseTestImpl -{ -public: - CxCore_CmpBaseTest( const char* test_name, const char* test_funcs, - int in_range, int _generate_scalars=0 ); -}; - -CxCore_CmpBaseTest::CxCore_CmpBaseTest( const char* test_name, const char* test_funcs, - int _in_range, int _generate_scalars ) - : CxCore_CmpBaseTestImpl( test_name, test_funcs, _in_range, _generate_scalars ) -{ - // inherit the default parameters from arithmerical test - size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -class CxCore_CmpTest : public CxCore_CmpBaseTest -{ -public: - CxCore_CmpTest(); -protected: - void run_func(); -}; - -CxCore_CmpTest::CxCore_CmpTest() - : CxCore_CmpBaseTest( "cmp-cmp", "cvCmp", 0, 0 ) -{ -} - -void CxCore_CmpTest::run_func() -{ - if(!test_nd) - { - cvCmp( test_array[INPUT][0], test_array[INPUT][1], - test_array[OUTPUT][0], cmp_op ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::compare(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - c, cmp_op); - } -} - -CxCore_CmpTest cmp_test; - - -class CxCore_CmpSTest : public CxCore_CmpBaseTest -{ -public: - CxCore_CmpSTest(); -protected: - void run_func(); -}; - -CxCore_CmpSTest::CxCore_CmpSTest() - : CxCore_CmpBaseTest( "cmp-cmps", "cvCmpS", 0, 4 ) -{ -} - -void CxCore_CmpSTest::run_func() -{ - if(!test_nd) - { - cvCmpS( test_array[INPUT][0], gamma.val[0], - test_array[OUTPUT][0], cmp_op ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::compare(cv::cvarrToMatND(test_array[INPUT][0]), - gamma.val[0], c, cmp_op); - } -} - -CxCore_CmpSTest cmps_test; - - -class CxCore_InRangeTest : public CxCore_CmpBaseTest -{ -public: - CxCore_InRangeTest(); -protected: - void run_func(); -}; - -CxCore_InRangeTest::CxCore_InRangeTest() - : CxCore_CmpBaseTest( "cmp-inrange", "cvInRange", 1, 0 ) -{ -} - -void CxCore_InRangeTest::run_func() -{ - if(!test_nd) - { - cvInRange( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT][2], test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::inRange(cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[INPUT][1]), - cv::cvarrToMatND(test_array[INPUT][2]), - c); - } -} - -CxCore_InRangeTest inrange_test; - - -class CxCore_InRangeSTest : public CxCore_CmpBaseTest -{ -public: - CxCore_InRangeSTest(); -protected: - void run_func(); -}; - -CxCore_InRangeSTest::CxCore_InRangeSTest() - : CxCore_CmpBaseTest( "cmp-inranges", "cvInRangeS", 1, 5 ) -{ -} - -void CxCore_InRangeSTest::run_func() -{ - if(!test_nd) - { - cvInRangeS( test_array[INPUT][0], alpha, gamma, test_array[OUTPUT][0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::inRange(cv::cvarrToMatND(test_array[INPUT][0]), alpha, gamma, c); - } -} - -CxCore_InRangeSTest inranges_test; - - -/////////////////////////// convertscale[abs] //////////////////////////////////////// - -static const char* cvt_param_names[] = { "size", "scale", "dst_depth", "depth", 0 }; -static const char* cvt_abs_param_names[] = { "size", "depth", 0 }; -static const int cvt_scale_flags[] = { 0, 1 }; - -class CxCore_CvtBaseTestImpl : public CxCore_ArithmTestImpl -{ -public: - CxCore_CvtBaseTestImpl( const char* test_name, const char* test_funcs, bool calc_abs ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int prepare_test_case( int test_case_idx ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int write_default_params( CvFileStorage* fs ); - - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_CvtBaseTestImpl::CxCore_CvtBaseTestImpl( const char* test_name, - const char* test_funcs, - bool _calc_abs ) - : CxCore_ArithmTestImpl( test_name, test_funcs, 5, false, _calc_abs ) -{ - test_array[INPUT].pop(); - default_timing_param_names = 0; - cn_list = 0; -} - - -// unlike many other arithmetic functions, conversion operations support 8s type, -// also, for cvCvtScale output array depth may be arbitrary and -// for cvCvtScaleAbs output depth = CV_8U -void CxCore_CvtBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CxCore_ArithmTestImpl::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvRNG* rng = ts->get_rng(); - int depth = CV_8U, rbits; - types[INPUT][0] = (types[INPUT][0] & ~CV_MAT_DEPTH_MASK)| - cvTsRandInt(rng)%(CV_64F+1); - if( !calc_abs ) - depth = cvTsRandInt(rng) % (CV_64F+1); - types[OUTPUT][0] = types[REF_OUTPUT][0] = (types[INPUT][0] & ~CV_MAT_DEPTH_MASK)|depth; - - rbits = cvTsRandInt(rng); - // check special cases: shift=0 and/or scale=1. - if( (rbits & 3) == 0 ) - gamma.val[0] = 0; - if( (rbits & 12) == 0 ) - alpha.val[0] = 1; -} - - -double CxCore_CvtBaseTestImpl::get_success_error_level( int, int, int ) -{ - if( CV_MAT_DEPTH(test_mat[OUTPUT][0].type) <= CV_32S ) - return alpha.val[0] != cvRound(alpha.val[0]) || - beta.val[0] != cvRound(beta.val[0]) || - gamma.val[0] != cvRound(gamma.val[0]); - - CvScalar l1, h1, l2, h2; - int stype = CV_MAT_TYPE(test_mat[INPUT][0].type); - int dtype = CV_MAT_TYPE(test_mat[OUTPUT][0].type); - get_minmax_bounds( INPUT, 0, stype, &l1, &h1 ); - get_minmax_bounds( OUTPUT, 0, dtype, &l2, &h2 ); - double maxval = 0; - for( int i = 0; i < 4; i++ ) - { - maxval = MAX(maxval, fabs(l1.val[i])); - maxval = MAX(maxval, fabs(h1.val[i])); - maxval = MAX(maxval, fabs(l2.val[i])); - maxval = MAX(maxval, fabs(h2.val[i])); - } - double max_err = (CV_MAT_DEPTH(stype) == CV_64F || CV_MAT_DEPTH(dtype) == CV_64F ? - DBL_EPSILON : FLT_EPSILON)*maxval*MAX(fabs(alpha.val[0]), 1.)*100; - return max_err; -} - - -void CxCore_CvtBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CxCore_ArithmTestImpl::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - bool scale = true; - int dst_depth = CV_8U; - int cn = CV_MAT_CN(types[INPUT][0]); - if( !calc_abs ) - { - scale = cvReadInt( find_timing_param( "scale" ), 1 ) != 0; - dst_depth = cvTsTypeByName( cvReadString(find_timing_param( "dst_depth" ), "8u") ); - } - - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(dst_depth, cn); - - if( scale ) - { - alpha.val[0] = 2.1; - gamma.val[0] = -100.; - } - else - { - alpha.val[0] = 1.; - gamma.val[0] = 0.; - } -} - - -int CxCore_CvtBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_ArithmTestImpl::prepare_test_case( test_case_idx ); - - if( code > 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - if( CV_ARE_TYPES_EQ( &test_mat[INPUT][0], &test_mat[OUTPUT][0] ) && - !calc_abs && alpha.val[0] == 1 && gamma.val[0] == 0 ) - code = 0; // skip the case when no any transformation is done - } - - return code; -} - - -void CxCore_CvtBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", alpha.val[0] == 1. && gamma.val[0] == 0. ? "no_scale" : "scale" ); - ptr += strlen(ptr); - params_left--; - CxCore_ArithmTestImpl::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_CvtBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int i, code = CxCore_ArithmTestImpl::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - if( !calc_abs ) - { - start_write_param( fs ); - cvStartWriteStruct( fs, "dst_depth", CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; arithm_depths[i] >= 0; i++ ) - cvWriteString( fs, 0, cvTsGetTypeName(arithm_depths[i]) ); - cvEndWriteStruct(fs); - write_int_list( fs, "scale", cvt_scale_flags, CV_DIM(cvt_scale_flags) ); - } - return code; -} - - -void CxCore_CvtBaseTestImpl::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvTsAdd( &test_mat[INPUT][0], cvScalarAll(alpha.val[0]), 0, beta, - cvScalarAll(gamma.val[0]), &test_mat[REF_OUTPUT][0], calc_abs ); -} - -CxCore_CvtBaseTestImpl cvt_test( "cvt", "", true ); - - -class CxCore_CvtBaseTest : public CxCore_CvtBaseTestImpl -{ -public: - CxCore_CvtBaseTest( const char* test_name, const char* test_funcs, bool calc_abs ); -}; - - -CxCore_CvtBaseTest::CxCore_CvtBaseTest( const char* test_name, const char* test_funcs, bool _calc_abs ) - : CxCore_CvtBaseTestImpl( test_name, test_funcs, _calc_abs ) -{ - // inherit the default parameters from arithmerical test - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - - -class CxCore_CvtScaleTest : public CxCore_CvtBaseTest -{ -public: - CxCore_CvtScaleTest(); -protected: - void run_func(); -}; - -CxCore_CvtScaleTest::CxCore_CvtScaleTest() - : CxCore_CvtBaseTest( "cvt-scale", "cvCvtScale", false ) -{ - default_timing_param_names = cvt_param_names; -} - -void CxCore_CvtScaleTest::run_func() -{ - if(!test_nd) - { - cvConvertScale( test_array[INPUT][0], test_array[OUTPUT][0], - alpha.val[0], gamma.val[0] ); - } - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::cvarrToMatND(test_array[INPUT][0]).convertTo(c,c.type(),alpha.val[0], gamma.val[0]); - } -} - -CxCore_CvtScaleTest cvtscale_test; - - -class CxCore_CvtScaleAbsTest : public CxCore_CvtBaseTest -{ -public: - CxCore_CvtScaleAbsTest(); -protected: - void run_func(); -}; - -CxCore_CvtScaleAbsTest::CxCore_CvtScaleAbsTest() - : CxCore_CvtBaseTest( "cvt-scaleabs", "cvCvtScaleAbs", true ) -{ - default_timing_param_names = cvt_abs_param_names; -} - -void CxCore_CvtScaleAbsTest::run_func() -{ - if(!test_nd) - { - cvConvertScaleAbs( test_array[INPUT][0], test_array[OUTPUT][0], - alpha.val[0], gamma.val[0] ); - } - else - { - cv::Mat c = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::convertScaleAbs(cv::cvarrToMat(test_array[INPUT][0]),c,alpha.val[0], gamma.val[0]); - } -} - -CxCore_CvtScaleAbsTest cvtscaleabs_test; - - -/////////////////////////////// statistics ////////////////////////////////// - -static const char* stat_param_names[] = { "size", "coi", "channels", "depth", 0 }; -static const char* stat_mask_param_names[] = { "size", "coi", "channels", "depth", "use_mask", 0 }; -static const char* stat_single_param_names[] = { "size", "channels", "depth", 0 }; -static const char* stat_single_mask_param_names[] = { "size", "channels", "depth", "use_mask", 0 }; -static const char* stat_coi_modes[] = { "all", "single", 0 }; - -class CxCore_StatTestImpl : public CvArrTest -{ -public: - CxCore_StatTestImpl( const char* test_name, const char* test_funcs, - int _output_count, bool _single_channel, - bool _allow_mask=true, bool _is_binary=false ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int write_default_params( CvFileStorage* fs ); - int prepare_test_case( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); - - int coi; - int output_count; - bool single_channel; - bool is_binary; - bool test_nd; -}; - - -CxCore_StatTestImpl::CxCore_StatTestImpl( const char* test_name, - const char* test_funcs, int _output_count, - bool _single_channel, bool _allow_mask, bool _is_binary ) - : CvArrTest( test_name, test_funcs, "" ), output_count(_output_count), - single_channel(_single_channel), is_binary(_is_binary) -{ - test_array[INPUT].push(NULL); - if( is_binary ) - test_array[INPUT].push(NULL); - optional_mask = _allow_mask; - if( optional_mask ) - test_array[MASK].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - coi = 0; - - size_list = arithm_sizes; - whole_size_list = arithm_whole_sizes; - depth_list = arithm_depths; - cn_list = arithm_channels; - test_nd = false; -} - - -void CxCore_StatTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng)%(CV_64F+1); - int cn = cvTsRandInt(rng) % 4 + 1; - int j, count = test_array[INPUT].size(); - - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth += depth == CV_8S; - - for( j = 0; j < count; j++ ) - types[INPUT][j] = CV_MAKETYPE(depth, cn); - - // regardless of the test case, the output is always a fixed-size tuple of numbers - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize( output_count, 1 ); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - - coi = 0; - cvmat_allowed = true; - if( cn > 1 && (single_channel || (cvTsRandInt(rng) & 3) == 0) ) - { - coi = cvTsRandInt(rng) % cn + 1; - cvmat_allowed = false; - } - test_nd = cvTsRandInt(rng) % 3 == 0; -} - - -void CxCore_StatTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - const char* coi_mode_str = cvReadString(find_timing_param("coi"), single_channel ? "single" : "all"); - - // regardless of the test case, the output is always a fixed-size tuple of numbers - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize( output_count, 1 ); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - - int cn = CV_MAT_CN(types[INPUT][0]); - coi = 0; - cvmat_allowed = true; - if( strcmp( coi_mode_str, "single" ) == 0 ) - { - CvRNG* rng = ts->get_rng(); - coi = cvTsRandInt(rng) % cn + 1; - cvmat_allowed = false; - *are_images = true; - } -} - - -int CxCore_StatTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - if( !single_channel ) - write_string_list( fs, "coi", stat_coi_modes ); - return code; -} - - -int CxCore_StatTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - - if( coi && code > 0 ) - { - int j, count = test_array[INPUT].size(); - - if( ts->get_testing_mode() == CvTS::TIMING_MODE && CV_MAT_CN(test_mat[INPUT][0].type) == 1 ) - return 0; - - for( j = 0; j < count; j++ ) - { - IplImage* img = (IplImage*)test_array[INPUT][j]; - if( img ) - cvSetImageCOI( img, coi ); - } - } - - return code; -} - - -void CxCore_StatTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", coi > 0 || CV_MAT_CN(test_mat[INPUT][0].type) == 1 ? "single" : "all" ); - ptr += strlen(ptr); - params_left--; - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_StatTestImpl::get_success_error_level( int test_case_idx, int i, int j ) -{ - int depth = CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])); - if( depth == CV_32F ) - return FLT_EPSILON*1000; - if( depth == CV_64F ) - return DBL_EPSILON*100000; - else - return CvArrTest::get_success_error_level( test_case_idx, i, j ); -} - -CxCore_StatTestImpl stat_test( "stat", "", 0, true, false ); - - -class CxCore_StatTest : public CxCore_StatTestImpl -{ -public: - CxCore_StatTest( const char* test_name, const char* test_funcs, - int _output_count, bool _single_channel, - bool _allow_mask=1, bool _is_binary=0 ); -}; - -CxCore_StatTest::CxCore_StatTest( const char* test_name, const char* test_funcs, - int _output_count, bool _single_channel, - bool _allow_mask, bool _is_binary ) - : CxCore_StatTestImpl( test_name, test_funcs, _output_count, _single_channel, _allow_mask, _is_binary ) -{ - if( !single_channel ) - default_timing_param_names = optional_mask ? stat_single_mask_param_names : stat_single_param_names; - else - default_timing_param_names = optional_mask ? stat_mask_param_names : stat_param_names; - - // inherit the default parameters from arithmerical test - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; -} - -////////////////// sum ///////////////// -class CxCore_SumTest : public CxCore_StatTest -{ -public: - CxCore_SumTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CxCore_SumTest::CxCore_SumTest() - : CxCore_StatTest( "stat-sum", "cvSum", 4 /* CvScalar */, false, false, false ) -{ -} - -double CxCore_SumTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])); - if( depth == CV_32F ) - return FLT_EPSILON*1000; - return DBL_EPSILON*100000; -} - - -void CxCore_SumTest::run_func() -{ - if(!test_nd || coi) - { - *(CvScalar*)(test_mat[OUTPUT][0].data.db) = cvSum(test_array[INPUT][0]); - } - else - { - *(cv::Scalar*)(test_mat[OUTPUT][0].data.db) = cv::sum(cv::cvarrToMatND(test_array[INPUT][0])); - } -} - -void CxCore_SumTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvScalar mean; - int nonzero = cvTsMeanStdDevNonZero( &test_mat[INPUT][0], 0, &mean, 0, coi ); - - *(CvScalar*)(test_mat[REF_OUTPUT][0].data.db) = mean; - mean = *(CvScalar*)(test_mat[OUTPUT][0].data.db); - - mean.val[0] /= nonzero; - mean.val[1] /= nonzero; - mean.val[2] /= nonzero; - mean.val[3] /= nonzero; - *(CvScalar*)(test_mat[OUTPUT][0].data.db) = mean; -} - -CxCore_SumTest sum_test; - - -////////////////// nonzero ///////////////// -class CxCore_NonZeroTest : public CxCore_StatTest -{ -public: - CxCore_NonZeroTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ); -}; - - -CxCore_NonZeroTest::CxCore_NonZeroTest() - : CxCore_StatTest( "stat-nonzero", "cvCountNonZero", 1 /* int */, true, false, false ) -{ - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); -} - -void CxCore_NonZeroTest::run_func() -{ - if(!test_nd || coi) - { - test_mat[OUTPUT][0].data.db[0] = cvCountNonZero(test_array[INPUT][0]); - } - else - { - test_mat[OUTPUT][0].data.db[0] = cv::countNonZero(cv::cvarrToMatND(test_array[INPUT][0])); - } -} - -void CxCore_NonZeroTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CxCore_StatTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[TEMP][0] = CV_8UC1; - if( CV_MAT_CN(types[INPUT][0]) > 1 ) - types[TEMP][1] = types[INPUT][0] & ~CV_MAT_CN_MASK; - else - sizes[TEMP][1] = cvSize(0,0); -} - - -void CxCore_NonZeroTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* plane = &test_mat[INPUT][0]; - if( CV_MAT_CN(plane->type) > 1 ) - { - plane = &test_mat[TEMP][1]; - assert( coi > 0 ); - cvTsExtract( &test_mat[INPUT][0], plane, coi-1 ); - } - cvTsCmpS( plane, 0, &test_mat[TEMP][0], CV_CMP_NE ); - int nonzero = cvTsMeanStdDevNonZero( &test_mat[INPUT][0], &test_mat[TEMP][0], 0, 0, coi ); - test_mat[REF_OUTPUT][0].data.db[0] = nonzero; -} - - -CxCore_NonZeroTest nonzero_test; - - -/////////////////// mean ////////////////////// -class CxCore_MeanTest : public CxCore_StatTest -{ -public: - CxCore_MeanTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_MeanTest::CxCore_MeanTest() - : CxCore_StatTest( "stat-mean", "cvAvg", 4 /* CvScalar */, false, true, false ) -{ -} - -void CxCore_MeanTest::run_func() -{ - if(!test_nd || coi) - { - *(CvScalar*)(test_mat[OUTPUT][0].data.db) = - cvAvg(test_array[INPUT][0], test_array[MASK][0]); - } - else - { - *(cv::Scalar*)(test_mat[OUTPUT][0].data.db) = cv::mean( - cv::cvarrToMatND(test_array[INPUT][0]), - cv::cvarrToMatND(test_array[MASK][0])); - } -} - -void CxCore_MeanTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvScalar mean; - cvTsMeanStdDevNonZero( &test_mat[INPUT][0], - test_array[MASK][0] ? &test_mat[MASK][0] : 0, - &mean, 0, coi ); - *(CvScalar*)(test_mat[REF_OUTPUT][0].data.db) = mean; -} - -CxCore_MeanTest mean_test; - - -/////////////////// mean_stddev ////////////////////// -class CxCore_MeanStdDevTest : public CxCore_StatTest -{ -public: - CxCore_MeanStdDevTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CxCore_MeanStdDevTest::CxCore_MeanStdDevTest() - : CxCore_StatTest( "stat-mean_stddev", "cvAvgSdv", 8 /* CvScalar x 2 */, false, true, false ) -{ -} - -void CxCore_MeanStdDevTest::run_func() -{ - if(!test_nd || coi) - { - cvAvgSdv( test_array[INPUT][0], - &((CvScalar*)(test_mat[OUTPUT][0].data.db))[0], - &((CvScalar*)(test_mat[OUTPUT][0].data.db))[1], - test_array[MASK][0] ); - } - else - { - cv::meanStdDev(cv::cvarrToMatND(test_array[INPUT][0]), - ((cv::Scalar*)(test_mat[OUTPUT][0].data.db))[0], - ((cv::Scalar*)(test_mat[OUTPUT][0].data.db))[1], - cv::cvarrToMatND(test_array[MASK][0]) ); - } -} - -double CxCore_MeanStdDevTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int depth = CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])); - if( depth < CV_64F && depth != CV_32S ) - return CxCore_StatTest::get_success_error_level( test_case_idx, i, j ); - return DBL_EPSILON*1e6; -} - -void CxCore_MeanStdDevTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvScalar mean, stddev; - int i; - CvMat* output = &test_mat[OUTPUT][0]; - CvMat* ref_output = &test_mat[REF_OUTPUT][0]; - cvTsMeanStdDevNonZero( &test_mat[INPUT][0], - test_array[MASK][0] ? &test_mat[MASK][0] : 0, - &mean, &stddev, coi ); - ((CvScalar*)(ref_output->data.db))[0] = mean; - ((CvScalar*)(ref_output->data.db))[1] = stddev; - for( i = 0; i < 4; i++ ) - { - output->data.db[i] *= output->data.db[i]; - output->data.db[i+4] = output->data.db[i+4]*output->data.db[i+4] + 1000; - ref_output->data.db[i] *= ref_output->data.db[i]; - ref_output->data.db[i+4] = ref_output->data.db[i+4]*ref_output->data.db[i+4] + 1000; - } -} - -CxCore_MeanStdDevTest mean_stddev_test; - - -/////////////////// minmaxloc ////////////////////// -class CxCore_MinMaxLocTest : public CxCore_StatTest -{ -public: - CxCore_MinMaxLocTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_MinMaxLocTest::CxCore_MinMaxLocTest() - : CxCore_StatTest( "stat-minmaxloc", "cvMinMaxLoc", 6 /* double x 2 + CvPoint x 2 */, true, true, false ) -{ -} - -void CxCore_MinMaxLocTest::run_func() -{ - CvPoint minloc = {0,0}, maxloc = {0,0}; - double* output = test_mat[OUTPUT][0].data.db; - - cvMinMaxLoc( test_array[INPUT][0], - output, output+1, &minloc, &maxloc, - test_array[MASK][0] ); - output[2] = minloc.x; - output[3] = minloc.y; - output[4] = maxloc.x; - output[5] = maxloc.y; -} - -void CxCore_MinMaxLocTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - double minval = 0, maxval = 0; - CvPoint minloc = {0,0}, maxloc = {0,0}; - double* ref_output = test_mat[REF_OUTPUT][0].data.db; - cvTsMinMaxLoc( &test_mat[INPUT][0], test_array[MASK][0] ? - &test_mat[MASK][0] : 0, &minval, &maxval, &minloc, &maxloc, coi ); - ref_output[0] = minval; - ref_output[1] = maxval; - ref_output[2] = minloc.x; - ref_output[3] = minloc.y; - ref_output[4] = maxloc.x; - ref_output[5] = maxloc.y; -} - -CxCore_MinMaxLocTest minmaxloc_test; - - -/////////////////// norm ////////////////////// - -static const char* stat_norm_param_names[] = { "size", "coi", "norm_type", "channels", "depth", "use_mask", 0 }; -static const char* stat_norm_type_names[] = { "Inf", "L1", "L2", "diff_Inf", "diff_L1", "diff_L2", 0 }; - -class CxCore_NormTest : public CxCore_StatTest -{ -public: - CxCore_NormTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int /*test_case_idx*/, - CvSize** sizes, int** types, CvSize** whole_sizes, bool *are_images ); - int prepare_test_case( int test_case_idx ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int write_default_params( CvFileStorage* fs ); - double get_success_error_level( int test_case_idx, int i, int j ); - int norm_type; -}; - - -CxCore_NormTest::CxCore_NormTest() - : CxCore_StatTest( "stat-norm", "cvNorm", 1 /* double */, false, true, true ) -{ - test_array[TEMP].push(NULL); - default_timing_param_names = stat_norm_param_names; -} - - -double CxCore_NormTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int depth = CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])); - if( (depth == CV_16U || depth == CV_16S) /*&& (norm_type&3) != CV_C*/ ) - return 1e-4; - else - return CxCore_StatTest::get_success_error_level( test_case_idx, i, j ); -} - - -void CxCore_NormTest::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - int intype; - int norm_kind; - CxCore_StatTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - norm_type = cvTsRandInt(ts->get_rng()) % 3; // CV_C, CV_L1 or CV_L2 - norm_kind = cvTsRandInt(ts->get_rng()) % 3; // simple, difference or relative difference - if( norm_kind == 0 ) - sizes[INPUT][1] = cvSize(0,0); - norm_type = (1 << norm_type) | (norm_kind*8); - intype = types[INPUT][0]; - if( CV_MAT_CN(intype) > 1 && coi == 0 ) - sizes[MASK][0] = cvSize(0,0); - sizes[TEMP][0] = cvSize(0,0); - if( (norm_type & (CV_DIFF|CV_RELATIVE)) && CV_MAT_DEPTH(intype) <= CV_32F ) - { - sizes[TEMP][0] = sizes[INPUT][0]; - types[TEMP][0] = (intype & ~CV_MAT_DEPTH_MASK)| - (CV_MAT_DEPTH(intype) < CV_32F ? CV_32S : CV_64F); - } -} - - -void CxCore_NormTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_StatTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* norm_type_str = cvReadString( find_timing_param( "norm_type" ), "L2" ); - bool diff = false; - if( strncmp( norm_type_str, "diff_", 5 ) == 0 ) - { - diff = true; - norm_type_str += 5; - } - - if( strcmp( norm_type_str, "L1" ) == 0 ) - norm_type = CV_L1; - else if( strcmp( norm_type_str, "L2" ) == 0 ) - norm_type = CV_L2; - else - norm_type = CV_C; - - if( diff ) - norm_type += CV_DIFF; - else - sizes[INPUT][1] = cvSize(0,0); -} - - -int CxCore_NormTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_StatTest::prepare_test_case( test_case_idx ); - if( code > 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - // currently it is not supported - if( test_array[MASK][0] && CV_MAT_CN(test_mat[INPUT][0].type) > 1 && coi == 0 ) - return 0; - } - return code; -} - - -int CxCore_NormTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_StatTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "norm_type", stat_norm_type_names ); - return code; -} - - -void CxCore_NormTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - int nt = norm_type & CV_NORM_MASK; - sprintf( ptr, "%s%s,", norm_type & CV_DIFF ? "diff_" : "", - nt == CV_C ? "Inf" : nt == CV_L1 ? "L1" : "L2" ); - ptr += strlen(ptr); - params_left--; - CxCore_StatTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CxCore_NormTest::run_func() -{ - if(!test_nd || coi) - { - test_mat[OUTPUT][0].data.db[0] = cvNorm( test_array[INPUT][0], - test_array[INPUT][1], norm_type, test_array[MASK][0] ); - } - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[INPUT][1]); - cv::MatND mask = cv::cvarrToMatND(test_array[MASK][0]); - test_mat[OUTPUT][0].data.db[0] = b.data ? - cv::norm( a, b, norm_type, mask ) : - cv::norm( a, norm_type, mask ); - } -} - -void CxCore_NormTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - double a_norm = 0, b_norm = 0; - CvMat* a = &test_mat[INPUT][0]; - CvMat* b = &test_mat[INPUT][1]; - CvMat* mask = test_array[MASK][0] ? &test_mat[MASK][0] : 0; - CvMat* diff = a; - - if( norm_type & (CV_DIFF|CV_RELATIVE) ) - { - diff = test_array[TEMP][0] ? &test_mat[TEMP][0] : a; - cvTsAdd( a, cvScalarAll(1.), b, cvScalarAll(-1.), - cvScalarAll(0.), diff, 0 ); - } - a_norm = cvTsNorm( diff, mask, norm_type & CV_NORM_MASK, coi ); - if( norm_type & CV_RELATIVE ) - { - b_norm = cvTsNorm( b, mask, norm_type & CV_NORM_MASK, coi ); - a_norm /= (b_norm + DBL_EPSILON ); - } - test_mat[REF_OUTPUT][0].data.db[0] = a_norm; -} - -CxCore_NormTest norm_test; - -// TODO: repeat(?), reshape(?), lut - -/* End of file. */ diff --git a/tests/cxcore/src/aarray.cpp b/tests/cxcore/src/aarray.cpp deleted file mode 100644 index e461ef5..0000000 --- a/tests/cxcore/src/aarray.cpp +++ /dev/null @@ -1,402 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -////////////////////////////////////////////////////////////////////////////////////////// -////////////////// tests for arithmetic, logic and statistical functions ///////////////// -////////////////////////////////////////////////////////////////////////////////////////// - -#include "cxcoretest.h" -#include -#include - -using namespace cv; -using namespace std; - -class CV_ArrayOpTest : public CvTest -{ -public: - CV_ArrayOpTest(); - ~CV_ArrayOpTest(); -protected: - void run(int); -}; - - -CV_ArrayOpTest::CV_ArrayOpTest() : CvTest( "nd-array-ops", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_ArrayOpTest::~CV_ArrayOpTest() {} - -static string idx2string(const int* idx, int dims) -{ - char buf[256]; - char* ptr = buf; - for( int k = 0; k < dims; k++ ) - { - sprintf(ptr, "%4d ", idx[k]); - ptr += strlen(ptr); - } - ptr[-1] = '\0'; - return string(buf); -} - -static const int* string2idx(const string& s, int* idx, int dims) -{ - const char* ptr = s.c_str(); - for( int k = 0; k < dims; k++ ) - { - int n = 0; - sscanf(ptr, "%d%n", idx + k, &n); - ptr += n; - } - return idx; -} - -static double getValue(SparseMat& M, const int* idx, RNG& rng) -{ - int d = M.dims(); - size_t hv = 0, *phv = 0; - if( (unsigned)rng % 2 ) - { - hv = d == 2 ? M.hash(idx[0], idx[1]) : - d == 3 ? M.hash(idx[0], idx[1], idx[2]) : M.hash(idx); - phv = &hv; - } - - const uchar* ptr = d == 2 ? M.ptr(idx[0], idx[1], false, phv) : - d == 3 ? M.ptr(idx[0], idx[1], idx[2], false, phv) : - M.ptr(idx, false, phv); - return !ptr ? 0 : M.type() == CV_32F ? *(float*)ptr : M.type() == CV_64F ? *(double*)ptr : 0; -} - -static double getValue(const CvSparseMat* M, const int* idx) -{ - int type = 0; - const uchar* ptr = cvPtrND(M, idx, &type, 0); - return !ptr ? 0 : type == CV_32F ? *(float*)ptr : type == CV_64F ? *(double*)ptr : 0; -} - -static void eraseValue(SparseMat& M, const int* idx, RNG& rng) -{ - int d = M.dims(); - size_t hv = 0, *phv = 0; - if( (unsigned)rng % 2 ) - { - hv = d == 2 ? M.hash(idx[0], idx[1]) : - d == 3 ? M.hash(idx[0], idx[1], idx[2]) : M.hash(idx); - phv = &hv; - } - - if( d == 2 ) - M.erase(idx[0], idx[1], phv); - else if( d == 3 ) - M.erase(idx[0], idx[1], idx[2], phv); - else - M.erase(idx, phv); -} - -static void eraseValue(CvSparseMat* M, const int* idx) -{ - cvClearND(M, idx); -} - -static void setValue(SparseMat& M, const int* idx, double value, RNG& rng) -{ - int d = M.dims(); - size_t hv = 0, *phv = 0; - if( (unsigned)rng % 2 ) - { - hv = d == 2 ? M.hash(idx[0], idx[1]) : - d == 3 ? M.hash(idx[0], idx[1], idx[2]) : M.hash(idx); - phv = &hv; - } - - uchar* ptr = d == 2 ? M.ptr(idx[0], idx[1], true, phv) : - d == 3 ? M.ptr(idx[0], idx[1], idx[2], true, phv) : - M.ptr(idx, true, phv); - if( M.type() == CV_32F ) - *(float*)ptr = (float)value; - else if( M.type() == CV_64F ) - *(double*)ptr = value; - else - CV_Error(CV_StsUnsupportedFormat, ""); -} - -void CV_ArrayOpTest::run( int /* start_from */) -{ - int errcount = 0; - - // dense matrix operations - { - int sz3[] = {5, 10, 15}; - MatND A(3, sz3, CV_32F), B(3, sz3, CV_16SC4); - CvMatND matA = A, matB = B; - RNG rng; - rng.fill(A, CV_RAND_UNI, Scalar::all(-10), Scalar::all(10)); - rng.fill(B, CV_RAND_UNI, Scalar::all(-10), Scalar::all(10)); - - int idx0[] = {3,4,5}, idx1[] = {0, 9, 7}; - float val0 = 130; - Scalar val1(-1000, 30, 3, 8); - cvSetRealND(&matA, idx0, val0); - cvSetReal3D(&matA, idx1[0], idx1[1], idx1[2], -val0); - cvSetND(&matB, idx0, val1); - cvSet3D(&matB, idx1[0], idx1[1], idx1[2], -val1); - Ptr matC = cvCloneMatND(&matB); - - if( A.at(idx0[0], idx0[1], idx0[2]) != val0 || - A.at(idx1[0], idx1[1], idx1[2]) != -val0 || - cvGetReal3D(&matA, idx0[0], idx0[1], idx0[2]) != val0 || - cvGetRealND(&matA, idx1) != -val0 || - - Scalar(B.at(idx0[0], idx0[1], idx0[2])) != val1 || - Scalar(B.at(idx1[0], idx1[1], idx1[2])) != -val1 || - Scalar(cvGet3D(matC, idx0[0], idx0[1], idx0[2])) != val1 || - Scalar(cvGetND(matC, idx1)) != -val1 ) - { - ts->printf(CvTS::LOG, "one of cvSetReal3D, cvSetRealND, cvSet3D, cvSetND " - "or the corresponding *Get* functions is not correct\n"); - errcount++; - } - } - - RNG rng; - const int MAX_DIM = 5, MAX_DIM_SZ = 10; - // sparse matrix operations - for( int si = 0; si < 10; si++ ) - { - int depth = (unsigned)rng % 2 == 0 ? CV_32F : CV_64F; - int dims = ((unsigned)rng % MAX_DIM) + 1; - int i, k, size[MAX_DIM]={0}, idx[MAX_DIM]={0}; - vector all_idxs; - vector all_vals; - vector all_vals2; - string sidx, min_sidx, max_sidx; - double min_val=0, max_val=0; - - int p = 1; - for( k = 0; k < dims; k++ ) - { - size[k] = ((unsigned)rng % MAX_DIM_SZ) + 1; - p *= size[k]; - } - SparseMat M( dims, size, depth ); - map M0; - - int nz0 = (unsigned)rng % max(p/5,10); - nz0 = min(max(nz0, 1), p); - all_vals.resize(nz0); - all_vals2.resize(nz0); - Mat_ _all_vals(all_vals), _all_vals2(all_vals2); - rng.fill(_all_vals, CV_RAND_UNI, Scalar(-1000), Scalar(1000)); - if( depth == CV_32F ) - { - Mat _all_vals_f; - _all_vals.convertTo(_all_vals_f, CV_32F); - _all_vals_f.convertTo(_all_vals, CV_64F); - } - _all_vals.convertTo(_all_vals2, _all_vals2.type(), 2); - if( depth == CV_32F ) - { - Mat _all_vals2_f; - _all_vals2.convertTo(_all_vals2_f, CV_32F); - _all_vals2_f.convertTo(_all_vals2, CV_64F); - } - - minMaxLoc(_all_vals, &min_val, &max_val); - double _norm0 = norm(_all_vals, CV_C); - double _norm1 = norm(_all_vals, CV_L1); - double _norm2 = norm(_all_vals, CV_L2); - - for( i = 0; i < nz0; i++ ) - { - for(;;) - { - for( k = 0; k < dims; k++ ) - idx[k] = (unsigned)rng % size[k]; - sidx = idx2string(idx, dims); - if( M0.count(sidx) == 0 ) - break; - } - all_idxs.push_back(sidx); - M0[sidx] = all_vals[i]; - if( all_vals[i] == min_val ) - min_sidx = sidx; - if( all_vals[i] == max_val ) - max_sidx = sidx; - setValue(M, idx, all_vals[i], rng); - double v = getValue(M, idx, rng); - if( v != all_vals[i] ) - { - ts->printf(CvTS::LOG, "%d. immediately after SparseMat[%s]=%.20g the current value is %.20g\n", - i, sidx.c_str(), all_vals[i], v); - errcount++; - break; - } - } - - Ptr M2 = (CvSparseMat*)M; - MatND Md; - M.copyTo(Md); - SparseMat M3; SparseMat(Md).convertTo(M3, Md.type(), 2); - - int nz1 = (int)M.nzcount(), nz2 = (int)M3.nzcount(); - double norm0 = norm(M, CV_C); - double norm1 = norm(M, CV_L1); - double norm2 = norm(M, CV_L2); - double eps = depth == CV_32F ? FLT_EPSILON*100 : DBL_EPSILON*1000; - - if( nz1 != nz0 || nz2 != nz0) - { - errcount++; - ts->printf(CvTS::LOG, "%d: The number of non-zero elements before/after converting to/from dense matrix is not correct: %d/%d (while it should be %d)\n", - si, nz1, nz2, nz0 ); - break; - } - - if( fabs(norm0 - _norm0) > fabs(_norm0)*eps || - fabs(norm1 - _norm1) > fabs(_norm1)*eps || - fabs(norm2 - _norm2) > fabs(_norm2)*eps ) - { - errcount++; - ts->printf(CvTS::LOG, "%d: The norms are different: %.20g/%.20g/%.20g vs %.20g/%.20g/%.20g\n", - si, norm0, norm1, norm2, _norm0, _norm1, _norm2 ); - break; - } - - int n = (unsigned)rng % max(p/5,10); - n = min(max(n, 1), p) + nz0; - - for( i = 0; i < n; i++ ) - { - double val1, val2, val3, val0; - if(i < nz0) - { - sidx = all_idxs[i]; - string2idx(sidx, idx, dims); - val0 = all_vals[i]; - } - else - { - for( k = 0; k < dims; k++ ) - idx[k] = (unsigned)rng % size[k]; - sidx = idx2string(idx, dims); - val0 = M0[sidx]; - } - val1 = getValue(M, idx, rng); - val2 = getValue(M2, idx); - val3 = getValue(M3, idx, rng); - - if( val1 != val0 || val2 != val0 || fabs(val3 - val0*2) > fabs(val0*2)*FLT_EPSILON ) - { - errcount++; - ts->printf(CvTS::LOG, "SparseMat M[%s] = %g/%g/%g (while it should be %g)\n", sidx.c_str(), val1, val2, val3, val0 ); - break; - } - } - - for( i = 0; i < n; i++ ) - { - double val1, val2; - if(i < nz0) - { - sidx = all_idxs[i]; - string2idx(sidx, idx, dims); - } - else - { - for( k = 0; k < dims; k++ ) - idx[k] = (unsigned)rng % size[k]; - sidx = idx2string(idx, dims); - } - eraseValue(M, idx, rng); - eraseValue(M2, idx); - val1 = getValue(M, idx, rng); - val2 = getValue(M2, idx); - if( val1 != 0 || val2 != 0 ) - { - errcount++; - ts->printf(CvTS::LOG, "SparseMat: after deleting M[%s], it is =%g/%g (while it should be 0)\n", sidx.c_str(), val1, val2 ); - break; - } - } - - int nz = (int)M.nzcount(); - if( nz != 0 ) - { - errcount++; - ts->printf(CvTS::LOG, "The number of non-zero elements after removing all the elements = %d (while it should be 0)\n", nz ); - break; - } - - int idx1[MAX_DIM], idx2[MAX_DIM]; - double val1 = 0, val2 = 0; - M3 = SparseMat(Md); - minMaxLoc(M3, &val1, &val2, idx1, idx2); - string s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims); - if( val1 != min_val || val2 != max_val || s1 != min_sidx || s2 != max_sidx ) - { - errcount++; - ts->printf(CvTS::LOG, "%d. Sparse: The value and positions of minimum/maximum elements are different from the reference values and positions:\n\t" - "(%g, %g, %s, %s) vs (%g, %g, %s, %s)\n", si, val1, val2, s1.c_str(), s2.c_str(), - min_val, max_val, min_sidx.c_str(), max_sidx.c_str()); - break; - } - - minMaxLoc(Md, &val1, &val2, idx1, idx2); - s1 = idx2string(idx1, dims), s2 = idx2string(idx2, dims); - if( (min_val < 0 && (val1 != min_val || s1 != min_sidx)) || - (max_val > 0 && (val2 != max_val || s2 != max_sidx)) ) - { - errcount++; - ts->printf(CvTS::LOG, "%d. Dense: The value and positions of minimum/maximum elements are different from the reference values and positions:\n\t" - "(%g, %g, %s, %s) vs (%g, %g, %s, %s)\n", si, val1, val2, s1.c_str(), s2.c_str(), - min_val, max_val, min_sidx.c_str(), max_sidx.c_str()); - break; - } - } - - ts->set_failed_test_info(errcount == 0 ? CvTS::OK : CvTS::FAIL_INVALID_OUTPUT); -} - -CV_ArrayOpTest cv_ArrayOp_test; - diff --git a/tests/cxcore/src/adatastruct.cpp b/tests/cxcore/src/adatastruct.cpp deleted file mode 100644 index fbccab7..0000000 --- a/tests/cxcore/src/adatastruct.cpp +++ /dev/null @@ -1,2342 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// tests for operations on dynamic data structures ///////////////////// -////////////////////////////////////////////////////////////////////////////////////////// - -#include "cxcoretest.h" - -/****************************************************************************************\ -* simple sequence implementation * -\****************************************************************************************/ - -typedef struct CvTsSimpleSeq -{ - schar* array; - int count; - int max_count; - int elem_size; -} -CvTsSimpleSeq; - - -static CvTsSimpleSeq* cvTsCreateSimpleSeq( int max_count, int elem_size ) -{ - CvTsSimpleSeq* seq = (CvTsSimpleSeq*)cvAlloc( sizeof(*seq) + max_count * elem_size ); - seq->elem_size = elem_size; - seq->max_count = max_count; - seq->count = 0; - seq->array = (schar*)(seq + 1); - return seq; -} - - -static void cvTsReleaseSimpleSeq( CvTsSimpleSeq** seq ) -{ - cvFree( seq ); -} - - -static schar* cvTsSimpleSeqElem( CvTsSimpleSeq* seq, int index ) -{ - assert( 0 <= index && index < seq->count ); - return seq->array + index * seq->elem_size; -} - - -static void cvTsClearSimpleSeq( CvTsSimpleSeq* seq ) -{ - seq->count = 0; -} - - -static void cvTsSimpleSeqShiftAndCopy( CvTsSimpleSeq* seq, int from_idx, int to_idx, void* elem=0 ) -{ - int elem_size = seq->elem_size; - - if( from_idx == to_idx ) - return; - assert( (from_idx > to_idx && !elem) || (from_idx < to_idx && elem) ); - - if( from_idx < seq->count ) - { - memmove( seq->array + to_idx*elem_size, seq->array + from_idx*elem_size, - (seq->count - from_idx)*elem_size ); - } - seq->count += to_idx - from_idx; - if( elem && to_idx > from_idx ) - memcpy( seq->array + from_idx*elem_size, elem, (to_idx - from_idx)*elem_size ); -} - -static void cvTsSimpleSeqInvert( CvTsSimpleSeq* seq ) -{ - int i, k, len = seq->count, elem_size = seq->elem_size; - schar *data = seq->array, t; - - for( i = 0; i < len/2; i++ ) - { - schar* a = data + i*elem_size; - schar* b = data + (len - i - 1)*elem_size; - for( k = 0; k < elem_size; k++ ) - CV_SWAP( a[k], b[k], t ); - } -} - -/****************************************************************************************\ -* simple cvset implementation * -\****************************************************************************************/ - -typedef struct CvTsSimpleSet -{ - schar* array; - int count, max_count; - int elem_size; - int* free_stack; - int free_count; -} -CvTsSimpleSet; - - -static void cvTsClearSimpleSet( CvTsSimpleSet* set_header ) -{ - int i; - int elem_size = set_header->elem_size; - - for( i = 0; i < set_header->max_count; i++ ) - { - set_header->array[i*elem_size] = 0; - set_header->free_stack[i] = set_header->max_count - i - 1; - } - set_header->free_count = set_header->max_count; - set_header->count = 0; -} - - -static CvTsSimpleSet* cvTsCreateSimpleSet( int max_count, int elem_size ) -{ - CvTsSimpleSet* set_header = (CvTsSimpleSet*)cvAlloc( sizeof(*set_header) + max_count * - (elem_size + 1 + sizeof(int))); - set_header->elem_size = elem_size + 1; - set_header->max_count = max_count; - set_header->free_stack = (int*)(set_header + 1); - set_header->array = (schar*)(set_header->free_stack + max_count); - - cvTsClearSimpleSet( set_header ); - return set_header; -} - - -static void cvTsReleaseSimpleSet( CvTsSimpleSet** set_header ) -{ - cvFree( set_header ); -} - - -static schar* cvTsSimpleSetFind( CvTsSimpleSet* set_header, int index ) -{ - int idx = index * set_header->elem_size; - assert( 0 <= index && index < set_header->max_count ); - return set_header->array[idx] ? set_header->array + idx + 1 : 0; -} - - -static int cvTsSimpleSetAdd( CvTsSimpleSet* set_header, void* elem ) -{ - int idx, idx2; - assert( set_header->free_count > 0 ); - - idx = set_header->free_stack[--set_header->free_count]; - idx2 = idx * set_header->elem_size; - assert( set_header->array[idx2] == 0 ); - set_header->array[idx2] = 1; - if( set_header->elem_size > 1 ) - memcpy( set_header->array + idx2 + 1, elem, set_header->elem_size - 1 ); - set_header->count = MAX( set_header->count, idx + 1 ); - - return idx; -} - - -static void cvTsSimpleSetRemove( CvTsSimpleSet* set_header, int index ) -{ - assert( set_header->free_count < set_header->max_count && - 0 <= index && index < set_header->max_count ); - assert( set_header->array[index * set_header->elem_size] == 1 ); - - set_header->free_stack[set_header->free_count++] = index; - set_header->array[index * set_header->elem_size] = 0; -} - - -/****************************************************************************************\ -* simple graph implementation * -\****************************************************************************************/ - -typedef struct CvTsSimpleGraph -{ - char* matrix; - int edge_size; - int oriented; - CvTsSimpleSet* vtx; -} -CvTsSimpleGraph; - - -static void cvTsClearSimpleGraph( CvTsSimpleGraph* graph ) -{ - int max_vtx_count = graph->vtx->max_count; - cvTsClearSimpleSet( graph->vtx ); - memset( graph->matrix, 0, max_vtx_count * max_vtx_count * graph->edge_size ); -} - - -static CvTsSimpleGraph* cvTsCreateSimpleGraph( int max_vtx_count, int vtx_size, - int edge_size, int oriented ) -{ - CvTsSimpleGraph* graph; - - assert( max_vtx_count > 1 && vtx_size >= 0 && edge_size >= 0 ); - graph = (CvTsSimpleGraph*)cvAlloc( sizeof(*graph) + - max_vtx_count * max_vtx_count * (edge_size + 1)); - graph->vtx = cvTsCreateSimpleSet( max_vtx_count, vtx_size ); - graph->edge_size = edge_size + 1; - graph->matrix = (char*)(graph + 1); - graph->oriented = oriented; - - cvTsClearSimpleGraph( graph ); - return graph; -} - - -static void cvTsReleaseSimpleGraph( CvTsSimpleGraph** graph ) -{ - if( *graph ) - { - cvTsReleaseSimpleSet( &(graph[0]->vtx) ); - cvFree( graph ); - } -} - - -static int cvTsSimpleGraphAddVertex( CvTsSimpleGraph* graph, void* vertex ) -{ - return cvTsSimpleSetAdd( graph->vtx, vertex ); -} - - -static void cvTsSimpleGraphRemoveVertex( CvTsSimpleGraph* graph, int index ) -{ - int i, max_vtx_count = graph->vtx->max_count; - int edge_size = graph->edge_size; - cvTsSimpleSetRemove( graph->vtx, index ); - - /* remove all the corresponding edges */ - for( i = 0; i < max_vtx_count; i++ ) - { - graph->matrix[(i*max_vtx_count + index)*edge_size] = - graph->matrix[(index*max_vtx_count + i)*edge_size] = 0; - } -} - - -static void cvTsSimpleGraphAddEdge( CvTsSimpleGraph* graph, int idx1, int idx2, void* edge ) -{ - int i, t, n = graph->oriented ? 1 : 2; - - assert( cvTsSimpleSetFind( graph->vtx, idx1 ) && - cvTsSimpleSetFind( graph->vtx, idx2 )); - - for( i = 0; i < n; i++ ) - { - int ofs = (idx1*graph->vtx->max_count + idx2)*graph->edge_size; - assert( graph->matrix[ofs] == 0 ); - graph->matrix[ofs] = 1; - if( graph->edge_size > 1 ) - memcpy( graph->matrix + ofs + 1, edge, graph->edge_size - 1 ); - - CV_SWAP( idx1, idx2, t ); - } -} - - -static void cvTsSimpleGraphRemoveEdge( CvTsSimpleGraph* graph, int idx1, int idx2 ) -{ - int i, t, n = graph->oriented ? 1 : 2; - - assert( cvTsSimpleSetFind( graph->vtx, idx1 ) && - cvTsSimpleSetFind( graph->vtx, idx2 )); - - for( i = 0; i < n; i++ ) - { - int ofs = (idx1*graph->vtx->max_count + idx2)*graph->edge_size; - assert( graph->matrix[ofs] == 1 ); - graph->matrix[ofs] = 0; - CV_SWAP( idx1, idx2, t ); - } -} - - -static schar* cvTsSimpleGraphFindVertex( CvTsSimpleGraph* graph, int index ) -{ - return cvTsSimpleSetFind( graph->vtx, index ); -} - - -static char* cvTsSimpleGraphFindEdge( CvTsSimpleGraph* graph, int idx1, int idx2 ) -{ - if( cvTsSimpleGraphFindVertex( graph, idx1 ) && - cvTsSimpleGraphFindVertex( graph, idx2 )) - { - char* edge = graph->matrix + (idx1 * graph->vtx->max_count + idx2)*graph->edge_size; - if( edge[0] ) return edge + 1; - } - return 0; -} - - -static int cvTsSimpleGraphVertexDegree( CvTsSimpleGraph* graph, int index ) -{ - int i, count = 0; - int edge_size = graph->edge_size; - int max_vtx_count = graph->vtx->max_count; - assert( cvTsSimpleGraphFindVertex( graph, index ) != 0 ); - - for( i = 0; i < max_vtx_count; i++ ) - { - count += graph->matrix[(i*max_vtx_count + index)*edge_size] + - graph->matrix[(index*max_vtx_count + i)*edge_size]; - } - - if( !graph->oriented ) - { - assert( count % 2 == 0 ); - count /= 2; - } - return count; -} - - -///////////////////////////////////// the tests ////////////////////////////////// - -#define CV_TS_SEQ_CHECK_CONDITION( expr, err_msg ) \ - if( !(expr) ) \ - { \ - set_error_context( #expr, err_msg, cvFuncName ); \ - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); \ - EXIT; \ - } - -class CxCore_DynStructBaseTest : public CvTest -{ -public: - CxCore_DynStructBaseTest( const char* test_name, const char* test_funcs ); - virtual ~CxCore_DynStructBaseTest(); - int write_default_params(CvFileStorage* fs); - bool can_do_fast_forward(); - void clear(); - -protected: - int read_params( CvFileStorage* fs ); - void run_func(void); - void set_error_context( const char* condition, - const char* err_msg, - const char* func_name ); - int test_seq_block_consistence( int _struct_idx, CvSeq* seq, int total ); - void update_progressbar(); - - int struct_count, max_struct_size, iterations, generations; - int min_log_storage_block_size, max_log_storage_block_size; - int min_log_elem_size, max_log_elem_size; - int gen, struct_idx, iter; - int test_progress; - int64 start_time; - double cpu_freq; - void** cxcore_struct; - void** simple_struct; - CvMemStorage* storage; -}; - - -CxCore_DynStructBaseTest::CxCore_DynStructBaseTest( const char* test_name, const char* test_funcs ): - CvTest( test_name, test_funcs ) -{ - struct_count = 2; - max_struct_size = 2000; - min_log_storage_block_size = 7; - max_log_storage_block_size = 12; - min_log_elem_size = 0; - max_log_elem_size = 8; - generations = 10; - iterations = max_struct_size*2; - gen = struct_idx = iter = -1; - test_progress = -1; - - storage = 0; - cxcore_struct = 0; - simple_struct = 0; -} - - -CxCore_DynStructBaseTest::~CxCore_DynStructBaseTest() -{ - clear(); -} - - -void CxCore_DynStructBaseTest::run_func() -{ -} - -bool CxCore_DynStructBaseTest::can_do_fast_forward() -{ - return false; -} - - -void CxCore_DynStructBaseTest::clear() -{ - CvTest::clear(); - cvReleaseMemStorage( &storage ); - cvFree( &cxcore_struct ); - cvFree( &simple_struct ); -} - - -int CxCore_DynStructBaseTest::write_default_params( CvFileStorage* fs ) -{ - write_param( fs, "struct_count", struct_count ); - write_param( fs, "max_struct_size", max_struct_size ); - write_param( fs, "generations", generations ); - write_param( fs, "iterations", iterations ); - write_param( fs, "min_log_storage_block_size", min_log_storage_block_size ); - write_param( fs, "max_log_storage_block_size", max_log_storage_block_size ); - write_param( fs, "min_log_elem_size", min_log_elem_size ); - write_param( fs, "max_log_elem_size", max_log_elem_size ); - return 0; -} - - -int CxCore_DynStructBaseTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - double sqrt_scale = sqrt(ts->get_test_case_count_scale()); - if( code < 0 ) - return code; - - struct_count = cvReadInt( find_param( fs, "struct_count" ), struct_count ); - max_struct_size = cvReadInt( find_param( fs, "max_struct_size" ), max_struct_size ); - generations = cvReadInt( find_param( fs, "generations" ), generations ); - iterations = cvReadInt( find_param( fs, "iterations" ), iterations ); - generations = cvRound(generations*sqrt_scale); - iterations = cvRound(iterations*sqrt_scale); - - min_log_storage_block_size = cvReadInt( find_param( fs, "min_log_storage_block_size" ), - min_log_storage_block_size ); - max_log_storage_block_size = cvReadInt( find_param( fs, "max_log_storage_block_size" ), - max_log_storage_block_size ); - min_log_elem_size = cvReadInt( find_param( fs, "min_log_elem_size" ), min_log_elem_size ); - max_log_elem_size = cvReadInt( find_param( fs, "max_log_elem_size" ), max_log_elem_size ); - - struct_count = cvTsClipInt( struct_count, 1, 100 ); - max_struct_size = cvTsClipInt( max_struct_size, 1, 1<<20 ); - generations = cvTsClipInt( generations, 1, 100 ); - iterations = cvTsClipInt( iterations, 100, 1<<20 ); - - min_log_storage_block_size = cvTsClipInt( min_log_storage_block_size, 7, 20 ); - max_log_storage_block_size = cvTsClipInt( max_log_storage_block_size, - min_log_storage_block_size, 20 ); - - min_log_elem_size = cvTsClipInt( min_log_elem_size, 0, 8 ); - max_log_elem_size = cvTsClipInt( max_log_elem_size, min_log_elem_size, 10 ); - - return 0; -} - - -void CxCore_DynStructBaseTest::update_progressbar() -{ - int64 t; - - if( test_progress < 0 ) - { - test_progress = 0; - cpu_freq = cv::getTickFrequency(); - start_time = cv::getTickCount(); - } - - t = cv::getTickCount(); - test_progress = update_progress( test_progress, 0, 0, (double)(t - start_time)/cpu_freq ); -} - - -void CxCore_DynStructBaseTest::set_error_context( const char* condition, - const char* err_msg, - const char* func_name ) -{ - ts->printf( CvTS::LOG, "%s: %s\n(\"%s\" failed).\n" - "generation = %d, struct_idx = %d, iter = %d\n", - func_name, err_msg, condition, gen, struct_idx, iter ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); -} - - -int CxCore_DynStructBaseTest::test_seq_block_consistence( int _struct_idx, CvSeq* seq, int total ) -{ - int sum = 0, code = -1; - CV_FUNCNAME( "CxCore_DynStructBaseTest::test_seq_block_consistence" ); - - struct_idx = _struct_idx; - - __BEGIN__; - - CV_TS_SEQ_CHECK_CONDITION( seq != 0, "Null sequence pointer" ); - - if( seq->first ) - { - CvSeqBlock* block = seq->first; - CvSeqBlock* prev_block = block->prev; - - int delta_idx = seq->first->start_index; - - for( ;; ) - { - CV_TS_SEQ_CHECK_CONDITION( sum == block->start_index - delta_idx && - block->count > 0 && block->prev == prev_block && - prev_block->next == block, - "sequence blocks are inconsistent" ); - sum += block->count; - prev_block = block; - block = block->next; - if( block == seq->first ) break; - } - - CV_TS_SEQ_CHECK_CONDITION( block->prev->count * seq->elem_size + - block->prev->data <= seq->block_max, - "block->data or block_max pointer are incorrect" ); - } - - CV_TS_SEQ_CHECK_CONDITION( seq->total == sum && sum == total, - "total number of elements is incorrect" ); - - code = 0; - - __END__; - - return code; -} - - -CxCore_DynStructBaseTest ds_test( "ds", "" ); - -/////////////////////////////////// sequence tests //////////////////////////////////// - -class CxCore_SeqBaseTest : public CxCore_DynStructBaseTest -{ -public: - CxCore_SeqBaseTest( const char* test_name, const char* test_funcs ); - void clear(); - void run( int ); - -protected: - int test_multi_create(); - int test_get_seq_elem( int _struct_idx, int iters ); - int test_get_seq_reading( int _struct_idx, int iters ); - int test_seq_ops( int iters ); -}; - - -CxCore_SeqBaseTest::CxCore_SeqBaseTest( const char* test_name, const char* test_funcs ) : - CxCore_DynStructBaseTest( test_name, test_funcs ) -{ -} - - -void CxCore_SeqBaseTest::clear() -{ - int i; - if( simple_struct ) - { - for( i = 0; i < struct_count; i++ ) - cvTsReleaseSimpleSeq( (CvTsSimpleSeq**)&simple_struct[i] ); - } - CxCore_DynStructBaseTest::clear(); -} - - -int CxCore_SeqBaseTest::test_multi_create() -{ - CvSeqWriter* writer = (CvSeqWriter*)cvStackAlloc( struct_count*sizeof(writer[0]) ); - int* pos = (int*)cvStackAlloc( struct_count*sizeof(pos[0]) ); - int* index = (int*)cvStackAlloc( struct_count*sizeof(index[0]) ); - int i, cur_count, elem_size; - int code = -1; - CvRNG* rng = ts->get_rng(); - - CV_FUNCNAME( "CxCore_SeqBaseTest::test_multi_create" ); - - __BEGIN__; - - for( i = 0; i < struct_count; i++ ) - { - double t; - CvMat m; - CvTsSimpleSeq* sseq; - - pos[i] = -1; - index[i] = i; - - t = cvTsRandReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size; - elem_size = cvRound( exp(t * CV_LOG2) ); - elem_size = MIN( elem_size, (int)(storage->block_size - sizeof(void*) - - sizeof(CvSeqBlock) - sizeof(CvMemBlock)) ); - - cvTsReleaseSimpleSeq( (CvTsSimpleSeq**)&simple_struct[i] ); - simple_struct[i] = sseq = cvTsCreateSimpleSeq( max_struct_size, elem_size ); - cxcore_struct[i] = 0; - sseq->count = cvTsRandInt( rng ) % max_struct_size; - m = cvMat( 1, MAX(sseq->count,1)*elem_size, CV_8UC1, sseq->array ); - cvRandArr( rng, &m, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(256) ); - } - - for( cur_count = struct_count; cur_count > 0; cur_count-- ) - { - for(;;) - { - int k = cvTsRandInt( rng ) % cur_count; - struct_idx = index[k]; - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[struct_idx]; - - if( pos[struct_idx] < 0 ) - { - int hdr_size = (cvTsRandInt(rng) % 10)*4 + sizeof(CvSeq); - hdr_size = MIN( hdr_size, (int)(storage->block_size - sizeof(CvMemBlock)) ); - elem_size = sseq->elem_size; - - if( cvTsRandInt(rng) % 2 ) - { - CV_CALL( cvStartWriteSeq( 0, hdr_size, elem_size, storage, writer + struct_idx )); - } - else - { - CvSeq* s; - CV_CALL( s = cvCreateSeq( 0, hdr_size, elem_size, storage )); - CV_CALL( cvStartAppendToSeq( s, writer + struct_idx )); - } - - CV_CALL( cvSetSeqBlockSize( writer[struct_idx].seq, cvTsRandInt( rng ) % 10000 )); - pos[struct_idx] = 0; - } - - update_progressbar(); - if( pos[struct_idx] == sseq->count ) - { - CV_CALL( cxcore_struct[struct_idx] = cvEndWriteSeq( writer + struct_idx )); - /* del index */ - for( ; k < cur_count-1; k++ ) - index[k] = index[k+1]; - break; - } - - { - schar* el = cvTsSimpleSeqElem( sseq, pos[struct_idx] ); - CV_WRITE_SEQ_ELEM_VAR( el, writer[struct_idx] ); - } - pos[struct_idx]++; - } - } - - code = 0; - - __END__; - - return code; -} - - -int CxCore_SeqBaseTest::test_get_seq_elem( int _struct_idx, int iters ) -{ - int i, code = -1; - CvRNG* rng = ts->get_rng(); - - CV_FUNCNAME( "CxCore_SeqBaseTest::test_get_seq_elem" ); - - __BEGIN__; - - CvSeq* seq = (CvSeq*)cxcore_struct[_struct_idx]; - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[_struct_idx]; - struct_idx = _struct_idx; - - assert( seq->total == sseq->count ); - - if( sseq->count == 0 ) - return 0; - - for( i = 0; i < iters; i++ ) - { - int idx = cvTsRandInt(rng) % (sseq->count*3) - sseq->count*3/2; - int idx0 = (unsigned)idx < (unsigned)(sseq->count) ? idx : idx < 0 ? - idx + sseq->count : idx - sseq->count; - int bad_range = (unsigned)idx0 >= (unsigned)(sseq->count); - schar* elem; - CV_CALL( elem = cvGetSeqElem( seq, idx )); - - if( bad_range ) - { - CV_TS_SEQ_CHECK_CONDITION( elem == 0, - "cvGetSeqElem doesn't " - "handle \"out of range\" properly" ); - } - else - { - CV_TS_SEQ_CHECK_CONDITION( elem != 0 && - !memcmp( elem, cvTsSimpleSeqElem(sseq, idx0), sseq->elem_size ), - "cvGetSeqElem returns wrong element" ); - - CV_CALL( idx = cvSeqElemIdx(seq, elem )); - CV_TS_SEQ_CHECK_CONDITION( idx >= 0 && idx == idx0, - "cvSeqElemIdx is incorrect" ); - } - } - - code = 0; - - __END__; - - return code; -} - - -int CxCore_SeqBaseTest::test_get_seq_reading( int _struct_idx, int iters ) -{ - const int max_val = 3*5 + 2; - int code = -1, pos; - CvSeq* seq = (CvSeq*)cxcore_struct[_struct_idx]; - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[_struct_idx]; - int total = seq->total; - CvRNG* rng = ts->get_rng(); - CvSeqReader reader; - schar* elem; - - CV_FUNCNAME( "CxCore_SeqBaseTest::test_get_seq_reading" ); - - __BEGIN__; - - assert( total == sseq->count ); - this->struct_idx = _struct_idx; - elem = (schar*)alloca( sseq->elem_size ); - - pos = cvTsRandInt(rng) % 2; - CV_CALL( cvStartReadSeq( seq, &reader, pos )); - - if( total == 0 ) - { - CV_TS_SEQ_CHECK_CONDITION( reader.ptr == 0, "Empty sequence reader pointer is not NULL" ); - code = 0; - EXIT; - } - - pos = pos ? seq->total - 1 : 0; - - CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos(&reader), - "initial reader position is wrong" ); - - for( iter = 0; iter < iters; iter++ ) - { - int op = cvTsRandInt(rng) % max_val; - - if( op >= max_val - 2 ) - { - int new_pos, new_pos0; - int bad_range; - int is_relative = op == max_val - 1; - - new_pos = cvTsRandInt(rng) % (total*2) - total; - new_pos0 = new_pos + (is_relative ? pos : 0 ); - - if( new_pos0 < 0 ) new_pos0 += total; - if( new_pos0 >= total ) new_pos0 -= total; - - bad_range = (unsigned)new_pos0 >= (unsigned)total; - CV_CALL( cvSetSeqReaderPos( &reader, new_pos, is_relative )); - - if( !bad_range ) - { - CV_TS_SEQ_CHECK_CONDITION( new_pos0 == cvGetSeqReaderPos( &reader ), - "cvset reader position doesn't work" ); - pos = new_pos0; - } - else - { - CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos( &reader ), - "reader doesn't stay at the current position after wrong positioning" ); - } - } - else - { - int direction = (op % 3) - 1; - memcpy( elem, reader.ptr, sseq->elem_size ); - - if( direction > 0 ) - { - CV_NEXT_SEQ_ELEM( sseq->elem_size, reader ); - } - else if( direction < 0 ) - { - CV_PREV_SEQ_ELEM( sseq->elem_size, reader ); - } - - CV_TS_SEQ_CHECK_CONDITION( memcmp(elem, cvTsSimpleSeqElem(sseq, pos), - sseq->elem_size) == 0, "reading is incorrect" ); - pos += direction; - if( pos < 0 ) pos += total; - if( pos >= total ) pos -= total; - - CV_TS_SEQ_CHECK_CONDITION( pos == cvGetSeqReaderPos( &reader ), - "reader doesn't move correctly after reading" ); - } - } - - code = 0; - - __END__; - - return code; -} - - -int CxCore_SeqBaseTest::test_seq_ops( int iters ) -{ - const int max_op = 14; - int i, code = -1; - int max_elem_size = 0; - schar *elem = 0, *elem2 = 0; - CvMat* elem_mat = 0; - CvRNG* rng = ts->get_rng(); - - CV_FUNCNAME( "CxCore_SeqBaseTest::test_seq_ops" ); - - __BEGIN__; - - for( i = 0; i < struct_count; i++ ) - max_elem_size = MAX( max_elem_size, ((CvSeq*)cxcore_struct[i])->elem_size ); - - CV_CALL( elem_mat = cvCreateMat( 1, max_struct_size*max_elem_size, CV_8UC1 )); - elem = (schar*)elem_mat->data.ptr; - - for( iter = 0; iter < iters; iter++ ) - { - struct_idx = cvTsRandInt(rng) % struct_count; - int op = cvTsRandInt(rng) % max_op; - CvSeq* seq = (CvSeq*)cxcore_struct[struct_idx]; - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[struct_idx]; - int elem_size = sseq->elem_size; - int whence = 0, pos = 0, count = 0; - - switch( op ) - { - case 0: - case 1: - case 2: // push/pushfront/insert - if( sseq->count == sseq->max_count ) - break; - - elem_mat->cols = elem_size; - cvRandArr( rng, elem_mat, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(255) ); - - whence = op - 1; - if( whence < 0 ) - { - pos = 0; - CV_CALL(cvSeqPushFront( seq, elem )); - } - else if( whence > 0 ) - { - pos = sseq->count; - CV_CALL(cvSeqPush( seq, elem )); - } - else - { - pos = cvTsRandInt(rng) % (sseq->count + 1); - CV_CALL(cvSeqInsert( seq, pos, elem )); - } - - cvTsSimpleSeqShiftAndCopy( sseq, pos, pos + 1, elem ); - elem2 = cvGetSeqElem( seq, pos ); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "The inserted element could not be retrieved" ); - CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count && - memcmp(elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0, - "The inserted sequence element is wrong" ); - break; - - case 3: - case 4: - case 5: // pop/popfront/remove - if( sseq->count == 0 ) - break; - - whence = op - 4; - if( whence < 0 ) - { - pos = 0; - CV_CALL( cvSeqPopFront( seq, elem )); - } - else if( whence > 0 ) - { - pos = sseq->count-1; - CV_CALL( cvSeqPop( seq, elem )); - } - else - { - pos = cvTsRandInt(rng) % sseq->count; - CV_CALL( cvSeqRemove( seq, pos )); - } - - if( whence != 0 ) - CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count - 1 && - memcmp( elem, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0, - "The popped sequence element isn't correct" ); - - cvTsSimpleSeqShiftAndCopy( sseq, pos + 1, pos ); - - if( sseq->count > 0 ) - { - CV_CALL( elem2 = cvGetSeqElem( seq, pos < sseq->count ? pos : -1 )); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "GetSeqElem fails after removing the element" ); - - CV_TS_SEQ_CHECK_CONDITION( memcmp( elem2, - cvTsSimpleSeqElem(sseq, pos - (pos == sseq->count)), elem_size) == 0, - "The first shifted element is not correct after removing another element" ); - } - else - { - CV_TS_SEQ_CHECK_CONDITION( seq->first == 0, - "The sequence doesn't become empty after the final remove" ); - } - break; - - case 6: - case 7: - case 8: // push [front] multi/insert slice - if( sseq->count == sseq->max_count ) - break; - - count = cvTsRandInt( rng ) % (sseq->max_count - sseq->count + 1); - elem_mat->cols = MAX(count,1) * elem_size; - cvRandArr( rng, elem_mat, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(255) ); - - whence = op - 7; - pos = whence < 0 ? 0 : whence > 0 ? sseq->count : cvTsRandInt(rng) % (sseq->count+1); - if( whence != 0 ) - { - CV_CALL( cvSeqPushMulti( seq, elem, count, whence < 0 )); - } - else - { - CvSeq header; - CvSeqBlock block; - CV_CALL( cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC, sizeof(CvSeq), - sseq->elem_size, - elem_mat->data.ptr, count, - &header, &block )); - - CV_CALL( cvSeqInsertSlice( seq, pos, &header )); - } - cvTsSimpleSeqShiftAndCopy( sseq, pos, pos + count, elem ); - - if( sseq->count > 0 ) - { - // choose the random element among the added - pos = count > 0 ? cvTsRandInt(rng) % count + pos : MAX(pos-1,0); - CV_CALL( elem2 = cvGetSeqElem( seq, pos )); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "multi push operation doesn't add elements" ); - CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count && - memcmp( elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0, - "One of the added elements is wrong" ); - } - else - { - CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0, - "Adding no elements to empty sequence fails" ); - } - break; - - case 9: - case 10: - case 11: // pop [front] multi - if( sseq->count == 0 ) - break; - - count = cvTsRandInt(rng) % (sseq->count+1); - whence = op - 10; - pos = whence < 0 ? 0 : whence > 0 ? sseq->count - count : - cvTsRandInt(rng) % (sseq->count - count + 1); - - if( whence != 0 ) - { - CV_CALL( cvSeqPopMulti( seq, elem, count, whence < 0 )); - - if( count > 0 ) - { - CV_TS_SEQ_CHECK_CONDITION( memcmp(elem, - cvTsSimpleSeqElem(sseq,pos), elem_size) == 0, - "The first (in the sequence order) removed element is wrong after popmulti" ); - } - } - else - { - CV_CALL( cvSeqRemoveSlice( seq, cvSlice(pos, pos + count) )); - } - - CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count - count, - "The popmulti left a wrong number of elements in the sequence" ); - - cvTsSimpleSeqShiftAndCopy( sseq, pos + count, pos, 0 ); - if( sseq->count > 0 ) - { - pos = whence < 0 ? 0 : MIN( pos, sseq->count - 1 ); - elem2 = cvGetSeqElem( seq, pos ); - CV_TS_SEQ_CHECK_CONDITION( elem2 && - memcmp( elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0, - "The last sequence element is wrong after POP" ); - } - else - { - CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0, - "The sequence doesn't become empty after final POP" ); - } - break; - case 12: // seqslice - { - CvMemStoragePos storage_pos; - cvSaveMemStoragePos( storage, &storage_pos ); - - int copy_data = cvTsRandInt(rng) % 2; - count = cvTsRandInt(rng) % (seq->total + 1); - pos = cvTsRandInt(rng) % (seq->total - count + 1); - CvSeq* seq_slice = cvSeqSlice( seq, cvSlice(pos, pos + count), storage, copy_data ); - - CV_TS_SEQ_CHECK_CONDITION( seq_slice && seq_slice->total == count, - "cvSeqSlice returned incorrect slice" ); - - if( count > 0 ) - { - int test_idx = cvTsRandInt(rng) % count; - elem2 = cvGetSeqElem( seq_slice, test_idx ); - schar* elem3 = cvGetSeqElem( seq, pos + test_idx ); - CV_TS_SEQ_CHECK_CONDITION( elem2 && - memcmp( elem2, cvTsSimpleSeqElem(sseq,pos + test_idx), elem_size) == 0, - "The extracted slice elements are not correct" ); - CV_TS_SEQ_CHECK_CONDITION( (elem2 == elem3) ^ copy_data, - "copy_data flag is handled incorrectly" ); - } - - cvRestoreMemStoragePos( storage, &storage_pos ); - } - break; - case 13: // clear - cvTsClearSimpleSeq( sseq ); - cvClearSeq( seq ); - CV_TS_SEQ_CHECK_CONDITION( seq->total == 0 && seq->first == 0, - "The sequence doesn't become empty after clear" ); - break; - default: - assert(0); - EXIT; - } - - if( test_seq_block_consistence(struct_idx, seq, sseq->count) < 0 ) - EXIT; - - if( test_get_seq_elem(struct_idx, 7) < 0 ) - EXIT; - - update_progressbar(); - } - - code = 0; - - __END__; - - if( elem_mat ) - elem_mat->cols = 1; // just to skip a consistency check - cvReleaseMat( &elem_mat ); - - return code; -} - - -void CxCore_SeqBaseTest::run( int ) -{ - CvRNG* rng = ts->get_rng(); - int i; - double t; - - //CV_FUNCNAME( "CxCore_SeqBaseTest::run" ); - - __BEGIN__; - - clear(); - test_progress = -1; - - simple_struct = (void**)cvAlloc( struct_count * sizeof(simple_struct[0]) ); - memset( simple_struct, 0, struct_count * sizeof(simple_struct[0]) ); - cxcore_struct = (void**)cvAlloc( struct_count * sizeof(cxcore_struct[0]) ); - memset( cxcore_struct, 0, struct_count * sizeof(cxcore_struct[0]) ); - - for( gen = 0; gen < generations; gen++ ) - { - struct_idx = iter = -1; - - if( !storage ) - { - t = cvTsRandReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) - + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); - } - - iter = struct_idx = -1; - test_multi_create(); - - for( i = 0; i < struct_count; i++ ) - { - if( test_seq_block_consistence(i, (CvSeq*)cxcore_struct[i], - ((CvTsSimpleSeq*)simple_struct[i])->count) < 0 ) - EXIT; - - if( test_get_seq_elem( i, MAX(iterations/3,7) ) < 0 ) - EXIT; - - if( test_get_seq_reading( i, MAX(iterations/3,7) ) < 0 ) - EXIT; - update_progressbar(); - } - - if( test_seq_ops( iterations ) < 0 ) - EXIT; - - if( cvTsRandInt(rng) % 2 ) - cvReleaseMemStorage( &storage ); - else - cvClearMemStorage( storage ); - } - - __END__; -} - -CxCore_SeqBaseTest seqbase_test( "ds-seq-base", "cvCreateSeq, cvClearSeq, cvSeqSlice, " - "cvStartAppendToSeq, cvStartWriteSeq, cvEndWriteSeq, CV_WRITE_SEQ_ELEM_VAR, " - "cvGetSeqElem, cvSeqElemIdx, cvStartReadSeq, CV_NEXT_SEQ_ELEM, CV_PREV_SEQ_ELEM, " - "cvSetSeqReaderPos, cvGetSeqReaderPos, cvSeqPush, cvSeqPushFront, cvSeqPop, " - "cvSeqPopFront, cvSeqPushMulti, cvSeqPopMulti, cvSeqInsert, cvSeqRemove, " - "cvSeqInsertSlice, cvSeqRemoveSlice, cvMakeSeqHeaderForArray" ); - -////////////////////////////// more sequence tests ////////////////////////////////////// - -class CxCore_SeqSortInvTest : public CxCore_SeqBaseTest -{ -public: - CxCore_SeqSortInvTest( const char* test_name, const char* test_funcs ); - void run( int ); - -protected: -}; - - -CxCore_SeqSortInvTest::CxCore_SeqSortInvTest( const char* test_name, const char* test_funcs ) : - CxCore_SeqBaseTest( test_name, test_funcs ) -{ -} - - -static int icvCmpSeqElems( const void* a, const void* b, void* userdata ) -{ - return memcmp( a, b, ((CvSeq*)userdata)->elem_size ); -} - -static int icvCmpSeqElems2_elem_size = 0; -static int icvCmpSeqElems2( const void* a, const void* b ) -{ - return memcmp( a, b, icvCmpSeqElems2_elem_size ); -} - - -void CxCore_SeqSortInvTest::run( int ) -{ - CvRNG* rng = ts->get_rng(); - int i, k; - double t; - schar *elem0, *elem, *elem2; - CvMat* buffer = 0; - - CV_FUNCNAME( "CxCore_SeqSortInvTest::run" ); - - __BEGIN__; - - clear(); - test_progress = -1; - - simple_struct = (void**)cvAlloc( struct_count * sizeof(simple_struct[0]) ); - memset( simple_struct, 0, struct_count * sizeof(simple_struct[0]) ); - cxcore_struct = (void**)cvAlloc( struct_count * sizeof(cxcore_struct[0]) ); - memset( cxcore_struct, 0, struct_count * sizeof(cxcore_struct[0]) ); - - for( gen = 0; gen < generations; gen++ ) - { - struct_idx = iter = -1; - - if( !storage ) - { - t = cvTsRandReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) - + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); - } - - for( iter = 0; iter < iterations/10; iter++ ) - { - int max_size = 0; - test_multi_create(); - - for( i = 0; i < struct_count; i++ ) - { - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[i]; - max_size = MAX( max_size, sseq->count*sseq->elem_size ); - } - - if( !buffer || buffer->cols < max_size ) - { - cvReleaseMat( &buffer ); - CV_CALL( buffer = cvCreateMat( 1, max_size, CV_8UC1 )); - } - - for( i = 0; i < struct_count; i++ ) - { - CvSeq* seq = (CvSeq*)cxcore_struct[i]; - CvTsSimpleSeq* sseq = (CvTsSimpleSeq*)simple_struct[i]; - CvSlice slice = CV_WHOLE_SEQ; - - //printf("%d. %d. %d-th size = %d\n", gen, iter, i, sseq->count ); - - CV_CALL( cvSeqInvert( seq )); - cvTsSimpleSeqInvert( sseq ); - - if( test_seq_block_consistence( i, seq, sseq->count ) < 0 ) - EXIT; - - if( sseq->count > 0 && cvTsRandInt(rng) % 2 == 0 ) - { - slice.end_index = cvTsRandInt(rng) % sseq->count + 1; - slice.start_index = cvTsRandInt(rng) % (sseq->count - slice.end_index + 1); - slice.end_index += slice.start_index; - } - - CV_CALL( cvCvtSeqToArray( seq, buffer->data.ptr, slice )); - - slice.end_index = MIN( slice.end_index, sseq->count ); - CV_TS_SEQ_CHECK_CONDITION( sseq->count == 0 || memcmp( buffer->data.ptr, - sseq->array + slice.start_index*sseq->elem_size, - (slice.end_index - slice.start_index)*sseq->elem_size ) == 0, - "cvSeqInvert returned wrong result" ); - - for( k = 0; k < (sseq->count > 0 ? 10 : 0); k++ ) - { - int idx0 = cvTsRandInt(rng) % sseq->count, idx = 0; - CV_CALL( elem0 = cvTsSimpleSeqElem( sseq, idx0 )); - CV_CALL( elem = cvGetSeqElem( seq, idx0 )); - elem2 = cvSeqSearch( seq, elem0, k % 2 ? icvCmpSeqElems : 0, 0, &idx, seq ); - - CV_TS_SEQ_CHECK_CONDITION( elem != 0 && - memcmp( elem0, elem, seq->elem_size ) == 0, - "cvSeqInvert gives incorrect result" ); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 && - memcmp( elem0, elem2, seq->elem_size ) == 0 && - elem2 == cvGetSeqElem( seq, idx ), - "cvSeqSearch failed (linear search)" ); - } - - CV_CALL( cvSeqSort( seq, icvCmpSeqElems, seq )); - - if( test_seq_block_consistence( i, seq, sseq->count ) < 0 ) - EXIT; - - if( sseq->count > 0 ) - { - // !!! This is not thread-safe !!! - icvCmpSeqElems2_elem_size = sseq->elem_size; - qsort( sseq->array, sseq->count, sseq->elem_size, icvCmpSeqElems2 ); - - if( cvTsRandInt(rng) % 2 == 0 ) - { - slice.end_index = cvTsRandInt(rng) % sseq->count + 1; - slice.start_index = cvTsRandInt(rng) % (sseq->count - slice.end_index + 1); - slice.end_index += slice.start_index; - } - } - - CV_CALL( cvCvtSeqToArray( seq, buffer->data.ptr, slice )); - CV_TS_SEQ_CHECK_CONDITION( sseq->count == 0 || memcmp( buffer->data.ptr, - sseq->array + slice.start_index*sseq->elem_size, - (slice.end_index - slice.start_index)*sseq->elem_size ) == 0, - "cvSeqSort returned wrong result" ); - - for( k = 0; k < (sseq->count > 0 ? 10 : 0); k++ ) - { - int idx0 = cvTsRandInt(rng) % sseq->count, idx = 0; - CV_CALL( elem0 = cvTsSimpleSeqElem( sseq, idx0 )); - CV_CALL( elem = cvGetSeqElem( seq, idx0 )); - elem2 = cvSeqSearch( seq, elem0, icvCmpSeqElems, 1, &idx, seq ); - - CV_TS_SEQ_CHECK_CONDITION( elem != 0 && - memcmp( elem0, elem, seq->elem_size ) == 0, - "cvSeqSort gives incorrect result" ); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 && - memcmp( elem0, elem2, seq->elem_size ) == 0 && - elem2 == cvGetSeqElem( seq, idx ), - "cvSeqSearch failed (binary search)" ); - } - } - - cvClearMemStorage( storage ); - } - - cvReleaseMemStorage( &storage ); - } - - __END__; - - cvReleaseMat( &buffer ); -} - - -CxCore_SeqSortInvTest seqsortinv_test( "ds-seq-sortinv", - "cvCreateSeq, cvStartAppendToSeq, cvStartWriteSeq, " - "cvEndWriteSeq, CV_WRITE_SEQ_ELEM_VAR, " - "cvSeqSort, cvSeqSearch, cvSeqInvert, " - "cvCvtSeqToArray, cvGetSeqElem" ); - -/////////////////////////////////////// set tests /////////////////////////////////////// - -class CxCore_SetTest : public CxCore_DynStructBaseTest -{ -public: - CxCore_SetTest(); - void clear(); - void run( int ); - -protected: - //int test_seq_block_consistence( int struct_idx ); - int test_set_ops( int iters ); -}; - - -CxCore_SetTest::CxCore_SetTest(): - CxCore_DynStructBaseTest( "ds-set", "cvCreateSet, cvClearSet, " - "cvSetAdd, cvSetRemove, cvSetNew, cvSetRemoveByPtr, cvGetSetElem" ) -{ -} - - -void CxCore_SetTest::clear() -{ - int i; - if( simple_struct ) - for( i = 0; i < struct_count; i++ ) - cvTsReleaseSimpleSet( (CvTsSimpleSet**)&simple_struct[i] ); - CxCore_DynStructBaseTest::clear(); -} - - -int CxCore_SetTest::test_set_ops( int iters ) -{ - const int max_op = 4; - int i, code = -1; - int max_elem_size = 0; - int idx, idx0; - CvSetElem *elem = 0, *elem2 = 0, *elem3 = 0; - schar* elem_data = 0; - CvMat* elem_mat = 0; - CvRNG* rng = ts->get_rng(); - //int max_active_count = 0, mean_active_count = 0; - - CV_FUNCNAME( "CxCore_SetTest::test_set_ops" ); - - __BEGIN__; - - for( i = 0; i < struct_count; i++ ) - max_elem_size = MAX( max_elem_size, ((CvSeq*)cxcore_struct[i])->elem_size ); - - CV_CALL( elem_mat = cvCreateMat( 1, max_elem_size, CV_8UC1 )); - - for( iter = 0; iter < iters; iter++ ) - { - struct_idx = cvTsRandInt(rng) % struct_count; - - CvSet* cvset = (CvSet*)cxcore_struct[struct_idx]; - CvTsSimpleSet* sset = (CvTsSimpleSet*)simple_struct[struct_idx]; - int pure_elem_size = sset->elem_size - 1; - int prev_total = cvset->total, prev_count = cvset->active_count; - int op = cvTsRandInt(rng) % (iter <= iters/10 ? 2 : max_op); - int by_ptr = op % 2 == 0; - CvSetElem* first_free = cvset->free_elems; - CvSetElem* next_free = first_free ? first_free->next_free : 0; - int pass_data = 0; - - if( iter > iters/10 && cvTsRandInt(rng)%200 == 0 ) // clear set - { - int prev_count = cvset->total; - cvClearSet( cvset ); - cvTsClearSimpleSet( sset ); - - CV_TS_SEQ_CHECK_CONDITION( cvset->active_count == 0 && cvset->total == 0 && - cvset->first == 0 && cvset->free_elems == 0 && - (cvset->free_blocks != 0 || prev_count == 0), - "cvClearSet doesn't remove all the elements" ); - continue; - } - else if( op == 0 || op == 1 ) // add element - { - if( sset->free_count == 0 ) - continue; - - elem_mat->cols = cvset->elem_size; - cvRandArr( rng, elem_mat, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(255) ); - elem = (CvSetElem*)elem_mat->data.ptr; - - if( by_ptr ) - { - CV_CALL( elem2 = cvSetNew( cvset )); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "cvSetNew returned NULL pointer" ); - } - else - { - pass_data = cvTsRandInt(rng) % 2; - CV_CALL( idx = cvSetAdd( cvset, pass_data ? elem : 0, &elem2 )); - CV_TS_SEQ_CHECK_CONDITION( elem2 != 0 && elem2->flags == idx, - "cvSetAdd returned NULL pointer or a wrong index" ); - } - - elem_data = (schar*)elem + sizeof(int); - - if( !pass_data ) - memcpy( (schar*)elem2 + sizeof(int), elem_data, pure_elem_size ); - - idx = elem2->flags; - idx0 = cvTsSimpleSetAdd( sset, elem_data ); - CV_CALL( elem3 = cvGetSetElem( cvset, idx )); - - CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(elem3) && - idx == idx0 && elem3 == elem2 && (!pass_data || - memcmp( (char*)elem3 + sizeof(int), elem_data, pure_elem_size) == 0), - "The added element is not correct" ); - - CV_TS_SEQ_CHECK_CONDITION( (!first_free || elem3 == first_free) && - (!next_free || cvset->free_elems == next_free) && - cvset->active_count == prev_count + 1, - "The free node list is modified incorrectly" ); - } - else if( op == 2 || op == 3 ) // remove element - { - idx = cvTsRandInt(rng) % sset->max_count; - - if( sset->free_count == sset->max_count || idx >= sset->count ) - continue; - - elem_data = cvTsSimpleSetFind(sset, idx); - if( elem_data == 0 ) - continue; - - CV_CALL( elem = cvGetSetElem( cvset, idx )); - CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(elem) && elem->flags == idx && - memcmp((char*)elem + sizeof(int), elem_data, pure_elem_size) == 0, - "cvGetSetElem returned wrong element" ); - - if( by_ptr ) - { - CV_CALL( cvSetRemoveByPtr( cvset, elem )); - } - else - { - CV_CALL( cvSetRemove( cvset, idx )); - } - - cvTsSimpleSetRemove( sset, idx ); - - CV_TS_SEQ_CHECK_CONDITION( !CV_IS_SET_ELEM(elem) && !cvGetSetElem(cvset, idx) && - (elem->flags & CV_SET_ELEM_IDX_MASK) == idx, - "cvSetRemove[ByPtr] didn't release the element properly" ); - - CV_TS_SEQ_CHECK_CONDITION( elem->next_free == first_free && - cvset->free_elems == elem && - cvset->active_count == prev_count - 1, - "The free node list has not been updated properly" ); - } - - //max_active_count = MAX( max_active_count, cvset->active_count ); - //mean_active_count += cvset->active_count; - CV_TS_SEQ_CHECK_CONDITION( cvset->active_count == sset->max_count - sset->free_count && - cvset->total >= cvset->active_count && - (cvset->total == 0 || cvset->total >= prev_total), - "The total number of cvset elements is not correct" ); - - // CvSet and simple set do not neccessary have the same "total" (active & free) number, - // so pass "set->total" to skip that check - test_seq_block_consistence( struct_idx, (CvSeq*)cvset, cvset->total ); - update_progressbar(); - } - - code = 0; - //ts->printf( CvTS::LOG, "\ngeneration %d. max_active_count = %d,\n\tmean_active_count = %d\n", - // gen, max_active_count, mean_active_count/iters ); - - __END__; - - if( elem_mat ) - elem_mat->cols = 1; // just to skip a consistency check - cvReleaseMat( &elem_mat ); - - return code; -} - - -void CxCore_SetTest::run( int ) -{ - CvRNG* rng = ts->get_rng(); - int i; - double t; - - CV_FUNCNAME( "CxCore_SetTest::run" ); - - __BEGIN__; - - clear(); - test_progress = -1; - - simple_struct = (void**)cvAlloc( struct_count * sizeof(simple_struct[0]) ); - memset( simple_struct, 0, struct_count * sizeof(simple_struct[0]) ); - cxcore_struct = (void**)cvAlloc( struct_count * sizeof(cxcore_struct[0]) ); - memset( cxcore_struct, 0, struct_count * sizeof(cxcore_struct[0]) ); - - for( gen = 0; gen < generations; gen++ ) - { - struct_idx = iter = -1; - t = cvTsRandReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - storage = cvCreateMemStorage( cvRound( exp(t * CV_LOG2) ) ); - - for( i = 0; i < struct_count; i++ ) - { - t = cvTsRandReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size; - int pure_elem_size = cvRound( exp(t * CV_LOG2) ); - int elem_size = pure_elem_size + sizeof(int); - elem_size = (elem_size + sizeof(size_t) - 1) & ~(sizeof(size_t)-1); - elem_size = MAX( elem_size, (int)sizeof(CvSetElem) ); - elem_size = MIN( elem_size, (int)(storage->block_size - sizeof(void*) - sizeof(CvMemBlock) - sizeof(CvSeqBlock)) ); - pure_elem_size = MIN( pure_elem_size, elem_size-(int)sizeof(CvSetElem) ); - - cvTsReleaseSimpleSet( (CvTsSimpleSet**)&simple_struct[i] ); - simple_struct[i] = cvTsCreateSimpleSet( max_struct_size, pure_elem_size ); - CV_CALL( cxcore_struct[i] = cvCreateSet( 0, sizeof(CvSet), elem_size, storage )); - } - - if( test_set_ops( iterations*100 ) < 0 ) - EXIT; - - cvReleaseMemStorage( &storage ); - } - - __END__; -} - -CxCore_SetTest set_test; - - -/////////////////////////////////////// graph tests ////////////////////////////////// - -class CxCore_GraphTest : public CxCore_DynStructBaseTest -{ -public: - CxCore_GraphTest(); - void clear(); - void run( int ); - -protected: - //int test_seq_block_consistence( int struct_idx ); - int test_graph_ops( int iters ); -}; - - -CxCore_GraphTest::CxCore_GraphTest(): - CxCore_DynStructBaseTest( "ds-graph", "cvCreateGraph, cvClearGraph, " - "cvGraphAddVtx, cvGraphRemoveVtx, cvGraphRemoveVtxByPtr, " - "cvGraphAddEdge, cvGraphAddEdgeByPtr, " - "cvGraphRemoveEdge, cvGraphRemoveEdgeByPtr, " - "cvGraphVtxDegree, cvGraphVtxDegreeByPtr, " - "cvGetGraphVtx, cvFindGraphEdge, cvFindGraphEdgeByPtr " ) -{ -} - - -void CxCore_GraphTest::clear() -{ - int i; - if( simple_struct ) - for( i = 0; i < struct_count; i++ ) - cvTsReleaseSimpleGraph( (CvTsSimpleGraph**)&simple_struct[i] ); - CxCore_DynStructBaseTest::clear(); -} - - -int CxCore_GraphTest::test_graph_ops( int iters ) -{ - const int max_op = 4; - int i, k, code = -1; - int max_elem_size = 0; - int idx, idx0; - CvGraphVtx *vtx = 0, *vtx2 = 0, *vtx3 = 0; - CvGraphEdge* edge = 0, *edge2 = 0; - CvMat* elem_mat = 0; - CvRNG* rng = ts->get_rng(); - //int max_active_count = 0, mean_active_count = 0; - - CV_FUNCNAME( "CxCore_GraphTest::test_graph_ops" ); - - __BEGIN__; - - for( i = 0; i < struct_count; i++ ) - { - CvGraph* graph = (CvGraph*)cxcore_struct[i]; - max_elem_size = MAX( max_elem_size, graph->elem_size ); - max_elem_size = MAX( max_elem_size, graph->edges->elem_size ); - } - - CV_CALL( elem_mat = cvCreateMat( 1, max_elem_size, CV_8UC1 )); - - for( iter = 0; iter < iters; iter++ ) - { - struct_idx = cvTsRandInt(rng) % struct_count; - CvGraph* graph = (CvGraph*)cxcore_struct[struct_idx]; - CvTsSimpleGraph* sgraph = (CvTsSimpleGraph*)simple_struct[struct_idx]; - CvSet* edges = graph->edges; - schar *vtx_data; - char *edge_data; - int pure_vtx_size = sgraph->vtx->elem_size - 1, - pure_edge_size = sgraph->edge_size - 1; - int prev_vtx_total = graph->total, - prev_edge_total = graph->edges->total, - prev_vtx_count = graph->active_count, - prev_edge_count = graph->edges->active_count; - int op = cvTsRandInt(rng) % max_op; - int pass_data = 0, vtx_degree0 = 0, vtx_degree = 0; - CvSetElem *first_free, *next_free; - - if( cvTsRandInt(rng) % 200 == 0 ) // clear graph - { - int prev_vtx_count = graph->total, prev_edge_count = graph->edges->total; - - cvClearGraph( graph ); - cvTsClearSimpleGraph( sgraph ); - - CV_TS_SEQ_CHECK_CONDITION( graph->active_count == 0 && graph->total == 0 && - graph->first == 0 && graph->free_elems == 0 && - (graph->free_blocks != 0 || prev_vtx_count == 0), - "The graph is not empty after clearing" ); - - CV_TS_SEQ_CHECK_CONDITION( edges->active_count == 0 && edges->total == 0 && - edges->first == 0 && edges->free_elems == 0 && - (edges->free_blocks != 0 || prev_edge_count == 0), - "The graph is not empty after clearing" ); - } - else if( op == 0 ) // add vertex - { - if( sgraph->vtx->free_count == 0 ) - continue; - - first_free = graph->free_elems; - next_free = first_free ? first_free->next_free : 0; - - if( pure_vtx_size ) - { - elem_mat->cols = graph->elem_size; - cvRandArr( rng, elem_mat, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(255) ); - } - - vtx = (CvGraphVtx*)elem_mat->data.ptr; - idx0 = cvTsSimpleGraphAddVertex( sgraph, vtx + 1 ); - - pass_data = cvTsRandInt(rng) % 2; - CV_CALL( idx = cvGraphAddVtx( graph, pass_data ? vtx : 0, &vtx2 )); - - if( !pass_data && pure_vtx_size > 0 ) - memcpy( vtx2 + 1, vtx + 1, pure_vtx_size ); - - vtx3 = cvGetGraphVtx( graph, idx ); - - CV_TS_SEQ_CHECK_CONDITION( (CV_IS_SET_ELEM(vtx3) && vtx3->flags == idx && - vtx3->first == 0) || (idx == idx0 && vtx3 == vtx2 && - (!pass_data || pure_vtx_size == 0 || - memcmp(vtx3 + 1, vtx + 1, pure_vtx_size) == 0)), - "The added element is not correct" ); - - CV_TS_SEQ_CHECK_CONDITION( (!first_free || first_free == (CvSetElem*)vtx3) && - (!next_free || graph->free_elems == next_free) && - graph->active_count == prev_vtx_count + 1, - "The free node list is modified incorrectly" ); - } - else if( op == 1 ) // remove vertex - { - idx = cvTsRandInt(rng) % sgraph->vtx->max_count; - if( sgraph->vtx->free_count == sgraph->vtx->max_count || idx >= sgraph->vtx->count ) - continue; - - vtx_data = cvTsSimpleGraphFindVertex(sgraph, idx); - if( vtx_data == 0 ) - continue; - - vtx_degree0 = cvTsSimpleGraphVertexDegree( sgraph, idx ); - first_free = graph->free_elems; - - CV_CALL( vtx = cvGetGraphVtx( graph, idx )); - CV_TS_SEQ_CHECK_CONDITION( CV_IS_SET_ELEM(vtx) && vtx->flags == idx && - (pure_vtx_size == 0 || memcmp( vtx + 1, vtx_data, pure_vtx_size) == 0), - "cvGetGraphVtx returned wrong element" ); - - if( cvTsRandInt(rng) % 2 ) - { - CV_CALL( vtx_degree = cvGraphVtxDegreeByPtr( graph, vtx )); - CV_CALL( cvGraphRemoveVtxByPtr( graph, vtx )); - } - else - { - CV_CALL( vtx_degree = cvGraphVtxDegree( graph, idx )); - CV_CALL( cvGraphRemoveVtx( graph, idx )); - } - - cvTsSimpleGraphRemoveVertex( sgraph, idx ); - - CV_TS_SEQ_CHECK_CONDITION( vtx_degree == vtx_degree0, - "Number of incident edges is different in two graph representations" ); - - CV_TS_SEQ_CHECK_CONDITION( !CV_IS_SET_ELEM(vtx) && !cvGetGraphVtx(graph, idx) && - (vtx->flags & CV_SET_ELEM_IDX_MASK) == idx, - "cvGraphRemoveVtx[ByPtr] didn't release the vertex properly" ); - - CV_TS_SEQ_CHECK_CONDITION( graph->edges->active_count == prev_edge_count - vtx_degree, - "cvGraphRemoveVtx[ByPtr] didn't remove all the incident edges " - "(or removed some extra)" ); - - CV_TS_SEQ_CHECK_CONDITION( ((CvSetElem*)vtx)->next_free == first_free && - graph->free_elems == (CvSetElem*)vtx && - graph->active_count == prev_vtx_count - 1, - "The free node list has not been updated properly" ); - } - else if( op == 2 ) // add edge - { - int v_idx[2] = {0,0}, res = 0; - int v_prev_degree[2] = {0,0}, v_degree[2] = {0,0}; - - if( sgraph->vtx->free_count >= sgraph->vtx->max_count-1 ) - continue; - - for( i = 0, k = 0; i < 10; i++ ) - { - int j = cvTsRandInt(rng) % sgraph->vtx->count; - vtx_data = cvTsSimpleGraphFindVertex( sgraph, j ); - if( vtx_data ) - { - v_idx[k] = j; - if( k == 0 ) - k++; - else if( v_idx[0] != v_idx[1] && - cvTsSimpleGraphFindEdge( sgraph, v_idx[0], v_idx[1] ) == 0 ) - { - k++; - break; - } - } - } - - if( k < 2 ) - continue; - - first_free = graph->edges->free_elems; - next_free = first_free ? first_free->next_free : 0; - - CV_CALL( edge = cvFindGraphEdge( graph, v_idx[0], v_idx[1] )); - CV_TS_SEQ_CHECK_CONDITION( edge == 0, "Extra edge appeared in the graph" ); - - if( pure_edge_size > 0 ) - { - elem_mat->cols = graph->edges->elem_size; - cvRandArr( rng, elem_mat, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(255) ); - } - edge = (CvGraphEdge*)elem_mat->data.ptr; - - // assign some default weight that is easy to check for - // consistensy, 'cause an edge weight is not stored - // in the simple graph - edge->weight = (float)(v_idx[0] + v_idx[1]); - pass_data = cvTsRandInt(rng) % 2; - - CV_CALL( vtx = cvGetGraphVtx( graph, v_idx[0] )); - CV_CALL( vtx2 = cvGetGraphVtx( graph, v_idx[1] )); - CV_TS_SEQ_CHECK_CONDITION( vtx != 0 && vtx2 != 0 && vtx->flags == v_idx[0] && - vtx2->flags == v_idx[1], "Some of the vertices are missing" ); - - if( cvTsRandInt(rng) % 2 ) - { - CV_CALL( v_prev_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx )); - CV_CALL( v_prev_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 )); - CV_CALL( res = cvGraphAddEdgeByPtr(graph, vtx, vtx2, pass_data ? edge : 0, &edge2)); - CV_CALL( v_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx )); - CV_CALL( v_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 )); - } - else - { - CV_CALL( v_prev_degree[0] = cvGraphVtxDegree( graph, v_idx[0] )); - CV_CALL( v_prev_degree[1] = cvGraphVtxDegree( graph, v_idx[1] )); - CV_CALL( res = cvGraphAddEdge(graph, v_idx[0], v_idx[1], pass_data ? edge : 0, &edge2)); - CV_CALL( v_degree[0] = cvGraphVtxDegree( graph, v_idx[0] )); - CV_CALL( v_degree[1] = cvGraphVtxDegree( graph, v_idx[1] )); - } - - //edge3 = (CvGraphEdge*)cvGetSetElem( graph->edges, idx ); - CV_TS_SEQ_CHECK_CONDITION( res == 1 && edge2 != 0 && CV_IS_SET_ELEM(edge2) && - ((edge2->vtx[0] == vtx && edge2->vtx[1] == vtx2) || - (!CV_IS_GRAPH_ORIENTED(graph) && edge2->vtx[0] == vtx2 && edge2->vtx[1] == vtx)) && - (!pass_data || pure_edge_size == 0 || memcmp( edge2 + 1, edge + 1, pure_edge_size ) == 0), - "The edge has been added incorrectly" ); - - if( !pass_data ) - { - if( pure_edge_size > 0 ) - memcpy( edge2 + 1, edge + 1, pure_edge_size ); - edge2->weight = edge->weight; - } - - CV_TS_SEQ_CHECK_CONDITION( v_degree[0] == v_prev_degree[0] + 1 && - v_degree[1] == v_prev_degree[1] + 1, - "The vertices lists have not been updated properly" ); - - cvTsSimpleGraphAddEdge( sgraph, v_idx[0], v_idx[1], edge + 1 ); - - CV_TS_SEQ_CHECK_CONDITION( (!first_free || first_free == (CvSetElem*)edge2) && - (!next_free || graph->edges->free_elems == next_free) && - graph->edges->active_count == prev_edge_count + 1, - "The free node list is modified incorrectly" ); - } - else if( op == 3 ) // find & remove edge - { - int v_idx[2] = {0,0}, by_ptr; - int v_prev_degree[2] = {0,0}, v_degree[2] = {0,0}; - - if( sgraph->vtx->free_count >= sgraph->vtx->max_count-1 ) - continue; - - edge_data = 0; - for( i = 0, k = 0; i < 10; i++ ) - { - int j = cvTsRandInt(rng) % sgraph->vtx->count; - vtx_data = cvTsSimpleGraphFindVertex( sgraph, j ); - if( vtx_data ) - { - v_idx[k] = j; - if( k == 0 ) - k++; - else - { - edge_data = cvTsSimpleGraphFindEdge( sgraph, v_idx[0], v_idx[1] ); - if( edge_data ) - { - k++; - break; - } - } - } - } - - if( k < 2 ) - continue; - - by_ptr = cvTsRandInt(rng) % 2; - first_free = graph->edges->free_elems; - - CV_CALL( vtx = cvGetGraphVtx( graph, v_idx[0] )); - CV_CALL( vtx2 = cvGetGraphVtx( graph, v_idx[1] )); - CV_TS_SEQ_CHECK_CONDITION( vtx != 0 && vtx2 != 0 && vtx->flags == v_idx[0] && - vtx2->flags == v_idx[1], "Some of the vertices are missing" ); - - if( by_ptr ) - { - CV_CALL( edge = cvFindGraphEdgeByPtr( graph, vtx, vtx2 )); - CV_CALL( v_prev_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx )); - CV_CALL( v_prev_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 )); - } - else - { - CV_CALL( edge = cvFindGraphEdge( graph, v_idx[0], v_idx[1] )); - CV_CALL( v_prev_degree[0] = cvGraphVtxDegree( graph, v_idx[0] )); - CV_CALL( v_prev_degree[1] = cvGraphVtxDegree( graph, v_idx[1] )); - } - - idx = edge->flags; - - CV_TS_SEQ_CHECK_CONDITION( edge != 0 && edge->weight == v_idx[0] + v_idx[1] && - ((edge->vtx[0] == vtx && edge->vtx[1] == vtx2) || - (!CV_IS_GRAPH_ORIENTED(graph) && edge->vtx[1] == vtx && edge->vtx[0] == vtx2)) && - (pure_edge_size == 0 || memcmp(edge + 1, edge_data, pure_edge_size) == 0), - "An edge is missing or incorrect" ); - - if( by_ptr ) - { - CV_CALL( cvGraphRemoveEdgeByPtr( graph, vtx, vtx2 )); - CV_CALL( edge2 = cvFindGraphEdgeByPtr( graph, vtx, vtx2 )); - CV_CALL( v_degree[0] = cvGraphVtxDegreeByPtr( graph, vtx )); - CV_CALL( v_degree[1] = cvGraphVtxDegreeByPtr( graph, vtx2 )); - } - else - { - CV_CALL( cvGraphRemoveEdge(graph, v_idx[0], v_idx[1] )); - CV_CALL( edge2 = cvFindGraphEdge( graph, v_idx[0], v_idx[1] )); - CV_CALL( v_degree[0] = cvGraphVtxDegree( graph, v_idx[0] )); - CV_CALL( v_degree[1] = cvGraphVtxDegree( graph, v_idx[1] )); - } - - CV_TS_SEQ_CHECK_CONDITION( !edge2 && !CV_IS_SET_ELEM(edge), - "The edge has not been removed from the edge set" ); - - CV_TS_SEQ_CHECK_CONDITION( v_degree[0] == v_prev_degree[0] - 1 && - v_degree[1] == v_prev_degree[1] - 1, - "The vertices lists have not been updated properly" ); - - cvTsSimpleGraphRemoveEdge( sgraph, v_idx[0], v_idx[1] ); - - CV_TS_SEQ_CHECK_CONDITION( graph->edges->free_elems == (CvSetElem*)edge && - graph->edges->free_elems->next_free == first_free && - graph->edges->active_count == prev_edge_count - 1, - "The free edge list has not been modified properly" ); - } - - //max_active_count = MAX( max_active_count, graph->active_count ); - //mean_active_count += graph->active_count; - - CV_TS_SEQ_CHECK_CONDITION( graph->active_count == sgraph->vtx->max_count - sgraph->vtx->free_count && - graph->total >= graph->active_count && - (graph->total == 0 || graph->total >= prev_vtx_total), - "The total number of graph vertices is not correct" ); - - CV_TS_SEQ_CHECK_CONDITION( graph->edges->total >= graph->edges->active_count && - (graph->edges->total == 0 || graph->edges->total >= prev_edge_total), - "The total number of graph vertices is not correct" ); - - // CvGraph and simple graph do not neccessary have the same "total" (active & free) number, - // so pass "graph->total" (or "graph->edges->total") to skip that check - test_seq_block_consistence( struct_idx, (CvSeq*)graph, graph->total ); - test_seq_block_consistence( struct_idx, (CvSeq*)graph->edges, graph->edges->total ); - update_progressbar(); - } - - code = 0; - //ts->printf( CvTS::LOG, "\ngeneration %d. max_active_count = %d,\n\tmean_active_count = %d\n", - // gen, max_active_count, mean_active_count/iters ); - - __END__; - - if( elem_mat ) - elem_mat->cols = 1; // just to skip a consistency check - cvReleaseMat( &elem_mat ); - - return code; -} - - -void CxCore_GraphTest::run( int ) -{ - CvRNG* rng = ts->get_rng(); - int i, k; - double t; - - CV_FUNCNAME( "CxCore_GraphTest::run" ); - - __BEGIN__; - - clear(); - test_progress = -1; - - simple_struct = (void**)cvAlloc( struct_count * sizeof(simple_struct[0]) ); - memset( simple_struct, 0, struct_count * sizeof(simple_struct[0]) ); - cxcore_struct = (void**)cvAlloc( struct_count * sizeof(cxcore_struct[0]) ); - memset( cxcore_struct, 0, struct_count * sizeof(cxcore_struct[0]) ); - - for( gen = 0; gen < generations; gen++ ) - { - struct_idx = iter = -1; - t = cvTsRandReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - int block_size = cvRound( exp(t * CV_LOG2) ); - block_size = MAX(block_size, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - - storage = cvCreateMemStorage(block_size); - - for( i = 0; i < struct_count; i++ ) - { - int pure_elem_size[2], elem_size[2]; - int is_oriented = (gen + i) % 2; - for( k = 0; k < 2; k++ ) - { - t = cvTsRandReal(rng)*(max_log_elem_size - min_log_elem_size) + min_log_elem_size; - int pe = cvRound( exp(t * CV_LOG2) ) - 1; // pure_elem_size==0 does also make sense - int delta = k == 0 ? sizeof(CvGraphVtx) : sizeof(CvGraphEdge); - int e = pe + delta; - e = (e + sizeof(size_t) - 1) & ~(sizeof(size_t)-1); - e = MIN( e, (int)(storage->block_size - sizeof(CvMemBlock) - - sizeof(CvSeqBlock) - sizeof(void*)) ); - pe = MIN(pe, e - delta); - pure_elem_size[k] = pe; - elem_size[k] = e; - } - - cvTsReleaseSimpleGraph( (CvTsSimpleGraph**)&simple_struct[i] ); - simple_struct[i] = cvTsCreateSimpleGraph( max_struct_size/4, pure_elem_size[0], - pure_elem_size[1], is_oriented ); - CV_CALL( cxcore_struct[i] = cvCreateGraph( is_oriented ? CV_ORIENTED_GRAPH : CV_GRAPH, - sizeof(CvGraph), elem_size[0], elem_size[1], - storage )); - } - - if( test_graph_ops( iterations*10 ) < 0 ) - EXIT; - - cvReleaseMemStorage( &storage ); - } - - __END__; -} - -CxCore_GraphTest graph_test; - - - -//////////// graph scan test ////////////// - -class CxCore_GraphScanTest : public CxCore_DynStructBaseTest -{ -public: - CxCore_GraphScanTest(); - void run( int ); - -protected: - //int test_seq_block_consistence( int struct_idx ); - int create_random_graph( int ); -}; - - -CxCore_GraphScanTest::CxCore_GraphScanTest(): - CxCore_DynStructBaseTest( "ds-graphscan", "cvCreateGraph, " - "cvGraphAddVtx, cvGraphAddEdge, cvNextGraphItem, " - "cvCreateGraphScanner, cvReleaseGraphScanner" ) -{ - iterations = 100; - struct_count = 1; -} - - -int CxCore_GraphScanTest::create_random_graph( int _struct_idx ) -{ - CvRNG* rng = ts->get_rng(); - int is_oriented = cvTsRandInt(rng) % 2; - int i, vtx_count = cvTsRandInt(rng) % max_struct_size; - int edge_count = cvTsRandInt(rng) % MAX(vtx_count*20, 1); - CvGraph* graph; - - CV_FUNCNAME( "CxCore_GraphScanTest::create_random_graph" ); - - __BEGIN__; - - struct_idx = _struct_idx; - - CV_CALL( cxcore_struct[_struct_idx] = graph = cvCreateGraph( - is_oriented ? CV_ORIENTED_GRAPH : CV_GRAPH, - sizeof(CvGraph), sizeof(CvGraphVtx), sizeof(CvGraphEdge), storage )); - - for( i = 0; i < vtx_count; i++ ) - CV_CALL( cvGraphAddVtx( graph )); - - assert( graph->active_count == vtx_count ); - - for( i = 0; i < edge_count; i++ ) - { - int j = cvTsRandInt(rng) % vtx_count; - int k = cvTsRandInt(rng) % vtx_count; - - if( j != k ) - CV_CALL( cvGraphAddEdge( graph, j, k )); - } - - assert( graph->active_count == vtx_count && graph->edges->active_count <= edge_count ); - - __END__; - - return 0; -} - - -void CxCore_GraphScanTest::run( int ) -{ - CvRNG* rng = ts->get_rng(); - CvGraphScanner* scanner = 0; - CvMat* vtx_mask = 0, *edge_mask = 0; - double t; - int i; - - CV_FUNCNAME( "CxCore_GraphTest::run" ); - - __BEGIN__; - - clear(); - test_progress = -1; - - cxcore_struct = (void**)cvAlloc( struct_count * sizeof(cxcore_struct[0]) ); - memset( cxcore_struct, 0, struct_count * sizeof(cxcore_struct[0]) ); - - for( gen = 0; gen < generations; gen++ ) - { - struct_idx = iter = -1; - t = cvTsRandReal(rng)*(max_log_storage_block_size - min_log_storage_block_size) + min_log_storage_block_size; - int storage_blocksize = cvRound( exp(t * CV_LOG2) ); - storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraph) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphEdge) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - storage_blocksize = MAX(storage_blocksize, (int)(sizeof(CvGraphVtx) + sizeof(CvMemBlock) + sizeof(CvSeqBlock))); - storage = cvCreateMemStorage(storage_blocksize); - - if( gen == 0 ) - { - // special regression test for one sample graph. - // !!! ATTENTION !!! The test relies on the particular order of the inserted edges - // (LIFO: the edge inserted last goes first in the list of incident edges). - // if it is changed, the test will have to be modified. - - int vtx_count = -1, edge_count = 0, edges[][3] = - { - {0,4,'f'}, {0,1,'t'}, {1,4,'t'}, {1,2,'t'}, {2,3,'t'}, {4,3,'c'}, {3,1,'b'}, - {5,7,'t'}, {7,5,'b'}, {5,6,'t'}, {6,0,'c'}, {7,6,'c'}, {6,4,'c'}, {-1,-1,0} - }; - - CvGraph* graph; - CV_CALL( graph = cvCreateGraph( CV_ORIENTED_GRAPH, sizeof(CvGraph), - sizeof(CvGraphVtx), sizeof(CvGraphEdge), storage )); - - for( i = 0; edges[i][0] >= 0; i++ ) - { - vtx_count = MAX( vtx_count, edges[i][0] ); - vtx_count = MAX( vtx_count, edges[i][1] ); - } - vtx_count++; - - for( i = 0; i < vtx_count; i++ ) - CV_CALL( cvGraphAddVtx( graph )); - - for( i = 0; edges[i][0] >= 0; i++ ) - { - CvGraphEdge* edge; - CV_CALL( cvGraphAddEdge( graph, edges[i][0], edges[i][1], 0, &edge )); - edge->weight = (float)edges[i][2]; - } - - edge_count = i; - CV_CALL( scanner = cvCreateGraphScanner( graph, 0, CV_GRAPH_ALL_ITEMS )); - - for(;;) - { - int code, a = -1, b = -1; - const char* event = ""; - CV_CALL( code = cvNextGraphItem( scanner )); - - switch( code ) - { - case CV_GRAPH_VERTEX: - event = "Vertex"; - vtx_count--; - a = cvGraphVtxIdx( graph, scanner->vtx ); - break; - case CV_GRAPH_TREE_EDGE: - event = "Tree Edge"; - edge_count--; - CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'t', - "Invalid edge type" ); - a = cvGraphVtxIdx( graph, scanner->vtx ); - b = cvGraphVtxIdx( graph, scanner->dst ); - break; - case CV_GRAPH_BACK_EDGE: - event = "Back Edge"; - edge_count--; - CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'b', - "Invalid edge type" ); - a = cvGraphVtxIdx( graph, scanner->vtx ); - b = cvGraphVtxIdx( graph, scanner->dst ); - break; - case CV_GRAPH_CROSS_EDGE: - event = "Cross Edge"; - edge_count--; - CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'c', - "Invalid edge type" ); - a = cvGraphVtxIdx( graph, scanner->vtx ); - b = cvGraphVtxIdx( graph, scanner->dst ); - break; - case CV_GRAPH_FORWARD_EDGE: - event = "Forward Edge"; - edge_count--; - CV_TS_SEQ_CHECK_CONDITION( scanner->edge->weight == (float)'f', - "Invalid edge type" ); - a = cvGraphVtxIdx( graph, scanner->vtx ); - b = cvGraphVtxIdx( graph, scanner->dst ); - break; - case CV_GRAPH_BACKTRACKING: - event = "Backtracking"; - a = cvGraphVtxIdx( graph, scanner->vtx ); - break; - case CV_GRAPH_NEW_TREE: - event = "New search tree"; - break; - case CV_GRAPH_OVER: - event = "End of procedure"; - break; - default: - CV_TS_SEQ_CHECK_CONDITION( 0, "Invalid code appeared during graph scan" ); - } - - ts->printf( CvTS::LOG, "%s", event ); - if( a >= 0 ) - { - if( b >= 0 ) - ts->printf( CvTS::LOG, ": (%d,%d)", a, b ); - else - ts->printf( CvTS::LOG, ": %d", a ); - } - - ts->printf( CvTS::LOG, "\n" ); - - if( code < 0 ) - break; - } - - CV_TS_SEQ_CHECK_CONDITION( vtx_count == 0 && edge_count == 0, - "Not every vertex/edge has been visited" ); - update_progressbar(); - } - - // for a random graph the test just checks that every graph vertex and - // every edge is vitisted during the scan - for( iter = 0; iter < iterations; iter++ ) - { - create_random_graph(0); - CvGraph* graph = (CvGraph*)cxcore_struct[0]; - - // iterate twice to check that scanner doesn't damage the graph - for( i = 0; i < 2; i++ ) - { - CvGraphVtx* start_vtx = cvTsRandInt(rng) % 2 || graph->active_count == 0 ? 0 : - cvGetGraphVtx( graph, cvTsRandInt(rng) % graph->active_count ); - - CV_CALL( scanner = cvCreateGraphScanner( graph, start_vtx, CV_GRAPH_ALL_ITEMS )); - - if( !vtx_mask || vtx_mask->cols < graph->active_count ) - { - cvReleaseMat( &vtx_mask ); - CV_CALL( vtx_mask = cvCreateMat( 1, MAX(graph->active_count, 1), CV_8UC1 )); - } - - if( !edge_mask || edge_mask->cols < graph->edges->active_count ) - { - cvReleaseMat( &edge_mask ); - CV_CALL( edge_mask = cvCreateMat( 1, MAX(graph->edges->active_count, 1), CV_8UC1 )); - } - - cvZero( vtx_mask ); - cvZero( edge_mask ); - - for(;;) - { - int code; - CV_CALL( code = cvNextGraphItem( scanner )); - - if( code == CV_GRAPH_OVER ) - break; - else if( code & CV_GRAPH_ANY_EDGE ) - { - int edge_idx = scanner->edge->flags & CV_SET_ELEM_IDX_MASK; - - CV_TS_SEQ_CHECK_CONDITION( edge_idx < graph->edges->active_count && - edge_mask->data.ptr[edge_idx] == 0, - "The edge is not found or visited for the second time" ); - edge_mask->data.ptr[edge_idx] = 1; - } - else if( code & CV_GRAPH_VERTEX ) - { - int vtx_idx = scanner->vtx->flags & CV_SET_ELEM_IDX_MASK; - - CV_TS_SEQ_CHECK_CONDITION( vtx_idx < graph->active_count && - vtx_mask->data.ptr[vtx_idx] == 0, - "The vtx is not found or visited for the second time" ); - vtx_mask->data.ptr[vtx_idx] = 1; - } - } - - cvReleaseGraphScanner( &scanner ); - - CV_TS_SEQ_CHECK_CONDITION( cvNorm(vtx_mask,0,CV_L1) == graph->active_count && - cvNorm(edge_mask,0,CV_L1) == graph->edges->active_count, - "Some vertices or edges have not been visited" ); - update_progressbar(); - } - cvClearMemStorage( storage ); - } - - cvReleaseMemStorage( &storage ); - } - - __END__; - - cvReleaseGraphScanner( &scanner ); - cvReleaseMat( &vtx_mask ); - cvReleaseMat( &edge_mask ); -} - -CxCore_GraphScanTest graphscan_test; - -/* End of file. */ diff --git a/tests/cxcore/src/adxt.cpp b/tests/cxcore/src/adxt.cpp deleted file mode 100644 index 6f9783e..0000000 --- a/tests/cxcore/src/adxt.cpp +++ /dev/null @@ -1,1011 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -////////////////////////////////////////////////////////////////////////////////////////// -////////////////// tests for discrete linear transforms (FFT, DCT ...) /////////////////// -////////////////////////////////////////////////////////////////////////////////////////// - -#include "cxcoretest.h" -#include - -typedef struct CvTsComplex32f -{ - float re, im; -} -CvTsComplex32f; - -typedef struct CvTsComplex64f -{ - double re, im; -} -CvTsComplex64f; - -static CvMat* cvTsInitDFTWave( int n, int inv ) -{ - int i; - double angle = (inv ? 1 : -1)*CV_PI*2/n; - CvTsComplex64f wi, w1; - CvMat* wave = cvCreateMat( 1, n, CV_64FC2 ); - CvTsComplex64f* w = (CvTsComplex64f*)wave->data.db; - - w1.re = cos(angle); - w1.im = sin(angle); - w[0].re = wi.re = 1.; - w[0].im = wi.im = 0.; - - for( i = 1; i < n; i++ ) - { - double t = wi.re*w1.re - wi.im*w1.im; - wi.im = wi.re*w1.im + wi.im*w1.re; - wi.re = t; - w[i] = wi; - } - - return wave; -} - - -static void cvTsDFT_1D( const CvMat* _src, CvMat* _dst, int flags, CvMat* wave=0 ) -{ - int i, j, k, n = _dst->cols + _dst->rows - 1; - const CvMat* wave0 = wave; - double scale = (flags & CV_DXT_SCALE) ? 1./n : 1.; - assert( _src->cols + _src->rows - 1 == n ); - int src_step = 1, dst_step = 1; - CvTsComplex64f* w; - - assert( CV_ARE_TYPES_EQ(_src,_dst) && _src->rows*_src->cols == _dst->rows*_dst->cols ); - - if( !wave ) - wave = cvTsInitDFTWave( n, flags & CV_DXT_INVERSE ); - - w = (CvTsComplex64f*)wave->data.db; - if( !CV_IS_MAT_CONT(_src->type) ) - src_step = _src->step/CV_ELEM_SIZE(_src->type); - if( !CV_IS_MAT_CONT(_dst->type) ) - dst_step = _dst->step/CV_ELEM_SIZE(_dst->type); - - if( CV_MAT_TYPE(_src->type) == CV_32FC2 ) - { - CvTsComplex32f* dst = (CvTsComplex32f*)_dst->data.fl; - for( i = 0; i < n; i++, dst += dst_step ) - { - CvTsComplex32f* src = (CvTsComplex32f*)_src->data.fl; - CvTsComplex64f sum = {0,0}; - int delta = i; - k = 0; - - for( j = 0; j < n; j++, src += src_step ) - { - sum.re += src->re*w[k].re - src->im*w[k].im; - sum.im += src->re*w[k].im + src->im*w[k].re; - k += delta; - k -= (k >= n ? n : 0); - } - - dst->re = (float)(sum.re*scale); - dst->im = (float)(sum.im*scale); - } - } - else if( CV_MAT_TYPE(_src->type) == CV_64FC2 ) - { - CvTsComplex64f* dst = (CvTsComplex64f*)_dst->data.db; - for( i = 0; i < n; i++, dst += dst_step ) - { - CvTsComplex64f* src = (CvTsComplex64f*)_src->data.db; - CvTsComplex64f sum = {0,0}; - int delta = i; - k = 0; - - for( j = 0; j < n; j++, src += src_step ) - { - sum.re += src->re*w[k].re - src->im*w[k].im; - sum.im += src->re*w[k].im + src->im*w[k].re; - k += delta; - k -= (k >= n ? n : 0); - } - - dst->re = sum.re*scale; - dst->im = sum.im*scale; - } - } - else - assert(0); - - if( !wave0 ) - cvReleaseMat( &wave ); -} - - -static void cvTsDFT_2D( const CvMat* src, CvMat* dst, int flags ) -{ - int i; - CvMat* tmp = cvCreateMat( dst->cols, dst->rows, dst->type ); - CvMat* wave = cvTsInitDFTWave( dst->cols, flags & CV_DXT_INVERSE ); - - // 1. row-wise transform - for( i = 0; i < dst->rows; i++ ) - { - CvMat src_row, dst_row; - cvGetRow( src, &src_row, i ); - cvGetCol( tmp, &dst_row, i ); - cvTsDFT_1D( &src_row, &dst_row, flags, wave ); - } - - if( !(flags & CV_DXT_ROWS) ) - { - if( dst->cols != dst->rows ) - { - cvReleaseMat( &wave ); - wave = cvTsInitDFTWave( dst->rows, flags & CV_DXT_INVERSE ); - } - - // 2. column-wise transform - for( i = 0; i < dst->cols; i++ ) - { - CvMat src_row, dst_row; - cvGetRow( tmp, &src_row, i ); - cvGetCol( dst, &dst_row, i ); - cvTsDFT_1D( &src_row, &dst_row, flags, wave ); - } - } - else - cvTsTranspose( tmp, dst ); - - cvReleaseMat( &wave ); - cvReleaseMat( &tmp ); -} - - -static CvMat* cvTsInitDCTWave( int n, int inv ) -{ - int i, k; - double angle = CV_PI*0.5/n; - CvMat* wave = cvCreateMat( n, n, CV_64FC1 ); - - double scale = sqrt(1./n); - for( k = 0; k < n; k++ ) - wave->data.db[k] = scale; - scale *= sqrt(2.); - for( i = 1; i < n; i++ ) - for( k = 0; k < n; k++ ) - wave->data.db[i*n + k] = scale*cos( angle*i*(2*k + 1) ); - - if( inv ) - cvTsTranspose( wave, wave ); - - return wave; -} - - -static void cvTsDCT_1D( const CvMat* _src, CvMat* _dst, int flags, CvMat* wave=0 ) -{ - int i, j, n = _dst->cols + _dst->rows - 1; - const CvMat* wave0 = wave; - assert( _src->cols + _src->rows - 1 == n); - int src_step = 1, dst_step = 1; - double* w; - - assert( CV_ARE_TYPES_EQ(_src,_dst) && _src->rows*_src->cols == _dst->rows*_dst->cols ); - - if( !wave ) - wave = cvTsInitDCTWave( n, flags & CV_DXT_INVERSE ); - w = wave->data.db; - - if( !CV_IS_MAT_CONT(_src->type) ) - src_step = _src->step/CV_ELEM_SIZE(_src->type); - if( !CV_IS_MAT_CONT(_dst->type) ) - dst_step = _dst->step/CV_ELEM_SIZE(_dst->type); - - if( CV_MAT_TYPE(_src->type) == CV_32FC1 ) - { - float *dst = _dst->data.fl; - - for( i = 0; i < n; i++, dst += dst_step ) - { - const float* src = _src->data.fl; - double sum = 0; - - for( j = 0; j < n; j++, src += src_step ) - sum += src[0]*w[j]; - w += n; - dst[0] = (float)sum; - } - } - else if( CV_MAT_TYPE(_src->type) == CV_64FC1 ) - { - double *dst = _dst->data.db; - - for( i = 0; i < n; i++, dst += dst_step ) - { - const double* src = _src->data.db; - double sum = 0; - - for( j = 0; j < n; j++, src += src_step ) - sum += src[0]*w[j]; - w += n; - dst[0] = sum; - } - } - else - assert(0); - - if( !wave0 ) - cvReleaseMat( &wave ); -} - - -static void cvTsDCT_2D( const CvMat* src, CvMat* dst, int flags ) -{ - int i; - CvMat* tmp = cvCreateMat( dst->cols, dst->rows, dst->type ); - CvMat* wave = cvTsInitDCTWave( dst->cols, flags & CV_DXT_INVERSE ); - - // 1. row-wise transform - for( i = 0; i < dst->rows; i++ ) - { - CvMat src_row, dst_row; - cvGetRow( src, &src_row, i ); - cvGetCol( tmp, &dst_row, i ); - cvTsDCT_1D( &src_row, &dst_row, flags, wave ); - } - - if( !(flags & CV_DXT_ROWS) ) - { - if( dst->cols != dst->rows ) - { - cvReleaseMat( &wave ); - wave = cvTsInitDCTWave( dst->rows, flags & CV_DXT_INVERSE ); - } - - // 2. column-wise transform - for( i = 0; i < dst->cols; i++ ) - { - CvMat src_row, dst_row; - cvGetRow( tmp, &src_row, i ); - cvGetCol( dst, &dst_row, i ); - cvTsDCT_1D( &src_row, &dst_row, flags, wave ); - } - } - else - { - cvTranspose( tmp, dst ); - } - - cvReleaseMat( &wave ); - cvReleaseMat( &tmp ); -} - - -static void cvTsConvertFromCCS( const CvMat* _src0, const CvMat* _src1, - CvMat* _dst, int flags ) -{ - if( _dst->rows > 1 && (_dst->cols > 1 || (flags & CV_DXT_ROWS)) ) - { - int i, count = _dst->rows, len = _dst->cols; - int is_2d = (flags & CV_DXT_ROWS) == 0; - CvMat src0_row, src1_row, dst_row; - for( i = 0; i < count; i++ ) - { - int j = !is_2d || i == 0 ? i : count - i; - cvGetRow( _src0, &src0_row, i ); - cvGetRow( _src1, &src1_row, j ); - cvGetRow( _dst, &dst_row, i ); - cvTsConvertFromCCS( &src0_row, &src1_row, &dst_row, 0 ); - } - - if( is_2d ) - { - cvGetCol( _src0, &src0_row, 0 ); - cvGetCol( _dst, &dst_row, 0 ); - cvTsConvertFromCCS( &src0_row, &src0_row, &dst_row, 0 ); - if( (len & 1) == 0 ) - { - cvGetCol( _src0, &src0_row, _src0->cols - 1 ); - cvGetCol( _dst, &dst_row, len/2 ); - cvTsConvertFromCCS( &src0_row, &src0_row, &dst_row, 0 ); - } - } - } - else - { - int i, n = _dst->cols + _dst->rows - 1, n2 = (n+1) >> 1; - int cn = CV_MAT_CN(_src0->type); - int src_step = cn, dst_step = 1; - - if( !CV_IS_MAT_CONT(_dst->type) ) - dst_step = _dst->step/CV_ELEM_SIZE(_dst->type); - - if( !CV_IS_MAT_CONT(_src0->type) ) - src_step = _src0->step/CV_ELEM_SIZE(_src0->type & CV_MAT_DEPTH_MASK); - - if( CV_MAT_DEPTH(_dst->type) == CV_32F ) - { - CvTsComplex32f* dst = (CvTsComplex32f*)_dst->data.fl; - const float* src0 = _src0->data.fl; - const float* src1 = _src1->data.fl; - int delta0, delta1; - - dst->re = src0[0]; - dst->im = 0; - - if( (n & 1) == 0 ) - { - dst[n2*dst_step].re = src0[(cn == 1 ? n-1 : n2)*src_step]; - dst[n2*dst_step].im = 0; - } - - delta0 = src_step; - delta1 = delta0 + (cn == 1 ? src_step : 1); - if( cn == 1 ) - src_step *= 2; - - for( i = 1; i < n2; i++, delta0 += src_step, delta1 += src_step ) - { - float t0 = src0[delta0]; - float t1 = src0[delta1]; - - dst[i*dst_step].re = t0; - dst[i*dst_step].im = t1; - - t0 = src1[delta0]; - t1 = -src1[delta1]; - - dst[(n-i)*dst_step].re = t0; - dst[(n-i)*dst_step].im = t1; - } - } - else - { - CvTsComplex64f* dst = (CvTsComplex64f*)_dst->data.db; - const double* src0 = _src0->data.db; - const double* src1 = _src1->data.db; - int delta0, delta1; - - dst->re = src0[0]; - dst->im = 0; - - if( (n & 1) == 0 ) - { - dst[n2*dst_step].re = src0[(cn == 1 ? n-1 : n2)*src_step]; - dst[n2*dst_step].im = 0; - } - - delta0 = src_step; - delta1 = delta0 + (cn == 1 ? src_step : 1); - if( cn == 1 ) - src_step *= 2; - - for( i = 1; i < n2; i++, delta0 += src_step, delta1 += src_step ) - { - double t0 = src0[delta0]; - double t1 = src0[delta1]; - - dst[i*dst_step].re = t0; - dst[i*dst_step].im = t1; - - t0 = src1[delta0]; - t1 = -src1[delta1]; - - dst[(n-i)*dst_step].re = t0; - dst[(n-i)*dst_step].im = t1; - } - } - } -} - - -static void cvTsFixCCS( CvMat* mat, int cols, int flags ) -{ - int i, rows = mat->rows; - int rows2 = flags & CV_DXT_ROWS ? rows : rows/2 + 1, cols2 = cols/2 + 1; - - assert( cols2 == mat->cols ); - - if( CV_MAT_TYPE(mat->type) == CV_32FC2 ) - { - for( i = 0; i < rows2; i++ ) - { - CvTsComplex32f* row = (CvTsComplex32f*)(mat->data.ptr + mat->step*i); - if( (flags & CV_DXT_ROWS) || i == 0 || (i == rows2 - 1 && rows % 2 == 0) ) - { - row[0].im = 0; - if( cols % 2 == 0 ) - row[cols2-1].im = 0; - } - else - { - CvTsComplex32f* row2 = (CvTsComplex32f*)(mat->data.ptr + mat->step*(rows-i)); - row2[0].re = row[0].re; - row2[0].im = -row[0].im; - - if( cols % 2 == 0 ) - { - row2[cols2-1].re = row[cols2-1].re; - row2[cols2-1].im = -row[cols2-1].im; - } - } - } - } - else if( CV_MAT_TYPE(mat->type) == CV_64FC2 ) - { - for( i = 0; i < rows2; i++ ) - { - CvTsComplex64f* row = (CvTsComplex64f*)(mat->data.ptr + mat->step*i); - if( (flags & CV_DXT_ROWS) || i == 0 || (i == rows2 - 1 && rows % 2 == 0) ) - { - row[0].im = 0; - if( cols % 2 == 0 ) - row[cols2-1].im = 0; - } - else - { - CvTsComplex64f* row2 = (CvTsComplex64f*)(mat->data.ptr + mat->step*(rows-i)); - row2[0].re = row[0].re; - row2[0].im = -row[0].im; - - if( cols % 2 == 0 ) - { - row2[cols2-1].re = row[cols2-1].re; - row2[cols2-1].im = -row[cols2-1].im; - } - } - } - } -} - - -static const CvSize dxt_sizes[] = {{16,1}, {256,1}, {1024,1}, {65536,1}, - {10,1}, {100,1}, {1000,1}, {100000,1}, {256, 256}, {1024,1024}, {-1,-1}}; -static const int dxt_depths[] = { CV_32F, CV_64F, -1 }; -static const char* dxt_param_names[] = { "size", "depth", "transform_type", 0 }; -static const char* dft_transforms[] = { "Fwd_CToC", "Inv_CToC", "Fwd_RToPack", "Inv_PackToR", 0 }; -static const char* mulsp_transforms[] = { "Fwd_CToC", "Fwd_RToPack", 0 }; -static const char* dct_transforms[] = { "Fwd", "Inv", 0 }; - -class CxCore_DXTBaseTestImpl : public CvArrTest -{ -public: - CxCore_DXTBaseTestImpl( const char* test_name, const char* test_funcs, - bool _allow_complex=false, bool _allow_odd=false, - bool _spectrum_mode=false ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - int prepare_test_case( int test_case_idx ); - double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int write_default_params( CvFileStorage* fs ); - int flags; // transformation flags - bool allow_complex, // whether input/output may be complex or not: - // true for DFT and MulSpectrums, false for DCT - allow_odd, // whether input/output may be have odd (!=1) dimensions: - // true for DFT and MulSpectrums, false for DCT - spectrum_mode, // (2 complex/ccs inputs, 1 complex/ccs output): - // true for MulSpectrums, false for DFT and DCT - inplace, // inplace operation (set for each individual test case) - temp_dst; // use temporary destination (for real->ccs DFT and ccs MulSpectrums) - const char** transform_type_list; -}; - - -CxCore_DXTBaseTestImpl::CxCore_DXTBaseTestImpl( const char* test_name, const char* test_funcs, - bool _allow_complex, bool _allow_odd, bool _spectrum_mode ) - : CvArrTest( test_name, test_funcs, "" ), - flags(0), allow_complex(_allow_complex), allow_odd(_allow_odd), - spectrum_mode(_spectrum_mode), inplace(false), temp_dst(false) -{ - test_array[INPUT].push(NULL); - if( spectrum_mode ) - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - max_log_array_size = 9; - element_wise_relative_error = spectrum_mode; - - size_list = (CvSize*)dxt_sizes; - whole_size_list = 0; - depth_list = (int*)dxt_depths; - cn_list = 0; - transform_type_list = 0; -} - - -void CxCore_DXTBaseTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - int depth = cvTsRandInt(rng)%2 + CV_32F; - int cn = !allow_complex || !(bits & 256) ? 1 : 2; - CvSize size; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - flags = bits & (CV_DXT_INVERSE | CV_DXT_SCALE | CV_DXT_ROWS | CV_DXT_MUL_CONJ); - if( spectrum_mode ) - flags &= ~CV_DXT_INVERSE; - types[TEMP][0] = types[TEMP][1] = types[INPUT][0] = - types[OUTPUT][0] = CV_MAKETYPE(depth, cn); - size = sizes[INPUT][0]; - - //size.width = size.width % 10 + 1; - //size.height = size.width % 10 + 1; - //size.width = 1; - //flags &= ~CV_DXT_ROWS; - temp_dst = false; - - if( flags & CV_DXT_ROWS && (bits&1024) ) - { - if( bits&16 ) - size.width = 1; - else - size.height = 1; - flags &= ~CV_DXT_ROWS; - } - - const int P2_MIN_SIZE = 32; - if( ((bits >> 10) & 1) == 0 ) - { - size.width = (size.width / P2_MIN_SIZE)*P2_MIN_SIZE; - size.width = MAX(size.width, 1); - size.height = (size.height / P2_MIN_SIZE)*P2_MIN_SIZE; - size.height = MAX(size.height, 1); - } - - if( !allow_odd ) - { - if( size.width > 1 && (size.width&1) != 0 ) - size.width = (size.width + 1) & -2; - - if( size.height > 1 && (size.height&1) != 0 && !(flags & CV_DXT_ROWS) ) - size.height = (size.height + 1) & -2; - } - - sizes[INPUT][0] = sizes[OUTPUT][0] = size; - sizes[TEMP][0] = sizes[TEMP][1] = cvSize(0,0); - - if( spectrum_mode ) - { - if( cn == 1 ) - { - types[OUTPUT][0] = depth + 8; - sizes[TEMP][0] = size; - } - sizes[INPUT][0] = sizes[INPUT][1] = size; - types[INPUT][1] = types[INPUT][0]; - } - else if( /*(cn == 2 && (bits&32)) ||*/ (cn == 1 && allow_complex) ) - { - types[TEMP][0] = depth + 8; // CV_??FC2 - sizes[TEMP][0] = size; - size = cvSize(size.width/2+1, size.height); - - if( flags & CV_DXT_INVERSE ) - { - if( cn == 2 ) - { - types[OUTPUT][0] = depth; - sizes[INPUT][0] = size; - } - types[TEMP][1] = types[TEMP][0]; - sizes[TEMP][1] = sizes[TEMP][0]; - } - else - { - if( allow_complex ) - types[OUTPUT][0] = depth + 8; - - if( cn == 2 ) - { - types[INPUT][0] = depth; - types[TEMP][1] = types[TEMP][0]; - sizes[TEMP][1] = size; - } - else - { - types[TEMP][1] = depth; - sizes[TEMP][1] = sizes[TEMP][0]; - } - temp_dst = true; - } - } - - inplace = false; - if( spectrum_mode || - (!temp_dst && types[INPUT][0] == types[OUTPUT][0]) || - (temp_dst && types[INPUT][0] == types[TEMP][1]) ) - inplace = (bits & 64) != 0; - - types[REF_OUTPUT][0] = types[OUTPUT][0]; - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; -} - - -void CxCore_DXTBaseTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* transform_type = cvReadString( find_timing_param( "transform_type" ), "" ); - int depth = CV_MAT_DEPTH(types[INPUT][0]); - int in_type = depth, out_type = depth; - - if( strcmp( transform_type, "Fwd_CToC" ) == 0 || strcmp( transform_type, "Inv_CToC" ) == 0 ) - in_type = out_type = CV_MAKETYPE(depth,2); - - if( strncmp( transform_type, "Fwd", 3 ) == 0 ) - flags = CV_DXT_FORWARD; - else - flags = CV_DXT_INV_SCALE; - - types[INPUT][0] = in_type; - if( spectrum_mode ) - types[INPUT][1] = in_type; - types[OUTPUT][0] = types[REF_OUTPUT][0] = out_type; - sizes[TEMP][0] = cvSize(0,0); - - inplace = false; -} - - -int CxCore_DXTBaseTestImpl::write_default_params( CvFileStorage* fs ) -{ - int code = CvArrTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "transform_type", transform_type_list ); - return code; -} - - -void CxCore_DXTBaseTestImpl::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", cvReadString( find_timing_param("transform_type"), "" ) ); - ptr += strlen(ptr); - params_left--; - CvArrTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_DXTBaseTestImpl::get_success_error_level( int test_case_idx, int i, int j ) -{ - return CvArrTest::get_success_error_level( test_case_idx, i, j ); -} - - -int CxCore_DXTBaseTestImpl::prepare_test_case( int test_case_idx ) -{ - int code = CvArrTest::prepare_test_case( test_case_idx ); - if( code > 0 && ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - int in_type = CV_MAT_TYPE(test_mat[INPUT][0].type); - int out_type = CV_MAT_TYPE(test_mat[OUTPUT][0].type); - - if( CV_MAT_CN(in_type) == 2 && CV_MAT_CN(out_type) == 1 ) - cvTsFixCCS( &test_mat[INPUT][0], test_mat[OUTPUT][0].cols, flags ); - - if( inplace ) - cvTsCopy( &test_mat[INPUT][test_case_idx & (int)spectrum_mode], - temp_dst ? &test_mat[TEMP][1] : - in_type == out_type ? &test_mat[OUTPUT][0] : - &test_mat[TEMP][0] ); - } - - return code; -} - -CxCore_DXTBaseTestImpl dxt_test( "dxt", "" ); - - -class CxCore_DXTBaseTest : public CxCore_DXTBaseTestImpl -{ -public: - CxCore_DXTBaseTest( const char* test_name, const char* test_funcs, - bool _allow_complex=false, bool _allow_odd=false, - bool _spectrum_mode=false ); -}; - -CxCore_DXTBaseTest::CxCore_DXTBaseTest( const char* test_name, const char* test_funcs, - bool _allow_complex, bool _allow_odd, bool _spectrum_mode ) - : CxCore_DXTBaseTestImpl( test_name, test_funcs, _allow_complex, _allow_odd, _spectrum_mode ) -{ - size_list = 0; - depth_list = 0; - default_timing_param_names = dxt_param_names; - transform_type_list = dft_transforms; -} - - -////////////////////// FFT //////////////////////// -class CxCore_DFTTest : public CxCore_DXTBaseTest -{ -public: - CxCore_DFTTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_DFTTest::CxCore_DFTTest() : CxCore_DXTBaseTest( "dxt-dft", "cvDFT", true, true, false ) -{ -} - - -void CxCore_DFTTest::run_func() -{ - CvArr* dst = temp_dst ? test_array[TEMP][1] : test_array[OUTPUT][0]; - CvArr* src = inplace ? dst : test_array[INPUT][0]; - - if(!(flags & CV_DXT_INVERSE)) - cvDFT( src, dst, flags ); - else - { - cv::Mat _src = cv::cvarrToMat(src), _dst = cv::cvarrToMat(dst); - idft(_src, _dst, flags & ~CV_DXT_INVERSE); - } -} - - -void CxCore_DFTTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_OUTPUT][0]; - CvMat* tmp_src = src; - CvMat* tmp_dst = dst; - int src_cn = CV_MAT_CN( src->type ); - int dst_cn = CV_MAT_CN( dst->type ); - - if( src_cn != 2 || dst_cn != 2 ) - { - tmp_src = &test_mat[TEMP][0]; - - if( !(flags & CV_DXT_INVERSE ) ) - { - CvMat* cvdft_dst = &test_mat[TEMP][1]; - cvTsConvertFromCCS( cvdft_dst, cvdft_dst, - &test_mat[OUTPUT][0], flags ); - cvTsZero( tmp_src ); - cvTsInsert( src, tmp_src, 0 ); - } - else - { - cvTsConvertFromCCS( src, src, tmp_src, flags ); - tmp_dst = &test_mat[TEMP][1]; - } - } - - if( src->rows == 1 || (src->cols == 1 && !(flags & CV_DXT_ROWS)) ) - cvTsDFT_1D( tmp_src, tmp_dst, flags ); - else - cvTsDFT_2D( tmp_src, tmp_dst, flags ); - - if( tmp_dst != dst ) - cvTsExtract( tmp_dst, dst, 0 ); -} - - -CxCore_DFTTest dft_test; - - -////////////////////// DCT //////////////////////// -class CxCore_DCTTest : public CxCore_DXTBaseTest -{ -public: - CxCore_DCTTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_DCTTest::CxCore_DCTTest() : CxCore_DXTBaseTest( "dxt-dct", "cvDCT", false, false, false ) -{ - transform_type_list = dct_transforms; -} - - -void CxCore_DCTTest::run_func() -{ - CvArr* dst = test_array[OUTPUT][0]; - CvArr* src = inplace ? dst : test_array[INPUT][0]; - - if(!(flags & CV_DXT_INVERSE)) - cvDCT( src, dst, flags ); - else - { - cv::Mat _src = cv::cvarrToMat(src), _dst = cv::cvarrToMat(dst); - idct(_src, _dst, flags & ~CV_DXT_INVERSE); - } -} - - -void CxCore_DCTTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src = &test_mat[INPUT][0]; - CvMat* dst = &test_mat[REF_OUTPUT][0]; - - if( src->rows == 1 || (src->cols == 1 && !(flags & CV_DXT_ROWS)) ) - cvTsDCT_1D( src, dst, flags ); - else - cvTsDCT_2D( src, dst, flags ); -} - - -CxCore_DCTTest dct_test; - - -////////////////////// MulSpectrums //////////////////////// -class CxCore_MulSpectrumsTest : public CxCore_DXTBaseTest -{ -public: - CxCore_MulSpectrumsTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_MulSpectrumsTest::CxCore_MulSpectrumsTest() : - CxCore_DXTBaseTest( "dxt-mulspectrums", "cvMulSpectrums", true, true, true ) -{ - transform_type_list = mulsp_transforms; -} - - -void CxCore_MulSpectrumsTest::run_func() -{ - CvArr* dst = test_array[TEMP].size() > 0 && test_array[TEMP][0] ? - test_array[TEMP][0] : test_array[OUTPUT][0]; - CvArr *src1 = test_array[INPUT][0], *src2 = test_array[INPUT][1]; - - if( inplace ) - { - if( ts->get_current_test_info()->test_case_idx & 1 ) - src2 = dst; - else - src1 = dst; - } - - cvMulSpectrums( src1, src2, dst, flags ); -} - - -static void cvTsMulComplex( const CvMat* A, const CvMat* B, CvMat* C, int flags ) -{ - int i, j, depth = CV_MAT_DEPTH(A->type), cols = A->cols*2; - - assert( CV_ARE_SIZES_EQ(A,B) && CV_ARE_SIZES_EQ(B,C) && - CV_ARE_TYPES_EQ(A,B) && CV_ARE_TYPES_EQ(B,C) && - CV_MAT_CN(A->type) == 2 && CV_MAT_DEPTH(A->type) >= CV_32F ); - - for( i = 0; i < C->rows; i++ ) - { - if( depth == CV_32F ) - { - const float* a = (float*)(A->data.ptr + A->step*i); - const float* b = (float*)(B->data.ptr + B->step*i); - float* c = (float*)(C->data.ptr + C->step*i); - - if( !(flags & CV_DXT_MUL_CONJ) ) - for( j = 0; j < cols; j += 2 ) - { - double re = (double)a[j]*b[j] - (double)a[j+1]*b[j+1]; - double im = (double)a[j+1]*b[j] + (double)a[j]*b[j+1]; - - c[j] = (float)re; - c[j+1] = (float)im; - } - else - for( j = 0; j < cols; j += 2 ) - { - double re = (double)a[j]*b[j] + (double)a[j+1]*b[j+1]; - double im = (double)a[j+1]*b[j] - (double)a[j]*b[j+1]; - - c[j] = (float)re; - c[j+1] = (float)im; - } - } - else - { - const double* a = (double*)(A->data.ptr + A->step*i); - const double* b = (double*)(B->data.ptr + B->step*i); - double* c = (double*)(C->data.ptr + C->step*i); - - if( !(flags & CV_DXT_MUL_CONJ) ) - for( j = 0; j < cols; j += 2 ) - { - double re = a[j]*b[j] - a[j+1]*b[j+1]; - double im = a[j+1]*b[j] + a[j]*b[j+1]; - - c[j] = re; - c[j+1] = im; - } - else - for( j = 0; j < cols; j += 2 ) - { - double re = a[j]*b[j] + a[j+1]*b[j+1]; - double im = a[j+1]*b[j] - a[j]*b[j+1]; - - c[j] = re; - c[j+1] = im; - } - } - } -} - - -void CxCore_MulSpectrumsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* src1 = &test_mat[INPUT][0]; - CvMat* src2 = &test_mat[INPUT][1]; - CvMat* dst = &test_mat[OUTPUT][0]; - CvMat* dst0 = &test_mat[REF_OUTPUT][0]; - CvMat* temp = test_array[TEMP].size() > 0 && test_array[TEMP][0] ? &test_mat[TEMP][0] : 0; - int cn = CV_MAT_CN(src1->type); - - if( cn == 1 ) - { - cvTsConvertFromCCS( src1, src1, dst, flags ); - cvTsConvertFromCCS( src2, src2, dst0, flags ); - src1 = dst; - src2 = dst0; - } - - cvTsMulComplex( src1, src2, dst0, flags ); - if( cn == 1 ) - { - assert( temp != 0 ); - cvTsConvertFromCCS( temp, temp, dst, flags ); - } -} - - -CxCore_MulSpectrumsTest mulspectrums_test; - - -/* End of file. */ diff --git a/tests/cxcore/src/aio.cpp b/tests/cxcore/src/aio.cpp deleted file mode 100644 index 810a440..0000000 --- a/tests/cxcore/src/aio.cpp +++ /dev/null @@ -1,432 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" -#include - -using namespace cv; - -class CV_IOTest : public CvTest -{ -public: - CV_IOTest(); -protected: - void run(int); -}; - - -CV_IOTest::CV_IOTest(): -CvTest( "io", "cvOpenFileStorage, cvReleaseFileStorage, cvRead*, cvWrite*, cvStartWriteStruct, cvEndWriteStruct" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -static SparseMat cvTsGetRandomSparseMat(int dims, const int* sz, int type, - int nzcount, double a, double b, CvRNG* 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] = cvTsRandInt(rng) % sz[j]; - double val = cvTsRandReal(rng)*(b - a) + a; - uchar* ptr = m.ptr(idx, true, 0); - if( type == CV_8U ) - *(uchar*)ptr = saturate_cast(val); - else if( type == CV_8S ) - *(schar*)ptr = saturate_cast(val); - else if( type == CV_16U ) - *(ushort*)ptr = saturate_cast(val); - else if( type == CV_16S ) - *(short*)ptr = saturate_cast(val); - else if( type == CV_32S ) - *(int*)ptr = saturate_cast(val); - else if( type == CV_32F ) - *(float*)ptr = saturate_cast(val); - else - *(double*)ptr = saturate_cast(val); - } - - return m; -} - -static bool cvTsCheckSparse(const CvSparseMat* m1, const CvSparseMat* m2, double eps) -{ - CvSparseMatIterator it1; - CvSparseNode* node1; - int depth = CV_MAT_DEPTH(m1->type); - - 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; - - 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; - } - - return true; -} - -void CV_IOTest::run( int ) -{ - double ranges[][2] = {{0, 256}, {-128, 128}, {0, 65536}, {-32768, 32768}, - {-1000000, 1000000}, {-10, 10}, {-10, 10}}; - CvRNG* rng = ts->get_rng(); - RNG rng0; - test_case_count = 2; - int progress = 0; - MemStorage storage(cvCreateMemStorage(0)); - - for( int idx = 0; idx < test_case_count; idx++ ) - { - ts->update_context( this, idx, false ); - progress = update_progress( progress, idx, test_case_count, 0 ); - - cvClearMemStorage(storage); - - char buf[L_tmpnam+16]; - char* filename = tmpnam(buf); - strcat(filename, idx % 2 ? ".yml" : ".xml"); - if(filename[0] == '\\') - filename++; - - FileStorage fs(filename, FileStorage::WRITE); - - int test_int = (int)cvTsRandInt(rng); - double test_real = (cvTsRandInt(rng)%2?1:-1)*exp(cvTsRandReal(rng)*18-9); - string test_string = "vw wv23424rt\"&<>&'@#$@$%$%&%IJUKYILFD@#$@%$&*&() "; - - int depth = cvTsRandInt(rng) % (CV_64F+1); - int cn = cvTsRandInt(rng) % 4 + 1; - Mat test_mat(cvTsRandInt(rng)%30+1, cvTsRandInt(rng)%30+1, CV_MAKETYPE(depth, cn)); - - 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); - } - - CvSeq* seq = cvCreateSeq(test_mat.type(), (int)sizeof(CvSeq), - (int)test_mat.elemSize(), storage); - cvSeqPushMulti(seq, test_mat.data, test_mat.cols*test_mat.rows); - - 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); - } - - depth = cvTsRandInt(rng) % (CV_64F+1); - cn = cvTsRandInt(rng) % 4 + 1; - int sz[] = {cvTsRandInt(rng)%10+1, cvTsRandInt(rng)%10+1, cvTsRandInt(rng)%10+1}; - MatND test_mat_nd(3, sz, CV_MAKETYPE(depth, cn)); - - 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); - } - - int ssz[] = {cvTsRandInt(rng)%10+1, cvTsRandInt(rng)%10+1, - cvTsRandInt(rng)%10+1,cvTsRandInt(rng)%10+1}; - SparseMat test_sparse_mat = cvTsGetRandomSparseMat(4, ssz, cvTsRandInt(rng)%(CV_64F+1), - cvTsRandInt(rng) % 10000, 0, 100, rng); - - 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; - - 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" << "[:"; - - const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1}; - fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0]))); - - fs << "]" << "}"; - cvWriteComment(*fs, "test comment", 0); - - fs.writeObj("test_seq", seq); - fs.writeObj("test_graph",graph); - CvGraph* graph2 = (CvGraph*)cvClone(graph); - - fs.release(); - - if(!fs.open(filename, FileStorage::READ)) - { - ts->printf( CvTS::LOG, "filename %s can not be read\n", filename ); - ts->set_failed_test_info( CvTS::FAIL_MISSING_TEST_DATA ); - return; - } - - int real_int = (int)fs["test_int"]; - double real_real = (double)fs["test_real"]; - string real_string = (string)fs["test_string"]; - - if( real_int != test_int || - fabs(real_real - test_real) > DBL_EPSILON*(fabs(test_real)+1) || - real_string != test_string ) - { - ts->printf( CvTS::LOG, "the read scalars are not correct\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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); - CvPoint pt = {0,0}; - - if( !m || !CV_IS_MAT(m) || m->rows != test_mat.rows || m->cols != test_mat.cols || - cvTsCmpEps( &stub1, &_test_stub1, &max_diff, 0, &pt, true) < 0 ) - { - ts->printf( CvTS::LOG, "the read matrix is not correct: (%.20g vs %.20g) at (%d,%d)\n", - cvGetReal2D(&stub1, pt.y, pt.x), cvGetReal2D(&_test_stub1, pt.y, pt.x), - pt.y, pt.x ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - if( m && CV_IS_MAT(m)) - cvReleaseMat(&m); - - CvMatND* m_nd = (CvMatND*)fs["test_mat_nd"].readObj(); - CvMatND _test_mat_nd = test_mat_nd; - - if( !m_nd || !CV_IS_MATND(m_nd) ) - { - ts->printf( CvTS::LOG, "the read nd-matrix is not correct\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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); - - if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) || - !CV_ARE_SIZES_EQ(&stub, &_test_stub) || - //cvNorm(&stub, &_test_stub, CV_L2) != 0 ) - cvTsCmpEps( &stub1, &_test_stub1, &max_diff, 0, &pt, true) < 0 ) - { - ts->printf( CvTS::LOG, "readObj method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n", - cvGetReal2D(&stub1, pt.y, pt.x), cvGetReal2D(&_test_stub1, pt.y, pt.x), - pt.y, pt.x ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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); - - if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) || - !CV_ARE_SIZES_EQ(&stub, &_test_stub) || - //cvNorm(&stub, &_test_stub, CV_L2) != 0 ) - cvTsCmpEps( &stub1, &_test_stub1, &max_diff, 0, &pt, true) < 0 ) - { - ts->printf( CvTS::LOG, "C++ method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n", - cvGetReal2D(&stub1, pt.y, pt.x), cvGetReal2D(&_test_stub1, pt.y, pt.x), - pt.y, pt.x ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - cvRelease((void**)&m_nd); - - Ptr m_s = (CvSparseMat*)fs["test_sparse_mat"].readObj(); - Ptr _test_sparse_ = (CvSparseMat*)test_sparse_mat; - Ptr _test_sparse = (CvSparseMat*)cvClone(_test_sparse_); - SparseMat m_s2; - fs["test_sparse_mat"] >> m_s2; - Ptr _m_s2 = (CvSparseMat*)m_s2; - - if( !m_s || !CV_IS_SPARSE_MAT(m_s) || - !cvTsCheckSparse(m_s, _test_sparse,0) || - !cvTsCheckSparse(_m_s2, _test_sparse,0)) - { - ts->printf( CvTS::LOG, "the read sparse matrix is not correct\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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 || - (string)tl[4] != "2-502 2-029 3egegeg" || - 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( CvTS::LOG, "the test list is incorrect\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - FileNode tm = fs["test_map"]; - FileNode tm_lbp = tm["lbp"]; - - int real_x = (int)tm["x"]; - int real_y = (int)tm["y"]; - int real_width = (int)tm["width"]; - int real_height = (int)tm["height"]; - - - 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 ); - - 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( CvTS::LOG, "the test map is incorrect\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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( CvTS::LOG, "the cloned or read graph have wrong number of vertices or edges\n" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - 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( CvTS::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( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - } - - fs.release(); - remove(filename); - } -} - -CV_IOTest opencv_io_test; diff --git a/tests/cxcore/src/amath.cpp b/tests/cxcore/src/amath.cpp deleted file mode 100644 index 67b66b8..0000000 --- a/tests/cxcore/src/amath.cpp +++ /dev/null @@ -1,3352 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -////////////////////////////////////////////////////////////////////////////////////////// -/////////////////// tests for matrix operations and math functions /////////////////////// -////////////////////////////////////////////////////////////////////////////////////////// - -#include "cxcoretest.h" -#include -#include - -/// !!! NOTE !!! These tests happily avoid overflow cases & out-of-range arguments -/// so that output arrays contain neigher Inf's nor Nan's. -/// Handling such cases would require special modification of check function -/// (validate_test_results) => TBD. -/// Also, need some logarithmic-scale generation of input data. Right now it is done (in some tests) -/// by generating min/max boundaries for random data in logarimithic scale, but -/// within the same test case all the input array elements are of the same order. - -static const CvSize math_sizes[] = {{10,1}, {100,1}, {10000,1}, {-1,-1}}; -static const int math_depths[] = { CV_32F, CV_64F, -1 }; -static const char* math_param_names[] = { "size", "depth", 0 }; - -static const CvSize matrix_sizes[] = {{3,3}, {4,4}, {10,10}, {30,30}, {100,100}, {500,500}, {-1,-1}}; - -class CxCore_MathTestImpl : public CvArrTest -{ -public: - CxCore_MathTestImpl( const char* test_name, const char* test_funcs ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int /*test_case_idx*/, int i, int j ); - bool test_nd; -}; - - -CxCore_MathTestImpl::CxCore_MathTestImpl( const char* test_name, const char* test_funcs ) - : CvArrTest( test_name, test_funcs, "" ) -{ - optional_mask = false; - - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - - default_timing_param_names = math_param_names; - - size_list = math_sizes; - whole_size_list = 0; - depth_list = math_depths; - cn_list = 0; - test_nd = false; -} - - -double CxCore_MathTestImpl::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - return CV_MAT_DEPTH(test_mat[i][j].type) == CV_32F ? FLT_EPSILON*128 : DBL_EPSILON*1024; -} - - -void CxCore_MathTestImpl::get_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng)%2 + CV_32F; - int cn = cvTsRandInt(rng) % 4 + 1, type = CV_MAKETYPE(depth, cn); - int i, j; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - for( j = 0; j < count; j++ ) - types[i][j] = type; - } - test_nd = cvTsRandInt(rng)%3 == 0; -} - -CxCore_MathTestImpl math_test( "math", "" ); - - -class CxCore_MathTest : public CxCore_MathTestImpl -{ -public: - CxCore_MathTest( const char* test_name, const char* test_funcs ); -}; - - -CxCore_MathTest::CxCore_MathTest( const char* test_name, const char* test_funcs ) - : CxCore_MathTestImpl( test_name, test_funcs ) -{ - size_list = 0; - depth_list = 0; -} - - -////////// exp ///////////// -class CxCore_ExpTest : public CxCore_MathTest -{ -public: - CxCore_ExpTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - double get_success_error_level( int /*test_case_idx*/, int i, int j ); - int prepare_test_case( int test_case ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int out_type; -}; - - -CxCore_ExpTest::CxCore_ExpTest() - : CxCore_MathTest( "math-exp", "cvExp" ) -{ - out_type = 0; -} - - -double CxCore_ExpTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int in_depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - int out_depth = CV_MAT_DEPTH(test_mat[OUTPUT][0].type); - int min_depth = MIN(in_depth, out_depth); - return min_depth == CV_32F ? 1e-5 : 1e-8; -} - - -void CxCore_ExpTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CxCore_MathTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - out_type = types[OUTPUT][0]; - /*if( CV_MAT_DEPTH(types[INPUT][0]) == CV_32F && (cvRandInt(ts->get_rng()) & 3) == 0 ) - types[OUTPUT][0] = types[REF_OUTPUT][0] = - out_type = (types[INPUT][0] & ~CV_MAT_DEPTH_MASK)|CV_64F;*/ -} - -void CxCore_ExpTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - double l = cvTsRandReal(ts->get_rng())*10+1; - double u = cvTsRandReal(ts->get_rng())*10+1; - l *= -l; - u *= u; - *low = cvScalarAll(l); - *high = cvScalarAll(CV_MAT_DEPTH(out_type)==CV_64F? u : u*0.5); -} - -int CxCore_ExpTest::prepare_test_case( int test_case ) -{ - int code = CxCore_MathTest::prepare_test_case(test_case); - if( code < 0 ) - return code; - - CvRNG* rng = ts->get_rng(); - - int i, j, k, count = cvTsRandInt(rng) % 10; - CvMat* src = &test_mat[INPUT][0]; - int depth = CV_MAT_DEPTH(src->type); - - // add some extremal values - for( k = 0; k < count; k++ ) - { - i = cvTsRandInt(rng) % src->rows; - j = cvTsRandInt(rng) % (src->cols*CV_MAT_CN(src->type)); - int sign = cvTsRandInt(rng) % 2 ? 1 : -1; - if( depth == CV_32F ) - ((float*)(src->data.ptr + src->step*i))[j] = FLT_MAX*sign; - else - ((double*)(src->data.ptr + src->step*i))[j] = DBL_MAX*sign; - } - - return code; -} - - -void CxCore_ExpTest::run_func() -{ - if(!test_nd) - cvExp( test_array[INPUT][0], test_array[OUTPUT][0] ); - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::exp(a, b); - } -} - - -void CxCore_ExpTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* a = &test_mat[INPUT][0]; - CvMat* b = &test_mat[REF_OUTPUT][0]; - - int a_depth = CV_MAT_DEPTH(a->type); - int b_depth = CV_MAT_DEPTH(b->type); - int ncols = test_mat[INPUT][0].cols*CV_MAT_CN(a->type); - int i, j; - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - if( a_depth == CV_32F && b_depth == CV_32F ) - { - for( j = 0; j < ncols; j++ ) - ((float*)b_data)[j] = (float)exp((double)((float*)a_data)[j]); - } - else if( a_depth == CV_32F && b_depth == CV_64F ) - { - for( j = 0; j < ncols; j++ ) - ((double*)b_data)[j] = exp((double)((float*)a_data)[j]); - } - else - { - assert( a_depth == CV_64F && b_depth == CV_64F ); - for( j = 0; j < ncols; j++ ) - ((double*)b_data)[j] = exp(((double*)a_data)[j]); - } - } -} - -CxCore_ExpTest exp_test; - - -////////// log ///////////// -class CxCore_LogTest : public CxCore_MathTest -{ -public: - CxCore_LogTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_LogTest::CxCore_LogTest() - : CxCore_MathTest( "math-log", "cvLog" ) -{ -} - - -void CxCore_LogTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CxCore_MathTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - /*if( CV_MAT_DEPTH(types[INPUT][0]) == CV_32F && (cvRandInt(ts->get_rng()) & 3) == 0 ) - types[INPUT][0] = (types[INPUT][0] & ~CV_MAT_DEPTH_MASK)|CV_64F;*/ -} - - -void CxCore_LogTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - double l = cvTsRandReal(ts->get_rng())*15-5; - double u = cvTsRandReal(ts->get_rng())*15-5; - double t; - l = exp(l); - u = exp(u); - if( l > u ) - CV_SWAP( l, u, t ); - *low = cvScalarAll(l); - *high = cvScalarAll(u); -} - - -void CxCore_LogTest::run_func() -{ - if(!test_nd) - cvLog( test_array[INPUT][0], test_array[OUTPUT][0] ); - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::log(a, b); - } -} - - -void CxCore_LogTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* a = &test_mat[INPUT][0]; - CvMat* b = &test_mat[REF_OUTPUT][0]; - - int a_depth = CV_MAT_DEPTH(a->type); - int b_depth = CV_MAT_DEPTH(b->type); - int ncols = test_mat[INPUT][0].cols*CV_MAT_CN(a->type); - int i, j; - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - if( a_depth == CV_32F && b_depth == CV_32F ) - { - for( j = 0; j < ncols; j++ ) - ((float*)b_data)[j] = (float)log((double)((float*)a_data)[j]); - } - else if( a_depth == CV_64F && b_depth == CV_32F ) - { - for( j = 0; j < ncols; j++ ) - ((float*)b_data)[j] = (float)log(((double*)a_data)[j]); - } - else - { - assert( a_depth == CV_64F && b_depth == CV_64F ); - for( j = 0; j < ncols; j++ ) - ((double*)b_data)[j] = log(((double*)a_data)[j]); - } - } -} - -CxCore_LogTest log_test; - - -////////// pow ///////////// - -static const double math_pow_values[] = { 2., 5., 0.5, -0.5, 1./3, -1./3, CV_PI }; -static const char* math_pow_param_names[] = { "size", "power", "depth", 0 }; -static const int math_pow_depths[] = { CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F, -1 }; - -class CxCore_PowTest : public CxCore_MathTest -{ -public: - CxCore_PowTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); - double power; -}; - - -CxCore_PowTest::CxCore_PowTest() - : CxCore_MathTest( "math-pow", "cvPow" ) -{ - power = 0; - default_timing_param_names = math_pow_param_names; - depth_list = math_pow_depths; -} - - -void CxCore_PowTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % (CV_64F+1); - int cn = cvTsRandInt(rng) % 4 + 1; - int i, j; - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth += depth == CV_8S; - - if( depth < CV_32F || cvTsRandInt(rng)%8 == 0 ) - // integer power - power = (int)(cvTsRandInt(rng)%21 - 10); - else - { - i = cvTsRandInt(rng)%17; - power = i == 16 ? 1./3 : i == 15 ? 0.5 : i == 14 ? -0.5 : cvTsRandReal(rng)*10 - 5; - } - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - int type = CV_MAKETYPE(depth, cn); - for( j = 0; j < count; j++ ) - types[i][j] = type; - } - test_nd = cvTsRandInt(rng)%3 == 0; -} - - -void CxCore_PowTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MathTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - power = cvReadReal( find_timing_param( "power" ), 0.2 ); -} - - -int CxCore_PowTest::write_default_params( CvFileStorage* fs ) -{ - int i, code = CxCore_MathTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - start_write_param( fs ); - cvStartWriteStruct( fs, "power", CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; i < CV_DIM(math_pow_values); i++ ) - cvWriteReal( fs, 0, math_pow_values[i] ); - cvEndWriteStruct(fs); - return code; -} - - -int CxCore_PowTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MathTest::prepare_test_case( test_case_idx ); - if( code > 0 && ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - if( cvRound(power) != power && CV_MAT_DEPTH(test_mat[INPUT][0].type) < CV_32F ) - return 0; - } - return code; -} - - -void CxCore_PowTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%g,", power ); - ptr += strlen(ptr); - params_left--; - CxCore_MathTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_PowTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int type = cvGetElemType( test_array[i][j] ); - if( CV_MAT_DEPTH(type) < CV_32F ) - return power == cvRound(power) && power >= 0 ? 0 : 1; - else - return CxCore_MathTest::get_success_error_level( test_case_idx, i, j ); -} - - -void CxCore_PowTest::get_minmax_bounds( int /*i*/, int /*j*/, int type, CvScalar* low, CvScalar* high ) -{ - double l, u = cvTsRandInt(ts->get_rng())%1000 + 1; - if( power > 0 ) - { - double mval = cvTsMaxVal(type); - double u1 = pow(mval,1./power)*2; - u = MIN(u,u1); - } - - l = power == cvRound(power) ? -u : FLT_EPSILON; - *low = cvScalarAll(l); - *high = cvScalarAll(u); -} - - -void CxCore_PowTest::run_func() -{ - if(!test_nd) - { - if( fabs(power-1./3) <= DBL_EPSILON && CV_MAT_DEPTH(test_mat[INPUT][0].type) == CV_32F ) - { - cv::Mat a(&test_mat[INPUT][0]), b(&test_mat[OUTPUT][0]); - - a = a.reshape(1); - b = b.reshape(1); - for( int i = 0; i < a.rows; i++ ) - { - b.at(i,0) = (float)fabs(cvCbrt(a.at(i,0))); - for( int j = 1; j < a.cols; j++ ) - b.at(i,j) = (float)fabs(cv::cubeRoot(a.at(i,j))); - } - } - else - cvPow( test_array[INPUT][0], test_array[OUTPUT][0], power ); - } - else - { - cv::MatND a = cv::cvarrToMatND(test_array[INPUT][0]); - cv::MatND b = cv::cvarrToMatND(test_array[OUTPUT][0]); - if(power == 0.5) - cv::sqrt(a, b); - else - cv::pow(a, power, b); - } -} - - -inline static int ipow( int a, int power ) -{ - int b = 1; - while( power > 0 ) - { - if( power&1 ) - b *= a, power--; - else - a *= a, power >>= 1; - } - return b; -} - - -inline static double ipow( double a, int power ) -{ - double b = 1.; - while( power > 0 ) - { - if( power&1 ) - b *= a, power--; - else - a *= a, power >>= 1; - } - return b; -} - - -void CxCore_PowTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* a = &test_mat[INPUT][0]; - CvMat* b = &test_mat[REF_OUTPUT][0]; - - int depth = CV_MAT_DEPTH(a->type); - int ncols = test_mat[INPUT][0].cols*CV_MAT_CN(a->type); - int ipower = cvRound(power), apower = abs(ipower); - int i, j; - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - switch( depth ) - { - case CV_8U: - if( ipower < 0 ) - for( j = 0; j < ncols; j++ ) - { - int val = ((uchar*)a_data)[j]; - ((uchar*)b_data)[j] = (uchar)(val <= 1 ? val : - val == 2 && ipower == -1 ? 1 : 0); - } - else - for( j = 0; j < ncols; j++ ) - { - int val = ((uchar*)a_data)[j]; - val = ipow( val, ipower ); - ((uchar*)b_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - if( ipower < 0 ) - for( j = 0; j < ncols; j++ ) - { - int val = ((char*)a_data)[j]; - ((char*)b_data)[j] = (char)((val&~1)==0 ? val : - val ==-1 ? 1-2*(ipower&1) : - val == 2 && ipower == -1 ? 1 : 0); - } - else - for( j = 0; j < ncols; j++ ) - { - int val = ((char*)a_data)[j]; - val = ipow( val, ipower ); - ((char*)b_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - if( ipower < 0 ) - for( j = 0; j < ncols; j++ ) - { - int val = ((ushort*)a_data)[j]; - ((ushort*)b_data)[j] = (ushort)((val&~1)==0 ? val : - val ==-1 ? 1-2*(ipower&1) : - val == 2 && ipower == -1 ? 1 : 0); - } - else - for( j = 0; j < ncols; j++ ) - { - int val = ((ushort*)a_data)[j]; - val = ipow( val, ipower ); - ((ushort*)b_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - if( ipower < 0 ) - for( j = 0; j < ncols; j++ ) - { - int val = ((short*)a_data)[j]; - ((short*)b_data)[j] = (short)((val&~1)==0 ? val : - val ==-1 ? 1-2*(ipower&1) : - val == 2 && ipower == -1 ? 1 : 0); - } - else - for( j = 0; j < ncols; j++ ) - { - int val = ((short*)a_data)[j]; - val = ipow( val, ipower ); - ((short*)b_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - if( ipower < 0 ) - for( j = 0; j < ncols; j++ ) - { - int val = ((int*)a_data)[j]; - ((int*)b_data)[j] = (val&~1)==0 ? val : - val ==-1 ? 1-2*(ipower&1) : - val == 2 && ipower == -1 ? 1 : 0; - } - else - for( j = 0; j < ncols; j++ ) - { - int val = ((int*)a_data)[j]; - val = ipow( val, ipower ); - ((int*)b_data)[j] = val; - } - break; - case CV_32F: - if( power != ipower ) - for( j = 0; j < ncols; j++ ) - { - double val = ((float*)a_data)[j]; - val = pow( fabs(val), power ); - ((float*)b_data)[j] = CV_CAST_32F(val); - } - else - for( j = 0; j < ncols; j++ ) - { - double val = ((float*)a_data)[j]; - if( ipower < 0 ) - val = 1./val; - val = ipow( val, apower ); - ((float*)b_data)[j] = (float)val; - } - break; - case CV_64F: - if( power != ipower ) - for( j = 0; j < ncols; j++ ) - { - double val = ((double*)a_data)[j]; - val = pow( fabs(val), power ); - ((double*)b_data)[j] = CV_CAST_64F(val); - } - else - for( j = 0; j < ncols; j++ ) - { - double val = ((double*)a_data)[j]; - if( ipower < 0 ) - val = 1./val; - val = ipow( val, apower ); - ((double*)b_data)[j] = (double)val; - } - break; - } - } -} - -CxCore_PowTest pow_test; - - - -////////// cart2polar ///////////// -class CxCore_CartToPolarTest : public CxCore_MathTest -{ -public: - CxCore_CartToPolarTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int use_degrees; -}; - - -CxCore_CartToPolarTest::CxCore_CartToPolarTest() - : CxCore_MathTest( "math-cart2polar", "cvCartToPolar" ) -{ - use_degrees = 0; - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); -} - - -void CxCore_CartToPolarTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CxCore_MathTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - use_degrees = cvTsRandInt(rng) & 1; - if( cvTsRandInt(rng) % 4 == 0 ) // check missing magnitude/angle cases - { - int idx = cvTsRandInt(rng) & 1; - sizes[OUTPUT][idx] = sizes[REF_OUTPUT][idx] = cvSize(0,0); - } -} - - -void CxCore_CartToPolarTest::run_func() -{ - if(!test_nd) - { - cvCartToPolar( test_array[INPUT][0], test_array[INPUT][1], - test_array[OUTPUT][0], test_array[OUTPUT][1], use_degrees ); - } - else - { - cv::Mat X = cv::cvarrToMat(test_array[INPUT][0]); - cv::Mat Y = cv::cvarrToMat(test_array[INPUT][1]); - cv::Mat mag = test_array[OUTPUT][0] ? cv::cvarrToMat(test_array[OUTPUT][0]) : cv::Mat(); - cv::Mat ph = test_array[OUTPUT][1] ? cv::cvarrToMat(test_array[OUTPUT][1]) : cv::Mat(); - if(!mag.data) - cv::phase(X, Y, ph, use_degrees != 0); - else if(!ph.data) - cv::magnitude(X, Y, mag); - else - cv::cartToPolar(X, Y, mag, ph, use_degrees != 0); - } -} - - -double CxCore_CartToPolarTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - return j == 1 ? 0.5*(use_degrees ? 1 : CV_PI/180.) : - CxCore_MathTest::get_success_error_level( test_case_idx, i, j ); -} - - -void CxCore_CartToPolarTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* x = &test_mat[INPUT][0]; - CvMat* y = &test_mat[INPUT][1]; - CvMat* mag = test_array[REF_OUTPUT][0] ? &test_mat[REF_OUTPUT][0] : 0; - CvMat* angle = test_array[REF_OUTPUT][1] ? &test_mat[REF_OUTPUT][1] : 0; - double C = use_degrees ? 180./CV_PI : 1.; - - int depth = CV_MAT_DEPTH(x->type); - int ncols = x->cols*CV_MAT_CN(x->type); - int i, j; - - for( i = 0; i < x->rows; i++ ) - { - uchar* x_data = x->data.ptr + i*x->step; - uchar* y_data = y->data.ptr + i*y->step; - uchar* mag_data = mag ? mag->data.ptr + i*mag->step : 0; - uchar* angle_data = angle ? angle->data.ptr + i*angle->step : 0; - - if( depth == CV_32F ) - { - for( j = 0; j < ncols; j++ ) - { - double xval = ((float*)x_data)[j]; - double yval = ((float*)y_data)[j]; - - if( mag_data ) - ((float*)mag_data)[j] = (float)sqrt(xval*xval + yval*yval); - if( angle_data ) - { - double a = atan2( yval, xval ); - if( a < 0 ) - a += CV_PI*2; - a *= C; - ((float*)angle_data)[j] = (float)a; - } - } - } - else - { - assert( depth == CV_64F ); - for( j = 0; j < ncols; j++ ) - { - double xval = ((double*)x_data)[j]; - double yval = ((double*)y_data)[j]; - - if( mag_data ) - ((double*)mag_data)[j] = sqrt(xval*xval + yval*yval); - if( angle_data ) - { - double a = atan2( yval, xval ); - if( a < 0 ) - a += CV_PI*2; - a *= C; - ((double*)angle_data)[j] = a; - } - } - } - } - - if( angle ) - { - // hack: increase angle value by 1 (so that alpha becomes 1+alpha) - // to hide large relative errors in case of very small angles - cvTsAdd( &test_mat[OUTPUT][1], cvScalarAll(1.), 0, cvScalarAll(0.), - cvScalarAll(1.), &test_mat[OUTPUT][1], 0 ); - cvTsAdd( &test_mat[REF_OUTPUT][1], cvScalarAll(1.), 0, cvScalarAll(0.), - cvScalarAll(1.), &test_mat[REF_OUTPUT][1], 0 ); - } -} - -CxCore_CartToPolarTest cart2polar_test; - - - -////////// polar2cart ///////////// -class CxCore_PolarToCartTest : public CxCore_MathTest -{ -public: - CxCore_PolarToCartTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int use_degrees; -}; - - -CxCore_PolarToCartTest::CxCore_PolarToCartTest() - : CxCore_MathTest( "math-polar2cart", "cvPolarToCart" ) -{ - use_degrees = 0; - test_array[INPUT].push(NULL); - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); -} - - -void CxCore_PolarToCartTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CxCore_MathTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - use_degrees = cvTsRandInt(rng) & 1; - if( cvTsRandInt(rng) % 4 == 0 ) // check missing magnitude case - sizes[INPUT][1] = cvSize(0,0); - - if( cvTsRandInt(rng) % 4 == 0 ) // check missing x/y cases - { - int idx = cvTsRandInt(rng) & 1; - sizes[OUTPUT][idx] = sizes[REF_OUTPUT][idx] = cvSize(0,0); - } -} - - -void CxCore_PolarToCartTest::run_func() -{ - if(!test_nd) - { - cvPolarToCart( test_array[INPUT][1], test_array[INPUT][0], - test_array[OUTPUT][0], test_array[OUTPUT][1], use_degrees ); - } - else - { - cv::Mat X = test_array[OUTPUT][0] ? cv::cvarrToMat(test_array[OUTPUT][0]) : cv::Mat(); - cv::Mat Y = test_array[OUTPUT][1] ? cv::cvarrToMat(test_array[OUTPUT][1]) : cv::Mat(); - cv::Mat mag = test_array[INPUT][1] ? cv::cvarrToMat(test_array[INPUT][1]) : cv::Mat(); - cv::Mat ph = test_array[INPUT][0] ? cv::cvarrToMat(test_array[INPUT][0]) : cv::Mat(); - cv::polarToCart(mag, ph, X, Y, use_degrees != 0); - } -} - - -double CxCore_PolarToCartTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return FLT_EPSILON*100; -} - - -void CxCore_PolarToCartTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat* x = test_array[REF_OUTPUT][0] ? &test_mat[REF_OUTPUT][0] : 0; - CvMat* y = test_array[REF_OUTPUT][1] ? &test_mat[REF_OUTPUT][1] : 0; - CvMat* angle = &test_mat[INPUT][0]; - CvMat* mag = test_array[INPUT][1] ? &test_mat[INPUT][1] : 0; - double C = use_degrees ? CV_PI/180. : 1.; - - int depth = CV_MAT_DEPTH(angle->type); - int ncols = angle->cols*CV_MAT_CN(angle->type); - int i, j; - - for( i = 0; i < angle->rows; i++ ) - { - uchar* x_data = x ? x->data.ptr + i*x->step : 0; - uchar* y_data = y ? y->data.ptr + i*y->step : 0; - uchar* mag_data = mag ? mag->data.ptr + i*mag->step : 0; - uchar* angle_data = angle->data.ptr + i*angle->step; - - if( depth == CV_32F ) - { - for( j = 0; j < ncols; j++ ) - { - double a = ((float*)angle_data)[j]*C; - double m = mag_data ? ((float*)mag_data)[j] : 1.; - - if( x_data ) - ((float*)x_data)[j] = (float)(m*cos(a)); - if( y_data ) - ((float*)y_data)[j] = (float)(m*sin(a)); - } - } - else - { - assert( depth == CV_64F ); - for( j = 0; j < ncols; j++ ) - { - double a = ((double*)angle_data)[j]*C; - double m = mag_data ? ((double*)mag_data)[j] : 1.; - - if( x_data ) - ((double*)x_data)[j] = m*cos(a); - if( y_data ) - ((double*)y_data)[j] = m*sin(a); - } - } - } -} - -CxCore_PolarToCartTest polar2cart_test; - -///////////////////////////////////////// matrix tests //////////////////////////////////////////// - -static const int matrix_all_depths[] = { CV_8U, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F, -1 }; - -class CxCore_MatrixTestImpl : public CvArrTest -{ -public: - CxCore_MatrixTestImpl( const char* test_name, const char* test_funcs, int in_count, int out_count, - bool allow_int, bool scalar_output, int max_cn ); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - bool allow_int; - bool scalar_output; - int max_cn; -}; - - -CxCore_MatrixTestImpl::CxCore_MatrixTestImpl( const char* test_name, const char* test_funcs, - int in_count, int out_count, - bool _allow_int, bool _scalar_output, int _max_cn ) - : CvArrTest( test_name, test_funcs, "" ), - allow_int(_allow_int), scalar_output(_scalar_output), max_cn(_max_cn) -{ - int i; - for( i = 0; i < in_count; i++ ) - test_array[INPUT].push(NULL); - - for( i = 0; i < out_count; i++ ) - { - test_array[OUTPUT].push(NULL); - test_array[REF_OUTPUT].push(NULL); - } - - element_wise_relative_error = false; - - default_timing_param_names = math_param_names; - - size_list = (CvSize*)matrix_sizes; - whole_size_list = 0; - depth_list = (int*)math_depths; - cn_list = 0; -} - - -void CxCore_MatrixTestImpl::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % (allow_int ? CV_64F+1 : 2); - int cn = cvTsRandInt(rng) % max_cn + 1; - int i, j; - - if( allow_int ) - depth += depth == CV_8S; - else - depth += CV_32F; - - CvArrTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - int flag = (i == OUTPUT || i == REF_OUTPUT) && scalar_output; - int type = !flag ? CV_MAKETYPE(depth, cn) : CV_64FC1; - - for( j = 0; j < count; j++ ) - { - types[i][j] = type; - if( flag ) - sizes[i][j] = cvSize( 4, 1 ); - } - } -} - - -void CxCore_MatrixTestImpl::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CvArrTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - if( scalar_output ) - { - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize( 4, 1 ); - whole_sizes[OUTPUT][0] = whole_sizes[REF_OUTPUT][0] = cvSize( 4, 1 ); - } -} - - -double CxCore_MatrixTestImpl::get_success_error_level( int test_case_idx, int i, int j ) -{ - int input_depth = CV_MAT_DEPTH(cvGetElemType( test_array[INPUT][0] )); - double input_precision = input_depth < CV_32F ? 0 : input_depth == CV_32F ? - 5e-5 : 5e-10; - double output_precision = CvArrTest::get_success_error_level( test_case_idx, i, j ); - return MAX(input_precision, output_precision); -} - -CxCore_MatrixTestImpl matrix_test( "matrix", "", 0, 0, false, false, 0 ); - - -class CxCore_MatrixTest : public CxCore_MatrixTestImpl -{ -public: - CxCore_MatrixTest( const char* test_name, const char* test_funcs, int in_count, int out_count, - bool allow_int, bool scalar_output, int max_cn ); -}; - - -CxCore_MatrixTest::CxCore_MatrixTest( const char* test_name, const char* test_funcs, - int in_count, int out_count, bool _allow_int, - bool _scalar_output, int _max_cn ) - : CxCore_MatrixTestImpl( test_name, test_funcs, in_count, out_count, - _allow_int, _scalar_output, _max_cn ) -{ - size_list = 0; - depth_list = 0; -} - - -///////////////// Trace ///////////////////// - -class CxCore_TraceTest : public CxCore_MatrixTest -{ -public: - CxCore_TraceTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_TraceTest::CxCore_TraceTest() : - CxCore_MatrixTest( "matrix-trace", "cvTrace", 1, 1, true, true, 4 ) -{ -} - - -void CxCore_TraceTest::run_func() -{ - *((CvScalar*)(test_mat[OUTPUT][0].data.db)) = cvTrace(test_array[INPUT][0]); -} - - -void CxCore_TraceTest::prepare_to_validation( int ) -{ - CvMat* mat = &test_mat[INPUT][0]; - int i, j, count = MIN( mat->rows, mat->cols ); - CvScalar trace = {{0,0,0,0}}; - - for( i = 0; i < count; i++ ) - { - CvScalar el = cvGet2D( mat, i, i ); - for( j = 0; j < 4; j++ ) - trace.val[j] += el.val[j]; - } - - *((CvScalar*)(test_mat[REF_OUTPUT][0].data.db)) = trace; -} - -CxCore_TraceTest trace_test; - - -///////// dotproduct ////////// - -class CxCore_DotProductTest : public CxCore_MatrixTest -{ -public: - CxCore_DotProductTest(); -protected: - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_DotProductTest::CxCore_DotProductTest() : - CxCore_MatrixTest( "matrix-dotproduct", "cvDotProduct", 2, 1, true, true, 4 ) -{ - depth_list = matrix_all_depths; -} - - -void CxCore_DotProductTest::run_func() -{ - *((CvScalar*)(test_mat[OUTPUT][0].data.ptr)) = - cvRealScalar(cvDotProduct( test_array[INPUT][0], test_array[INPUT][1] )); -} - - -void CxCore_DotProductTest::prepare_to_validation( int ) -{ - *((CvScalar*)(test_mat[REF_OUTPUT][0].data.ptr)) = - cvRealScalar(cvTsCrossCorr( &test_mat[INPUT][0], &test_mat[INPUT][1] )); -} - -CxCore_DotProductTest dotproduct_test; - - -///////// crossproduct ////////// - -static const CvSize cross_product_sizes[] = {{3,1}, {-1,-1}}; - -class CxCore_CrossProductTest : public CxCore_MatrixTest -{ -public: - CxCore_CrossProductTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_CrossProductTest::CxCore_CrossProductTest() : - CxCore_MatrixTest( "matrix-crossproduct", "cvCrossProduct", 2, 1, false, false, 1 ) -{ - size_list = cross_product_sizes; -} - - -void CxCore_CrossProductTest::get_test_array_types_and_sizes( int /*test_case_idx*/, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int depth = cvTsRandInt(rng) % 2 + CV_32F; - int cn = cvTsRandInt(rng) & 1 ? 3 : 1, type = CV_MAKETYPE(depth, cn); - CvSize sz; - - types[INPUT][0] = types[INPUT][1] = types[OUTPUT][0] = types[REF_OUTPUT][0] = type; - - if( cn == 3 ) - sz = cvSize(1,1); - else if( cvTsRandInt(rng) & 1 ) - sz = cvSize(3,1); - else - sz = cvSize(1,3); - - sizes[INPUT][0] = sizes[INPUT][1] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sz; -} - - -void CxCore_CrossProductTest::run_func() -{ - cvCrossProduct( test_array[INPUT][0], test_array[INPUT][1], test_array[OUTPUT][0] ); -} - - -void CxCore_CrossProductTest::prepare_to_validation( int ) -{ - CvScalar a = {{0,0,0,0}}, b = {{0,0,0,0}}, c = {{0,0,0,0}}; - - if( test_mat[INPUT][0].rows > 1 ) - { - a.val[0] = cvGetReal2D( &test_mat[INPUT][0], 0, 0 ); - a.val[1] = cvGetReal2D( &test_mat[INPUT][0], 1, 0 ); - a.val[2] = cvGetReal2D( &test_mat[INPUT][0], 2, 0 ); - - b.val[0] = cvGetReal2D( &test_mat[INPUT][1], 0, 0 ); - b.val[1] = cvGetReal2D( &test_mat[INPUT][1], 1, 0 ); - b.val[2] = cvGetReal2D( &test_mat[INPUT][1], 2, 0 ); - } - else if( test_mat[INPUT][0].cols > 1 ) - { - a.val[0] = cvGetReal1D( &test_mat[INPUT][0], 0 ); - a.val[1] = cvGetReal1D( &test_mat[INPUT][0], 1 ); - a.val[2] = cvGetReal1D( &test_mat[INPUT][0], 2 ); - - b.val[0] = cvGetReal1D( &test_mat[INPUT][1], 0 ); - b.val[1] = cvGetReal1D( &test_mat[INPUT][1], 1 ); - b.val[2] = cvGetReal1D( &test_mat[INPUT][1], 2 ); - } - else - { - a = cvGet1D( &test_mat[INPUT][0], 0 ); - b = cvGet1D( &test_mat[INPUT][1], 0 ); - } - - c.val[2] = a.val[0]*b.val[1] - a.val[1]*b.val[0]; - c.val[1] = -a.val[0]*b.val[2] + a.val[2]*b.val[0]; - c.val[0] = a.val[1]*b.val[2] - a.val[2]*b.val[1]; - - if( test_mat[REF_OUTPUT][0].rows > 1 ) - { - cvSetReal2D( &test_mat[REF_OUTPUT][0], 0, 0, c.val[0] ); - cvSetReal2D( &test_mat[REF_OUTPUT][0], 1, 0, c.val[1] ); - cvSetReal2D( &test_mat[REF_OUTPUT][0], 2, 0, c.val[2] ); - } - else if( test_mat[REF_OUTPUT][0].cols > 1 ) - { - cvSetReal1D( &test_mat[REF_OUTPUT][0], 0, c.val[0] ); - cvSetReal1D( &test_mat[REF_OUTPUT][0], 1, c.val[1] ); - cvSetReal1D( &test_mat[REF_OUTPUT][0], 2, c.val[2] ); - } - else - { - cvSet1D( &test_mat[REF_OUTPUT][0], 0, c ); - } -} - -CxCore_CrossProductTest crossproduct_test; - - -///////////////// scaleadd ///////////////////// - -class CxCore_ScaleAddTest : public CxCore_MatrixTest -{ -public: - CxCore_ScaleAddTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - CvScalar alpha; - bool test_nd; -}; - -CxCore_ScaleAddTest::CxCore_ScaleAddTest() : - CxCore_MatrixTest( "matrix-scaleadd", "cvScaleAdd", 3, 1, false, false, 4 ) -{ - alpha = cvScalarAll(0); - test_nd = false; -} - - -void CxCore_ScaleAddTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][2] = cvSize(1,1); - types[INPUT][2] &= CV_MAT_DEPTH_MASK; - test_nd = cvTsRandInt(ts->get_rng()) % 2 != 0; -} - - -void CxCore_ScaleAddTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, are_images ); - sizes[INPUT][2] = cvSize(1,1); - types[INPUT][2] &= CV_MAT_DEPTH_MASK; -} - - -int CxCore_ScaleAddTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - alpha = cvGet1D( &test_mat[INPUT][2], 0 ); - if( test_nd ) - alpha.val[1] = 0; - return code; -} - - -void CxCore_ScaleAddTest::run_func() -{ - if(!test_nd) - cvScaleAdd( test_array[INPUT][0], alpha, test_array[INPUT][1], test_array[OUTPUT][0] ); - else - { - cv::MatND c = cv::cvarrToMatND(test_array[OUTPUT][0]); - cv::scaleAdd( cv::cvarrToMatND(test_array[INPUT][0]), alpha.val[0], - cv::cvarrToMatND(test_array[INPUT][1]), c); - } -} - - -void CxCore_ScaleAddTest::prepare_to_validation( int ) -{ - cvTsAdd( &test_mat[INPUT][0], cvScalarAll(alpha.val[0]), - &test_mat[INPUT][1], cvScalarAll(1.), - cvScalarAll(0.), &test_mat[REF_OUTPUT][0], 0 ); -} - -CxCore_ScaleAddTest scaleadd_test; - - -///////////////// gemm ///////////////////// - -static const char* matrix_gemm_param_names[] = { "size", "add_c", "mul_type", "depth", 0 }; -static const char* matrix_gemm_mul_types[] = { "AB", "AtB", "ABt", "AtBt", 0 }; -static const int matrix_gemm_add_c_flags[] = { 0, 1 }; - -class CxCore_GEMMTest : public CxCore_MatrixTest -{ -public: - CxCore_GEMMTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int tabc_flag; - double alpha, beta; -}; - -CxCore_GEMMTest::CxCore_GEMMTest() : - CxCore_MatrixTest( "matrix-gemm", "cvGEMM", 5, 1, false, false, 2 ) -{ - test_case_count = 100; - max_log_array_size = 10; - default_timing_param_names = matrix_gemm_param_names; - alpha = beta = 0; -} - - -void CxCore_GEMMTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvSize sizeA; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizeA = sizes[INPUT][0]; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sizeA; - sizes[INPUT][2] = sizes[INPUT][3] = cvSize(1,1); - types[INPUT][2] = types[INPUT][3] &= ~CV_MAT_CN_MASK; - - tabc_flag = cvTsRandInt(rng) & 7; - - switch( tabc_flag & (CV_GEMM_A_T|CV_GEMM_B_T) ) - { - case 0: - sizes[INPUT][1].height = sizes[INPUT][0].width; - sizes[OUTPUT][0].height = sizes[INPUT][0].height; - sizes[OUTPUT][0].width = sizes[INPUT][1].width; - break; - case CV_GEMM_B_T: - sizes[INPUT][1].width = sizes[INPUT][0].width; - sizes[OUTPUT][0].height = sizes[INPUT][0].height; - sizes[OUTPUT][0].width = sizes[INPUT][1].height; - break; - case CV_GEMM_A_T: - sizes[INPUT][1].height = sizes[INPUT][0].height; - sizes[OUTPUT][0].height = sizes[INPUT][0].width; - sizes[OUTPUT][0].width = sizes[INPUT][1].width; - break; - case CV_GEMM_A_T | CV_GEMM_B_T: - sizes[INPUT][1].width = sizes[INPUT][0].height; - sizes[OUTPUT][0].height = sizes[INPUT][0].width; - sizes[OUTPUT][0].width = sizes[INPUT][1].height; - break; - } - - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; - - if( cvTsRandInt(rng) & 1 ) - sizes[INPUT][4] = cvSize(0,0); - else if( !(tabc_flag & CV_GEMM_C_T) ) - sizes[INPUT][4] = sizes[OUTPUT][0]; - else - { - sizes[INPUT][4].width = sizes[OUTPUT][0].height; - sizes[INPUT][4].height = sizes[OUTPUT][0].width; - } -} - - -void CxCore_GEMMTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* mul_type = cvReadString( find_timing_param("mul_type"), "AB" ); - if( strcmp( mul_type, "AtB" ) == 0 ) - tabc_flag = CV_GEMM_A_T; - else if( strcmp( mul_type, "ABt" ) == 0 ) - tabc_flag = CV_GEMM_B_T; - else if( strcmp( mul_type, "AtBt" ) == 0 ) - tabc_flag = CV_GEMM_A_T + CV_GEMM_B_T; - else - tabc_flag = 0; - - if( cvReadInt( find_timing_param( "add_c" ), 0 ) == 0 ) - sizes[INPUT][4] = cvSize(0,0); -} - - -int CxCore_GEMMTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MatrixTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "mul_type", matrix_gemm_mul_types ); - write_int_list( fs, "add_c", matrix_gemm_add_c_flags, CV_DIM(matrix_gemm_add_c_flags) ); - return code; -} - - -void CxCore_GEMMTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s%s,%s,", - tabc_flag & CV_GEMM_A_T ? "At" : "A", - tabc_flag & CV_GEMM_B_T ? "Bt" : "B", - test_array[INPUT][4] ? "plusC" : "" ); - ptr += strlen(ptr); - params_left -= 2; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_GEMMTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - alpha = cvmGet( &test_mat[INPUT][2], 0, 0 ); - beta = cvmGet( &test_mat[INPUT][3], 0, 0 ); - } - return code; -} - - -void CxCore_GEMMTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); -} - - -void CxCore_GEMMTest::run_func() -{ - cvGEMM( test_array[INPUT][0], test_array[INPUT][1], alpha, - test_array[INPUT][4], beta, test_array[OUTPUT][0], tabc_flag ); -} - - -void CxCore_GEMMTest::prepare_to_validation( int ) -{ - cvTsGEMM( &test_mat[INPUT][0], &test_mat[INPUT][1], alpha, - test_array[INPUT][4] ? &test_mat[INPUT][4] : 0, - beta, &test_mat[REF_OUTPUT][0], tabc_flag ); -} - -CxCore_GEMMTest gemm_test; - - -///////////////// multransposed ///////////////////// - -static const char* matrix_multrans_param_names[] = { "size", "use_delta", "mul_type", "depth", 0 }; -static const int matrix_multrans_use_delta_flags[] = { 0, 1 }; -static const char* matrix_multrans_mul_types[] = { "AAt", "AtA", 0 }; - -class CxCore_MulTransposedTest : public CxCore_MatrixTest -{ -public: - CxCore_MulTransposedTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int order; -}; - - -CxCore_MulTransposedTest::CxCore_MulTransposedTest() : - CxCore_MatrixTest( "matrix-multransposed", "cvMulTransposed, cvRepeat", 2, 1, false, false, 1 ) -{ - test_case_count = 100; - order = 0; - test_array[TEMP].push(NULL); - default_timing_param_names = matrix_multrans_param_names; -} - - -void CxCore_MulTransposedTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - int src_type = cvTsRandInt(rng) % 5; - int dst_type = cvTsRandInt(rng) % 2; - - src_type = src_type == 0 ? CV_8U : src_type == 1 ? CV_16U : src_type == 2 ? CV_16S : - src_type == 3 ? CV_32F : CV_64F; - dst_type = dst_type == 0 ? CV_32F : CV_64F; - dst_type = MAX( dst_type, src_type ); - - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( bits & 1 ) - sizes[INPUT][1] = cvSize(0,0); - else - { - sizes[INPUT][1] = sizes[INPUT][0]; - if( bits & 2 ) - sizes[INPUT][1].height = 1; - if( bits & 4 ) - sizes[INPUT][1].width = 1; - } - - sizes[TEMP][0] = sizes[INPUT][0]; - types[INPUT][0] = src_type; - types[OUTPUT][0] = types[REF_OUTPUT][0] = types[INPUT][1] = types[TEMP][0] = dst_type; - - order = (bits & 8) != 0; - sizes[OUTPUT][0].width = sizes[OUTPUT][0].height = order == 0 ? - sizes[INPUT][0].height : sizes[INPUT][0].width; - sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; -} - - -void CxCore_MulTransposedTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* mul_type = cvReadString( find_timing_param("mul_type"), "AAt" ); - order = strcmp( mul_type, "AtA" ) == 0; - - if( cvReadInt( find_timing_param( "use_delta" ), 0 ) == 0 ) - sizes[INPUT][1] = cvSize(0,0); -} - - -int CxCore_MulTransposedTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MatrixTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "mul_type", matrix_multrans_mul_types ); - write_int_list( fs, "use_delta", matrix_multrans_use_delta_flags, - CV_DIM(matrix_multrans_use_delta_flags) ); - return code; -} - - -void CxCore_MulTransposedTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,%s,", order == 0 ? "AAt" : "AtA", test_array[INPUT][1] ? "delta" : "" ); - ptr += strlen(ptr); - params_left -= 2; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -void CxCore_MulTransposedTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-10.); - *high = cvScalarAll(10.); -} - - -void CxCore_MulTransposedTest::run_func() -{ - cvMulTransposed( test_array[INPUT][0], test_array[OUTPUT][0], - order, test_array[INPUT][1] ); -} - - -void CxCore_MulTransposedTest::prepare_to_validation( int ) -{ - CvMat* delta = test_array[INPUT][1] ? &test_mat[INPUT][1] : 0; - if( delta ) - { - if( test_mat[INPUT][1].rows < test_mat[INPUT][0].rows || - test_mat[INPUT][1].cols < test_mat[INPUT][0].cols ) - { - cvRepeat( delta, &test_mat[TEMP][0] ); - delta = &test_mat[TEMP][0]; - } - cvTsAdd( &test_mat[INPUT][0], cvScalarAll(1.), delta, cvScalarAll(-1.), - cvScalarAll(0.), &test_mat[TEMP][0], 0 ); - } - else - cvTsConvert( &test_mat[INPUT][0], &test_mat[TEMP][0] ); - delta = &test_mat[TEMP][0]; - - cvTsGEMM( delta, delta, 1., 0, 0, &test_mat[REF_OUTPUT][0], order == 0 ? CV_GEMM_B_T : CV_GEMM_A_T ); -} - -CxCore_MulTransposedTest multransposed_test; - - -///////////////// Transform ///////////////////// - -static const CvSize matrix_transform_sizes[] = {{10,10}, {100,100}, {720,480}, {-1,-1}}; -static const CvSize matrix_transform_whole_sizes[] = {{10,10}, {720,480}, {720,480}, {-1,-1}}; -static const int matrix_transform_channels[] = { 2, 3, 4, -1 }; -static const char* matrix_transform_param_names[] = { "size", "channels", "depth", 0 }; - -class CxCore_TransformTest : public CxCore_MatrixTest -{ -public: - CxCore_TransformTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - - double scale; - bool diagMtx; -}; - - -CxCore_TransformTest::CxCore_TransformTest() : - CxCore_MatrixTest( "matrix-transform", "cvTransform", 3, 1, true, false, 4 ) -{ - default_timing_param_names = matrix_transform_param_names; - cn_list = matrix_transform_channels; - depth_list = matrix_all_depths; - size_list = matrix_transform_sizes; - whole_size_list = matrix_transform_whole_sizes; -} - - -void CxCore_TransformTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - int depth, dst_cn, mat_cols, mattype; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - mat_cols = CV_MAT_CN(types[INPUT][0]); - depth = CV_MAT_DEPTH(types[INPUT][0]); - dst_cn = cvTsRandInt(rng) % 4 + 1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, dst_cn); - - mattype = depth < CV_32S ? CV_32F : depth == CV_64F ? CV_64F : bits & 1 ? CV_32F : CV_64F; - types[INPUT][1] = mattype; - types[INPUT][2] = CV_MAKETYPE(mattype, dst_cn); - - scale = 1./((cvTsRandInt(rng)%4)*50+1); - - if( bits & 2 ) - { - sizes[INPUT][2] = cvSize(0,0); - mat_cols += (bits & 4) != 0; - } - else if( bits & 4 ) - sizes[INPUT][2] = cvSize(1,1); - else - { - if( bits & 8 ) - sizes[INPUT][2] = cvSize(dst_cn,1); - else - sizes[INPUT][2] = cvSize(1,dst_cn); - types[INPUT][2] &= ~CV_MAT_CN_MASK; - } - diagMtx = (bits & 16) != 0; - - sizes[INPUT][1] = cvSize(mat_cols,dst_cn); -} - - -void CxCore_TransformTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - int cn = CV_MAT_CN(types[INPUT][0]); - sizes[INPUT][1] = cvSize(cn + (cn < 4), cn); - sizes[INPUT][2] = cvSize(0,0); - types[INPUT][1] = types[INPUT][2] = CV_64FC1; - scale = 1./1000; -} - -int CxCore_TransformTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - cvTsAdd(&test_mat[INPUT][1], cvScalarAll(scale), &test_mat[INPUT][1], - cvScalarAll(0), cvScalarAll(0), &test_mat[INPUT][1], 0 ); - if(diagMtx) - { - CvMat* w = cvCloneMat(&test_mat[INPUT][1]); - cvSetIdentity(w, cvScalarAll(1)); - cvMul(w, &test_mat[INPUT][1], &test_mat[INPUT][1]); - cvReleaseMat(&w); - } - } - return code; -} - -void CxCore_TransformTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - CvSize size = cvGetMatSize(&test_mat[INPUT][1]); - sprintf( ptr, "matrix=%dx%d,", size.height, size.width ); - ptr += strlen(ptr); - params_left--; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_TransformTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth <= CV_8S ? 1 : depth <= CV_32S ? 9 : - CxCore_MatrixTest::get_success_error_level( test_case_idx, i, j ); -} - -void CxCore_TransformTest::run_func() -{ - cvTransform( test_array[INPUT][0], test_array[OUTPUT][0], &test_mat[INPUT][1], - test_array[INPUT][2] ? &test_mat[INPUT][2] : 0); -} - - -void CxCore_TransformTest::prepare_to_validation( int ) -{ - CvMat* transmat = &test_mat[INPUT][1]; - CvMat* shift = test_array[INPUT][2] ? &test_mat[INPUT][2] : 0; - - cvTsTransform( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], transmat, shift ); -} - -CxCore_TransformTest transform_test; - - -///////////////// PerspectiveTransform ///////////////////// - -static const int matrix_perspective_transform_channels[] = { 2, 3, -1 }; - -class CxCore_PerspectiveTransformTest : public CxCore_MatrixTest -{ -public: - CxCore_PerspectiveTransformTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_PerspectiveTransformTest::CxCore_PerspectiveTransformTest() : - CxCore_MatrixTest( "matrix-perspective", "cvPerspectiveTransform", 2, 1, false, false, 2 ) -{ - default_timing_param_names = matrix_transform_param_names; - cn_list = matrix_perspective_transform_channels; - size_list = matrix_transform_sizes; - whole_size_list = matrix_transform_whole_sizes; -} - - -void CxCore_PerspectiveTransformTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - int depth, cn, mattype; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - cn = CV_MAT_CN(types[INPUT][0]) + 1; - depth = CV_MAT_DEPTH(types[INPUT][0]); - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, cn); - - mattype = depth == CV_64F ? CV_64F : bits & 1 ? CV_32F : CV_64F; - types[INPUT][1] = mattype; - sizes[INPUT][1] = cvSize(cn + 1, cn + 1); -} - - -double CxCore_PerspectiveTransformTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int depth = CV_MAT_DEPTH(test_mat[INPUT][0].type); - return depth == CV_32F ? 1e-4 : depth == CV_64F ? 1e-8 : - CxCore_MatrixTest::get_success_error_level(test_case_idx, i, j); -} - - -void CxCore_PerspectiveTransformTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - int cn = CV_MAT_CN(types[INPUT][0]); - sizes[INPUT][1] = cvSize(cn + 1, cn + 1); - types[INPUT][1] = CV_64FC1; -} - - -void CxCore_PerspectiveTransformTest::run_func() -{ - cvPerspectiveTransform( test_array[INPUT][0], test_array[OUTPUT][0], &test_mat[INPUT][1] ); -} - - -static void cvTsPerspectiveTransform( const CvArr* _src, CvArr* _dst, const CvMat* transmat ) -{ - int i, j, cols; - int cn, depth, mat_depth; - CvMat astub, bstub, *a, *b; - double mat[16], *buf; - - a = cvGetMat( _src, &astub, 0, 0 ); - b = cvGetMat( _dst, &bstub, 0, 0 ); - - cn = CV_MAT_CN(a->type); - depth = CV_MAT_DEPTH(a->type); - mat_depth = CV_MAT_DEPTH(transmat->type); - cols = transmat->cols; - - // prepare cn x (cn + 1) transform matrix - if( mat_depth == CV_32F ) - { - for( i = 0; i < transmat->rows; i++ ) - for( j = 0; j < cols; j++ ) - mat[i*cols + j] = ((float*)(transmat->data.ptr + transmat->step*i))[j]; - } - else - { - assert( mat_depth == CV_64F ); - for( i = 0; i < transmat->rows; i++ ) - for( j = 0; j < cols; j++ ) - mat[i*cols + j] = ((double*)(transmat->data.ptr + transmat->step*i))[j]; - } - - // transform data - cols = a->cols * cn; - buf = (double*)cvStackAlloc( cols * sizeof(double) ); - - for( i = 0; i < a->rows; i++ ) - { - uchar* src = a->data.ptr + i*a->step; - uchar* dst = b->data.ptr + i*b->step; - - switch( depth ) - { - case CV_32F: - for( j = 0; j < cols; j++ ) - buf[j] = ((float*)src)[j]; - break; - case CV_64F: - for( j = 0; j < cols; j++ ) - buf[j] = ((double*)src)[j]; - break; - default: - assert(0); - } - - switch( cn ) - { - case 2: - for( j = 0; j < cols; j += 2 ) - { - double t0 = buf[j]*mat[0] + buf[j+1]*mat[1] + mat[2]; - double t1 = buf[j]*mat[3] + buf[j+1]*mat[4] + mat[5]; - double w = buf[j]*mat[6] + buf[j+1]*mat[7] + mat[8]; - w = w ? 1./w : 0; - buf[j] = t0*w; - buf[j+1] = t1*w; - } - break; - case 3: - for( j = 0; j < cols; j += 3 ) - { - double t0 = buf[j]*mat[0] + buf[j+1]*mat[1] + buf[j+2]*mat[2] + mat[3]; - double t1 = buf[j]*mat[4] + buf[j+1]*mat[5] + buf[j+2]*mat[6] + mat[7]; - double t2 = buf[j]*mat[8] + buf[j+1]*mat[9] + buf[j+2]*mat[10] + mat[11]; - double w = buf[j]*mat[12] + buf[j+1]*mat[13] + buf[j+2]*mat[14] + mat[15]; - w = w ? 1./w : 0; - buf[j] = t0*w; - buf[j+1] = t1*w; - buf[j+2] = t2*w; - } - break; - default: - assert(0); - } - - switch( depth ) - { - case CV_32F: - for( j = 0; j < cols; j++ ) - ((float*)dst)[j] = (float)buf[j]; - break; - case CV_64F: - for( j = 0; j < cols; j++ ) - ((double*)dst)[j] = buf[j]; - break; - default: - assert(0); - } - } -} - - -void CxCore_PerspectiveTransformTest::prepare_to_validation( int ) -{ - CvMat* transmat = &test_mat[INPUT][1]; - cvTsPerspectiveTransform( test_array[INPUT][0], test_array[REF_OUTPUT][0], transmat ); -} - -CxCore_PerspectiveTransformTest perspective_test; - - -///////////////// Mahalanobis ///////////////////// - -class CxCore_MahalanobisTest : public CxCore_MatrixTest -{ -public: - CxCore_MahalanobisTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_MahalanobisTest::CxCore_MahalanobisTest() : - CxCore_MatrixTest( "matrix-mahalanobis", "cvMahalanobis", 3, 1, false, true, 1 ) -{ - test_case_count = 100; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); -} - - -void CxCore_MahalanobisTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - if( cvTsRandInt(rng) & 1 ) - sizes[INPUT][0].width = sizes[INPUT][1].width = 1; - else - sizes[INPUT][0].height = sizes[INPUT][1].height = 1; - - sizes[TEMP][0] = sizes[TEMP][1] = sizes[INPUT][0]; - sizes[INPUT][2].width = sizes[INPUT][2].height = sizes[INPUT][0].width + sizes[INPUT][0].height - 1; - sizes[TEMP][2] = sizes[INPUT][2]; - types[TEMP][0] = types[TEMP][1] = types[TEMP][2] = types[INPUT][0]; -} - - -void CxCore_MahalanobisTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - sizes[INPUT][0].height = sizes[INPUT][1].height = 1; -} - - -int CxCore_MahalanobisTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 && ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - // make sure that the inverted "covariation" matrix is symmetrix and positively defined. - cvTsGEMM( &test_mat[INPUT][2], &test_mat[INPUT][2], 1., 0, 0., &test_mat[TEMP][2], CV_GEMM_B_T ); - cvTsCopy( &test_mat[TEMP][2], &test_mat[INPUT][2] ); - } - - return code; -} - - -void CxCore_MahalanobisTest::run_func() -{ - *((CvScalar*)(test_mat[OUTPUT][0].data.db)) = - cvRealScalar(cvMahalanobis(test_array[INPUT][0], test_array[INPUT][1], test_array[INPUT][2])); -} - -void CxCore_MahalanobisTest::prepare_to_validation( int ) -{ - cvTsAdd( &test_mat[INPUT][0], cvScalarAll(1.), - &test_mat[INPUT][1], cvScalarAll(-1.), - cvScalarAll(0.), &test_mat[TEMP][0], 0 ); - if( test_mat[INPUT][0].rows == 1 ) - cvTsGEMM( &test_mat[TEMP][0], &test_mat[INPUT][2], 1., - 0, 0., &test_mat[TEMP][1], 0 ); - else - cvTsGEMM( &test_mat[INPUT][2], &test_mat[TEMP][0], 1., - 0, 0., &test_mat[TEMP][1], 0 ); - - *((CvScalar*)(test_mat[REF_OUTPUT][0].data.db)) = - cvRealScalar(sqrt(cvTsCrossCorr(&test_mat[TEMP][0], &test_mat[TEMP][1]))); -} - -CxCore_MahalanobisTest mahalanobis_test; - - -///////////////// covarmatrix ///////////////////// - -class CxCore_CovarMatrixTest : public CxCore_MatrixTest -{ -public: - CxCore_CovarMatrixTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - CvTestPtrVec temp_hdrs; - uchar* hdr_data; - int flags, t_flag, len, count; - bool are_images; -}; - - -CxCore_CovarMatrixTest::CxCore_CovarMatrixTest() : - CxCore_MatrixTest( "matrix-covar", "cvCalcCovarMatrix", 1, 1, true, false, 1 ), - flags(0), t_flag(0), are_images(false) -{ - test_case_count = 100; - test_array[INPUT_OUTPUT].push(NULL); - test_array[REF_INPUT_OUTPUT].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - - -void CxCore_CovarMatrixTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - int i, single_matrix; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - flags = bits & (CV_COVAR_NORMAL | CV_COVAR_USE_AVG | CV_COVAR_SCALE | CV_COVAR_ROWS ); - single_matrix = flags & CV_COVAR_ROWS; - t_flag = (bits & 256) != 0; - - const int min_count = 2; - - if( !t_flag ) - { - len = sizes[INPUT][0].width; - count = sizes[INPUT][0].height; - count = MAX(count, min_count); - sizes[INPUT][0] = cvSize(len, count); - } - else - { - len = sizes[INPUT][0].height; - count = sizes[INPUT][0].width; - count = MAX(count, min_count); - sizes[INPUT][0] = cvSize(count, len); - } - - if( single_matrix && t_flag ) - flags = (flags & ~CV_COVAR_ROWS) | CV_COVAR_COLS; - - if( CV_MAT_DEPTH(types[INPUT][0]) == CV_32S ) - types[INPUT][0] = (types[INPUT][0] & ~CV_MAT_DEPTH_MASK) | CV_32F; - - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = flags & CV_COVAR_NORMAL ? cvSize(len,len) : cvSize(count,count); - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = !t_flag ? cvSize(len,1) : cvSize(1,len); - sizes[TEMP][0] = sizes[INPUT][0]; - - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = - types[OUTPUT][0] = types[REF_OUTPUT][0] = types[TEMP][0] = - CV_MAT_DEPTH(types[INPUT][0]) == CV_64F || (bits & 512) ? CV_64F : CV_32F; - - are_images = (bits & 1024) != 0; - for( i = 0; i < (single_matrix ? 1 : count); i++ ) - temp_hdrs.push(NULL); -} - - -int CxCore_CovarMatrixTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - int i; - int single_matrix = flags & (CV_COVAR_ROWS|CV_COVAR_COLS); - int hdr_size = are_images ? sizeof(IplImage) : sizeof(CvMat); - - hdr_data = (uchar*)cvAlloc( count*hdr_size ); - if( single_matrix ) - { - if( !are_images ) - *((CvMat*)hdr_data) = test_mat[INPUT][0]; - else - cvGetImage( &test_mat[INPUT][0], (IplImage*)hdr_data ); - temp_hdrs[0] = hdr_data; - } - else - for( i = 0; i < count; i++ ) - { - CvMat part; - void* ptr = hdr_data + i*hdr_size; - - if( !t_flag ) - cvGetRow( &test_mat[INPUT][0], &part, i ); - else - cvGetCol( &test_mat[INPUT][0], &part, i ); - - if( !are_images ) - *((CvMat*)ptr) = part; - else - cvGetImage( &part, (IplImage*)ptr ); - - temp_hdrs[i] = ptr; - } - } - - return code; -} - - -void CxCore_CovarMatrixTest::run_func() -{ - cvCalcCovarMatrix( (const void**)&temp_hdrs[0], count, - test_array[OUTPUT][0], test_array[INPUT_OUTPUT][0], flags ); -} - - -void CxCore_CovarMatrixTest::prepare_to_validation( int ) -{ - CvMat* avg = &test_mat[REF_INPUT_OUTPUT][0]; - double scale = 1.; - - if( !(flags & CV_COVAR_USE_AVG) ) - { - int i; - cvTsZero( avg ); - - for( i = 0; i < count; i++ ) - { - CvMat stub, *vec = 0; - if( flags & CV_COVAR_ROWS ) - vec = cvGetRow( temp_hdrs[0], &stub, i ); - else if( flags & CV_COVAR_COLS ) - vec = cvGetCol( temp_hdrs[0], &stub, i ); - else - vec = cvGetMat( temp_hdrs[i], &stub ); - - cvTsAdd( avg, cvScalarAll(1.), vec, - cvScalarAll(1.), cvScalarAll(0.), avg, 0 ); - } - - cvTsAdd( avg, cvScalarAll(1./count), 0, - cvScalarAll(0.), cvScalarAll(0.), avg, 0 ); - } - - if( flags & CV_COVAR_SCALE ) - { - scale = 1./count; - } - - cvRepeat( avg, &test_mat[TEMP][0] ); - cvTsAdd( &test_mat[INPUT][0], cvScalarAll(1.), - &test_mat[TEMP][0], cvScalarAll(-1.), - cvScalarAll(0.), &test_mat[TEMP][0], 0 ); - - cvTsGEMM( &test_mat[TEMP][0], &test_mat[TEMP][0], - scale, 0, 0., &test_mat[REF_OUTPUT][0], - t_flag ^ ((flags & CV_COVAR_NORMAL) != 0) ? - CV_GEMM_A_T : CV_GEMM_B_T ); - - cvFree( &hdr_data ); - temp_hdrs.clear(); -} - -CxCore_CovarMatrixTest covarmatrix_test; - - -static void cvTsFloodWithZeros( CvMat* mat, CvRNG* rng ) -{ - int k, total = mat->rows*mat->cols; - int zero_total = cvTsRandInt(rng) % total; - assert( CV_MAT_TYPE(mat->type) == CV_32FC1 || - CV_MAT_TYPE(mat->type) == CV_64FC1 ); - - for( k = 0; k < zero_total; k++ ) - { - int i = cvTsRandInt(rng) % mat->rows; - int j = cvTsRandInt(rng) % mat->cols; - uchar* row = mat->data.ptr + mat->step*i; - - if( CV_MAT_DEPTH(mat->type) == CV_32FC1 ) - ((float*)row)[j] = 0.f; - else - ((double*)row)[j] = 0.; - } -} - - -///////////////// determinant ///////////////////// - -class CxCore_DetTest : public CxCore_MatrixTest -{ -public: - CxCore_DetTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); -}; - - -CxCore_DetTest::CxCore_DetTest() : - CxCore_MatrixTest( "matrix-det", "cvDet", 1, 1, false, true, 1 ) -{ - test_case_count = 100; - max_log_array_size = 7; - test_array[TEMP].push(NULL); -} - - -void CxCore_DetTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - sizes[INPUT][0].width = sizes[INPUT][0].height = sizes[INPUT][0].height; - sizes[TEMP][0] = sizes[INPUT][0]; - types[TEMP][0] = CV_64FC1; -} - - -void CxCore_DetTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-2.); - *high = cvScalarAll(2.); -} - - -double CxCore_DetTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])) == CV_32F ? 1e-2 : 1e-5; -} - - -int CxCore_DetTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - cvTsFloodWithZeros( &test_mat[INPUT][0], ts->get_rng() ); - - return code; -} - - -void CxCore_DetTest::run_func() -{ - *((CvScalar*)(test_mat[OUTPUT][0].data.db)) = cvRealScalar(cvDet(test_array[INPUT][0])); -} - - -// LU method that chooses the optimal in a column pivot element -static double cvTsLU( CvMat* a, CvMat* b=NULL, CvMat* x=NULL, int* rank=0 ) -{ - int i, j, k, N = a->rows, N1 = a->cols, Nm = MIN(N, N1), step = a->step/sizeof(double); - int M = b ? b->cols : 0, b_step = b ? b->step/sizeof(double) : 0; - int x_step = x ? x->step/sizeof(double) : 0; - double *a0 = a->data.db, *b0 = b ? b->data.db : 0; - double *x0 = x ? x->data.db : 0; - double t, det = 1.; - assert( CV_MAT_TYPE(a->type) == CV_64FC1 && - (!b || CV_ARE_TYPES_EQ(a,b)) && (!x || CV_ARE_TYPES_EQ(a,x))); - - for( i = 0; i < Nm; i++ ) - { - double max_val = fabs(a0[i*step + i]); - double *a1, *a2, *b1 = 0, *b2 = 0; - k = i; - - for( j = i+1; j < N; j++ ) - { - t = fabs(a0[j*step + i]); - if( max_val < t ) - { - max_val = t; - k = j; - } - } - - if( k != i ) - { - for( j = i; j < N1; j++ ) - CV_SWAP( a0[i*step + j], a0[k*step + j], t ); - - for( j = 0; j < M; j++ ) - CV_SWAP( b0[i*b_step + j], b0[k*b_step + j], t ); - det = -det; - } - - if( max_val == 0 ) - { - if( rank ) - *rank = i; - return 0.; - } - - a1 = a0 + i*step; - a2 = a1 + step; - b1 = b0 + i*b_step; - b2 = b1 + b_step; - - for( j = i+1; j < N; j++, a2 += step, b2 += b_step ) - { - t = a2[i]/a1[i]; - for( k = i+1; k < N1; k++ ) - a2[k] -= t*a1[k]; - - for( k = 0; k < M; k++ ) - b2[k] -= t*b1[k]; - } - - det *= a1[i]; - } - - if( x ) - { - assert( b ); - - for( i = N-1; i >= 0; i-- ) - { - double* a1 = a0 + i*step; - double* b1 = b0 + i*b_step; - for( j = 0; j < M; j++ ) - { - t = b1[j]; - for( k = i+1; k < N1; k++ ) - t -= a1[k]*x0[k*x_step + j]; - x0[i*x_step + j] = t/a1[i]; - } - } - } - - if( rank ) - *rank = i; - return det; -} - - -void CxCore_DetTest::prepare_to_validation( int ) -{ - if( !CV_ARE_TYPES_EQ( &test_mat[INPUT][0], &test_mat[TEMP][0] )) - cvTsConvert( &test_mat[INPUT][0], &test_mat[TEMP][0] ); - else - cvTsCopy( &test_mat[INPUT][0], &test_mat[TEMP][0], 0 ); - - *((CvScalar*)(test_mat[REF_OUTPUT][0].data.db)) = cvRealScalar(cvTsLU(&test_mat[TEMP][0], 0, 0)); -} - -CxCore_DetTest det_test; - - - -///////////////// invert ///////////////////// - -static const char* matrix_solve_invert_param_names[] = { "size", "method", "depth", 0 }; -static const char* matrix_solve_invert_methods[] = { "LU", "SVD", 0 }; - -class CxCore_InvertTest : public CxCore_MatrixTest -{ -public: - CxCore_InvertTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int method, rank; - double result; -}; - - -CxCore_InvertTest::CxCore_InvertTest() : - CxCore_MatrixTest( "matrix-invert", "cvInvert, cvSVD, cvSVBkSb", 1, 1, false, false, 1 ), method(0), rank(0), result(0.) -{ - test_case_count = 100; - max_log_array_size = 7; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - default_timing_param_names = matrix_solve_invert_param_names; -} - - -void CxCore_InvertTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int min_size = MIN( sizes[INPUT][0].width, sizes[INPUT][0].height ); - - if( (bits & 3) == 0 ) - { - method = CV_SVD; - if( bits & 4 ) - { - sizes[INPUT][0] = cvSize(min_size, min_size); - if( bits & 16 ) - method = CV_CHOLESKY; - } - } - else - { - method = CV_LU; - sizes[INPUT][0] = cvSize(min_size, min_size); - } - - sizes[TEMP][0].width = sizes[INPUT][0].height; - sizes[TEMP][0].height = sizes[INPUT][0].width; - sizes[TEMP][1] = sizes[INPUT][0]; - types[TEMP][0] = types[INPUT][0]; - types[TEMP][1] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(min_size, min_size); -} - - -void CxCore_InvertTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* method_str = cvReadString( find_timing_param("method"), "LU" ); - method = strcmp( method_str, "LU" ) == 0 ? CV_LU : CV_SVD; -} - - -int CxCore_InvertTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MatrixTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "method", matrix_solve_invert_methods ); - return code; -} - - -void CxCore_InvertTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", method == CV_LU ? "LU" : "SVD" ); - ptr += strlen(ptr); - params_left--; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -double CxCore_InvertTest::get_success_error_level( int /*test_case_idx*/, int, int ) -{ - return CV_MAT_DEPTH(cvGetElemType(test_array[OUTPUT][0])) == CV_32F ? 1e-2 : 1e-6; -} - -int CxCore_InvertTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - cvTsFloodWithZeros( &test_mat[INPUT][0], ts->get_rng() ); - - if( method == CV_CHOLESKY ) - { - cvTsGEMM( &test_mat[INPUT][0], &test_mat[INPUT][0], 1., - 0, 0., &test_mat[TEMP][0], CV_GEMM_B_T ); - cvTsCopy( &test_mat[TEMP][0], &test_mat[INPUT][0] ); - } - } - - return code; -} - - - -void CxCore_InvertTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-1.); - *high = cvScalarAll(1.); -} - - -void CxCore_InvertTest::run_func() -{ - result = cvInvert(test_array[INPUT][0], test_array[TEMP][0], method); -} - - -static double cvTsSVDet( CvMat* mat, double* ratio ) -{ - int type = CV_MAT_TYPE(mat->type); - int i, nm = MIN( mat->rows, mat->cols ); - CvMat* w = cvCreateMat( nm, 1, type ); - double det = 1.; - - cvSVD( mat, w, 0, 0, 0 ); - - if( type == CV_32FC1 ) - { - for( i = 0; i < nm; i++ ) - det *= w->data.fl[i]; - *ratio = w->data.fl[nm-1] < FLT_EPSILON ? FLT_MAX : w->data.fl[nm-1]/w->data.fl[0]; - } - else - { - for( i = 0; i < nm; i++ ) - det *= w->data.db[i]; - *ratio = w->data.db[nm-1] < FLT_EPSILON ? DBL_MAX : w->data.db[nm-1]/w->data.db[0]; - } - - cvReleaseMat( &w ); - return det; -} - -void CxCore_InvertTest::prepare_to_validation( int ) -{ - CvMat* input = &test_mat[INPUT][0]; - double ratio = 0, det = cvTsSVDet( input, &ratio ); - double threshold = (CV_MAT_DEPTH(input->type) == CV_32F ? FLT_EPSILON : DBL_EPSILON)*1000; - - if( CV_MAT_TYPE(input->type) == CV_32FC1 ) - cvTsConvert( input, &test_mat[TEMP][1] ); - else - cvTsCopy( input, &test_mat[TEMP][1], 0 ); - - if( det < threshold || - ((method == CV_LU || method == CV_CHOLESKY) && (result == 0 || ratio < threshold)) || - ((method == CV_SVD || method == CV_SVD_SYM) && result < threshold) ) - { - cvTsZero( &test_mat[OUTPUT][0] ); - cvTsZero( &test_mat[REF_OUTPUT][0] ); - //cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), cvScalarAll(fabs(det)>1e-3), - // &test_mat[REF_OUTPUT][0], 0 ); - return; - } - - if( input->rows >= input->cols ) - cvTsGEMM( &test_mat[TEMP][0], input, 1., 0, 0., &test_mat[OUTPUT][0], 0 ); - else - cvTsGEMM( input, &test_mat[TEMP][0], 1., 0, 0., &test_mat[OUTPUT][0], 0 ); - - cvTsSetIdentity( &test_mat[REF_OUTPUT][0], cvScalarAll(1.) ); -} - -CxCore_InvertTest invert_test; - - -///////////////// solve ///////////////////// - -class CxCore_SolveTest : public CxCore_MatrixTest -{ -public: - CxCore_SolveTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - double get_success_error_level( int test_case_idx, int i, int j ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int method, rank; - double result; -}; - - -CxCore_SolveTest::CxCore_SolveTest() : - CxCore_MatrixTest( "matrix-solve", "cvSolve, cvSVD, cvSVBkSb", 2, 1, false, false, 1 ), method(0), rank(0), result(0.) -{ - test_case_count = 100; - max_log_array_size = 7; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - default_timing_param_names = matrix_solve_invert_param_names; -} - - -void CxCore_SolveTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - CvSize in_sz = sizes[INPUT][0]; - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = in_sz; - int min_size = MIN( sizes[INPUT][0].width, sizes[INPUT][0].height ); - - if( (bits & 3) == 0 ) - { - method = CV_SVD; - if( bits & 4 ) - { - sizes[INPUT][0] = cvSize(min_size, min_size); - /*if( bits & 8 ) - method = CV_SVD_SYM;*/ - } - } - else - { - method = CV_LU; - sizes[INPUT][0] = cvSize(min_size, min_size); - } - - sizes[INPUT][1].height = sizes[INPUT][0].height; - sizes[TEMP][0].width = sizes[INPUT][1].width; - sizes[TEMP][0].height = sizes[INPUT][0].width; - sizes[TEMP][1] = sizes[INPUT][0]; - types[TEMP][0] = types[INPUT][0]; - types[TEMP][1] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(sizes[INPUT][1].width, min_size); -} - -void CxCore_SolveTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* method_str = cvReadString( find_timing_param("method"), "LU" ); - sizes[INPUT][1].width = sizes[TEMP][0].width = sizes[OUTPUT][0].width = sizes[REF_OUTPUT][0].width = 1; - method = strcmp( method_str, "LU" ) == 0 ? CV_LU : CV_SVD; -} - - -int CxCore_SolveTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MatrixTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "method", matrix_solve_invert_methods ); - return code; -} - - -void CxCore_SolveTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", method == CV_LU ? "LU" : "SVD" ); - ptr += strlen(ptr); - params_left--; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_SolveTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - - /*if( method == CV_SVD_SYM ) - { - cvTsGEMM( test_array[INPUT][0], test_array[INPUT][0], 1., - 0, 0., test_array[TEMP][0], CV_GEMM_B_T ); - cvTsCopy( test_array[TEMP][0], test_array[INPUT][0] ); - }*/ - - return code; -} - - -void CxCore_SolveTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-1.); - *high = cvScalarAll(1.); -} - - -double CxCore_SolveTest::get_success_error_level( int /*test_case_idx*/, int, int ) -{ - return CV_MAT_DEPTH(cvGetElemType(test_array[OUTPUT][0])) == CV_32F ? 5e-2 : 1e-8; -} - - -void CxCore_SolveTest::run_func() -{ - result = cvSolve(test_array[INPUT][0], test_array[INPUT][1], test_array[TEMP][0], method); -} - -void CxCore_SolveTest::prepare_to_validation( int ) -{ - //int rank = test_mat[REF_OUTPUT][0].rows; - CvMat* dst; - CvMat* input = &test_mat[INPUT][0]; - - if( method == CV_LU ) - { - if( result == 0 ) - { - if( CV_MAT_TYPE(input->type) == CV_32FC1 ) - cvTsConvert( input, &test_mat[TEMP][1] ); - else - cvTsCopy( input, &test_mat[TEMP][1], 0 ); - - cvTsZero( &test_mat[OUTPUT][0] ); - double det = cvTsLU( &test_mat[TEMP][1], 0, 0 ); - cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), cvScalarAll(det != 0), - &test_mat[REF_OUTPUT][0], 0 ); - return; - } - - double threshold = (CV_MAT_DEPTH(input->type) == CV_32F ? FLT_EPSILON : DBL_EPSILON)*1000; - double ratio = 0, det = cvTsSVDet( input, &ratio ); - if( det < threshold || ratio < threshold ) - { - cvTsZero( &test_mat[OUTPUT][0] ); - cvTsZero( &test_mat[REF_OUTPUT][0] ); - return; - } - } - - - dst = input->rows <= input->cols ? &test_mat[OUTPUT][0] : &test_mat[INPUT][1]; - - cvTsGEMM( input, &test_mat[TEMP][0], 1., &test_mat[INPUT][1], -1., dst, 0 ); - if( dst != &test_mat[OUTPUT][0] ) - cvTsGEMM( input, dst, 1., 0, 0., &test_mat[OUTPUT][0], CV_GEMM_A_T ); - cvTsZero( &test_mat[REF_OUTPUT][0] ); -} - -CxCore_SolveTest solve_test; - - -///////////////// SVD ///////////////////// - -static const char* matrix_svd_param_names[] = { "size", "output", "depth", 0 }; -static const char* matrix_svd_output_modes[] = { "w", "all", 0 }; - -class CxCore_SVDTest : public CxCore_MatrixTest -{ -public: - CxCore_SVDTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - int write_default_params( CvFileStorage* fs ); - void print_timing_params( int test_case_idx, char* ptr, int params_left ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int flags; - bool have_u, have_v, symmetric, compact, vector_w; -}; - - -CxCore_SVDTest::CxCore_SVDTest() : - CxCore_MatrixTest( "matrix-svd", "cvSVD", 1, 4, false, false, 1 ), - flags(0), have_u(false), have_v(false), symmetric(false), compact(false), vector_w(false) -{ - test_case_count = 100; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - - default_timing_param_names = matrix_svd_param_names; -} - - -void CxCore_SVDTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int min_size, i, m, n; - - min_size = MIN( sizes[INPUT][0].width, sizes[INPUT][0].height ); - - flags = bits & (CV_SVD_MODIFY_A+CV_SVD_U_T+CV_SVD_V_T); - have_u = (bits & 8) != 0; - have_v = (bits & 16) != 0; - symmetric = (bits & 32) != 0; - compact = (bits & 64) != 0; - vector_w = (bits & 128) != 0; - - if( symmetric ) - sizes[INPUT][0] = cvSize(min_size, min_size); - - m = sizes[INPUT][0].height; - n = sizes[INPUT][0].width; - - if( compact ) - sizes[TEMP][0] = cvSize(min_size, min_size); - else - sizes[TEMP][0] = sizes[INPUT][0]; - sizes[TEMP][3] = cvSize(0,0); - - if( vector_w ) - { - sizes[TEMP][3] = sizes[TEMP][0]; - if( bits & 256 ) - sizes[TEMP][0] = cvSize(1, min_size); - else - sizes[TEMP][0] = cvSize(min_size, 1); - } - - if( have_u ) - { - sizes[TEMP][1] = compact ? cvSize(min_size, m) : cvSize(m, m); - - if( flags & CV_SVD_U_T ) - CV_SWAP( sizes[TEMP][1].width, sizes[TEMP][1].height, i ); - } - else - sizes[TEMP][1] = cvSize(0,0); - - if( have_v ) - { - sizes[TEMP][2] = compact ? cvSize(n, min_size) : cvSize(n, n); - - if( !(flags & CV_SVD_V_T) ) - CV_SWAP( sizes[TEMP][2].width, sizes[TEMP][2].height, i ); - } - else - sizes[TEMP][2] = cvSize(0,0); - - types[TEMP][0] = types[TEMP][1] = types[TEMP][2] = types[TEMP][3] = types[INPUT][0]; - types[OUTPUT][0] = types[OUTPUT][1] = types[OUTPUT][2] = types[INPUT][0]; - types[OUTPUT][3] = CV_8UC1; - sizes[OUTPUT][0] = !have_u || !have_v ? cvSize(0,0) : sizes[INPUT][0]; - sizes[OUTPUT][1] = !have_u ? cvSize(0,0) : compact ? cvSize(min_size,min_size) : cvSize(m,m); - sizes[OUTPUT][2] = !have_v ? cvSize(0,0) : compact ? cvSize(min_size,min_size) : cvSize(n,n); - sizes[OUTPUT][3] = cvSize(min_size,1); - - for( i = 0; i < 4; i++ ) - { - sizes[REF_OUTPUT][i] = sizes[OUTPUT][i]; - types[REF_OUTPUT][i] = types[OUTPUT][i]; - } -} - - -void CxCore_SVDTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - const char* output_str = cvReadString( find_timing_param("output"), "all" ); - bool need_all = strcmp( output_str, "all" ) == 0; - int i, count = test_array[OUTPUT].size(); - vector_w = true; - symmetric = false; - compact = true; - sizes[TEMP][0] = cvSize(1,sizes[INPUT][0].height); - if( need_all ) - { - have_u = have_v = true; - } - else - { - have_u = have_v = false; - sizes[TEMP][1] = sizes[TEMP][2] = cvSize(0,0); - } - - flags = CV_SVD_U_T + CV_SVD_V_T; - for( i = 0; i < count; i++ ) - sizes[OUTPUT][i] = sizes[REF_OUTPUT][i] = cvSize(0,0); - sizes[OUTPUT][0] = cvSize(1,1); -} - - -int CxCore_SVDTest::write_default_params( CvFileStorage* fs ) -{ - int code = CxCore_MatrixTest::write_default_params(fs); - if( code < 0 || ts->get_testing_mode() != CvTS::TIMING_MODE ) - return code; - write_string_list( fs, "output", matrix_svd_output_modes ); - return code; -} - - -void CxCore_SVDTest::print_timing_params( int test_case_idx, char* ptr, int params_left ) -{ - sprintf( ptr, "%s,", have_u ? "all" : "w" ); - ptr += strlen(ptr); - params_left--; - CxCore_MatrixTest::print_timing_params( test_case_idx, ptr, params_left ); -} - - -int CxCore_SVDTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - CvMat* input = &test_mat[INPUT][0]; - cvTsFloodWithZeros( input, ts->get_rng() ); - - if( symmetric && (have_u || have_v) ) - { - CvMat* temp = &test_mat[TEMP][have_u ? 1 : 2]; - cvTsGEMM( input, input, 1., - 0, 0., temp, CV_GEMM_B_T ); - cvTsCopy( temp, input ); - } - - if( (flags & CV_SVD_MODIFY_A) && test_array[OUTPUT][0] ) - cvTsCopy( input, &test_mat[OUTPUT][0] ); - } - - return code; -} - - -void CxCore_SVDTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-2.); - *high = cvScalarAll(2.); -} - -double CxCore_SVDTest::get_success_error_level( int test_case_idx, int i, int j ) -{ - int input_depth = CV_MAT_DEPTH(cvGetElemType( test_array[INPUT][0] )); - double input_precision = input_depth < CV_32F ? 0 : input_depth == CV_32F ? - 5e-5 : 5e-11; - double output_precision = CvArrTest::get_success_error_level( test_case_idx, i, j ); - return MAX(input_precision, output_precision); -} - -void CxCore_SVDTest::run_func() -{ - CvArr* src = test_array[!(flags & CV_SVD_MODIFY_A) ? INPUT : OUTPUT][0]; - if( !src ) - src = test_array[INPUT][0]; - cvSVD( src, test_array[TEMP][0], test_array[TEMP][1], test_array[TEMP][2], flags ); -} - - -void CxCore_SVDTest::prepare_to_validation( int ) -{ - CvMat* input = &test_mat[INPUT][0]; - int m = input->rows, n = input->cols, min_size = MIN(m, n); - CvMat *src, *dst, *w; - double prev = 0, threshold = CV_MAT_TYPE(input->type) == CV_32FC1 ? FLT_EPSILON : DBL_EPSILON; - int i, j = 0, step; - - if( have_u ) - { - src = &test_mat[TEMP][1]; - dst = &test_mat[OUTPUT][1]; - cvTsGEMM( src, src, 1., 0, 0., dst, src->rows == dst->rows ? CV_GEMM_B_T : CV_GEMM_A_T ); - cvTsSetIdentity( &test_mat[REF_OUTPUT][1], cvScalarAll(1.) ); - } - - if( have_v ) - { - src = &test_mat[TEMP][2]; - dst = &test_mat[OUTPUT][2]; - cvTsGEMM( src, src, 1., 0, 0., dst, src->rows == dst->rows ? CV_GEMM_B_T : CV_GEMM_A_T ); - cvTsSetIdentity( &test_mat[REF_OUTPUT][2], cvScalarAll(1.) ); - } - - w = &test_mat[TEMP][0]; - step = w->rows == 1 ? 1 : w->step/CV_ELEM_SIZE(w->type); - for( i = 0; i < min_size; i++ ) - { - double norm = 0, aii; - uchar* row_ptr; - if( w->rows > 1 && w->cols > 1 ) - { - CvMat row; - cvGetRow( w, &row, i ); - norm = cvNorm( &row, 0, CV_L1 ); - j = i; - row_ptr = row.data.ptr; - } - else - { - row_ptr = w->data.ptr; - j = i*step; - } - - aii = CV_MAT_TYPE(w->type) == CV_32FC1 ? - (double)((float*)row_ptr)[j] : ((double*)row_ptr)[j]; - if( w->rows == 1 || w->cols == 1 ) - norm = aii; - norm = fabs(norm - aii); - test_mat[OUTPUT][3].data.ptr[i] = aii >= 0 && norm < threshold && (i == 0 || aii <= prev); - prev = aii; - } - - cvTsAdd( 0, cvScalarAll(0.), 0, cvScalarAll(0.), - cvScalarAll(1.), &test_mat[REF_OUTPUT][3], 0 ); - - if( have_u && have_v ) - { - if( vector_w ) - { - cvTsZero( &test_mat[TEMP][3] ); - for( i = 0; i < min_size; i++ ) - { - double val = cvGetReal1D( w, i ); - cvSetReal2D( &test_mat[TEMP][3], i, i, val ); - } - w = &test_mat[TEMP][3]; - } - - if( m >= n ) - { - cvTsGEMM( &test_mat[TEMP][1], w, 1., 0, 0., &test_mat[REF_OUTPUT][0], - flags & CV_SVD_U_T ? CV_GEMM_A_T : 0 ); - cvTsGEMM( &test_mat[REF_OUTPUT][0], &test_mat[TEMP][2], 1., 0, 0., - &test_mat[OUTPUT][0], flags & CV_SVD_V_T ? 0 : CV_GEMM_B_T ); - } - else - { - cvTsGEMM( w, &test_mat[TEMP][2], 1., 0, 0., &test_mat[REF_OUTPUT][0], - flags & CV_SVD_V_T ? 0 : CV_GEMM_B_T ); - cvTsGEMM( &test_mat[TEMP][1], &test_mat[REF_OUTPUT][0], 1., 0, 0., - &test_mat[OUTPUT][0], flags & CV_SVD_U_T ? CV_GEMM_A_T : 0 ); - } - - cvTsCopy( &test_mat[INPUT][0], &test_mat[REF_OUTPUT][0], 0 ); - } -} - - -CxCore_SVDTest svd_test; - - -///////////////// SVBkSb ///////////////////// - -class CxCore_SVBkSbTest : public CxCore_MatrixTest -{ -public: - CxCore_SVBkSbTest(); -protected: - void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - void get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ); - double get_success_error_level( int test_case_idx, int i, int j ); - void get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ); - int prepare_test_case( int test_case_idx ); - void run_func(); - void prepare_to_validation( int test_case_idx ); - int flags; - bool have_b, symmetric, compact, vector_w; -}; - - -CxCore_SVBkSbTest::CxCore_SVBkSbTest() : - CxCore_MatrixTest( "matrix-svbksb", "cvSVBkSb", 2, 1, false, false, 1 ), - flags(0), have_b(false), symmetric(false), compact(false), vector_w(false) -{ - test_case_count = 100; - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); - test_array[TEMP].push(NULL); -} - - -void CxCore_SVBkSbTest::get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - int bits = cvTsRandInt(rng); - CxCore_MatrixTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int min_size, i, m, n; - CvSize b_size; - - min_size = MIN( sizes[INPUT][0].width, sizes[INPUT][0].height ); - - flags = bits & (CV_SVD_MODIFY_A+CV_SVD_U_T+CV_SVD_V_T); - have_b = (bits & 16) != 0; - symmetric = (bits & 32) != 0; - compact = (bits & 64) != 0; - vector_w = (bits & 128) != 0; - - if( symmetric ) - sizes[INPUT][0] = cvSize(min_size, min_size); - - m = sizes[INPUT][0].height; - n = sizes[INPUT][0].width; - - sizes[INPUT][1] = cvSize(0,0); - b_size = cvSize(m,m); - if( have_b ) - { - sizes[INPUT][1].height = sizes[INPUT][0].height; - sizes[INPUT][1].width = cvTsRandInt(rng) % 100 + 1; - b_size = sizes[INPUT][1]; - } - - if( compact ) - sizes[TEMP][0] = cvSize(min_size, min_size); - else - sizes[TEMP][0] = sizes[INPUT][0]; - - if( vector_w ) - { - if( bits & 256 ) - sizes[TEMP][0] = cvSize(1, min_size); - else - sizes[TEMP][0] = cvSize(min_size, 1); - } - - sizes[TEMP][1] = compact ? cvSize(min_size, m) : cvSize(m, m); - - if( flags & CV_SVD_U_T ) - CV_SWAP( sizes[TEMP][1].width, sizes[TEMP][1].height, i ); - - sizes[TEMP][2] = compact ? cvSize(n, min_size) : cvSize(n, n); - - if( !(flags & CV_SVD_V_T) ) - CV_SWAP( sizes[TEMP][2].width, sizes[TEMP][2].height, i ); - - types[TEMP][0] = types[TEMP][1] = types[TEMP][2] = types[INPUT][0]; - types[OUTPUT][0] = types[REF_OUTPUT][0] = types[INPUT][0]; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize( b_size.width, n ); -} - - -void CxCore_SVBkSbTest::get_timing_test_array_types_and_sizes( int test_case_idx, - CvSize** sizes, int** types, - CvSize** whole_sizes, bool* are_images ) -{ - CxCore_MatrixTest::get_timing_test_array_types_and_sizes( test_case_idx, - sizes, types, whole_sizes, are_images ); - have_b = true; - vector_w = true; - compact = true; - sizes[TEMP][0] = cvSize(1,sizes[INPUT][0].height); - sizes[INPUT][1] = sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(1,sizes[INPUT][0].height); - flags = CV_SVD_U_T + CV_SVD_V_T; -} - - -int CxCore_SVBkSbTest::prepare_test_case( int test_case_idx ) -{ - int code = CxCore_MatrixTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - CvMat* input = &test_mat[INPUT][0]; - cvTsFloodWithZeros( input, ts->get_rng() ); - - if( symmetric ) - { - CvMat* temp = &test_mat[TEMP][1]; - cvTsGEMM( input, input, 1., 0, 0., temp, CV_GEMM_B_T ); - cvTsCopy( temp, input ); - } - - cvSVD( input, test_array[TEMP][0], test_array[TEMP][1], test_array[TEMP][2], flags ); - } - - return code; -} - - -void CxCore_SVBkSbTest::get_minmax_bounds( int /*i*/, int /*j*/, int /*type*/, CvScalar* low, CvScalar* high ) -{ - *low = cvScalarAll(-2.); - *high = cvScalarAll(2.); -} - - -double CxCore_SVBkSbTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return CV_MAT_DEPTH(cvGetElemType(test_array[INPUT][0])) == CV_32F ? 1e-3 : 1e-7; -} - - -void CxCore_SVBkSbTest::run_func() -{ - cvSVBkSb( test_array[TEMP][0], test_array[TEMP][1], test_array[TEMP][2], - test_array[INPUT][1], test_array[OUTPUT][0], flags ); -} - - -void CxCore_SVBkSbTest::prepare_to_validation( int ) -{ - CvMat* input = &test_mat[INPUT][0]; - int i, m = input->rows, n = input->cols, min_size = MIN(m, n), nb; - bool is_float = CV_MAT_DEPTH(input->type) == CV_32F; - CvSize w_size = compact ? cvSize(min_size,min_size) : cvSize(m,n); - CvMat* w = &test_mat[TEMP][0]; - CvMat* wdb = cvCreateMat( w_size.height, w_size.width, CV_64FC1 ); - // use exactly the same threshold as in icvSVD... , - // so the changes in the library and here should be synchronized. - double threshold = cvSum( w ).val[0]*2*(is_float ? FLT_EPSILON : DBL_EPSILON); - CvMat *u, *v, *b, *t0, *t1; - - cvTsZero(wdb); - for( i = 0; i < min_size; i++ ) - { - double wii = vector_w ? cvGetReal1D(w,i) : cvGetReal2D(w,i,i); - cvSetReal2D( wdb, i, i, wii > threshold ? 1./wii : 0. ); - } - - u = &test_mat[TEMP][1]; - v = &test_mat[TEMP][2]; - b = 0; - nb = m; - - if( test_array[INPUT][1] ) - { - b = &test_mat[INPUT][1]; - nb = b->cols; - } - - if( is_float ) - { - u = cvCreateMat( u->rows, u->cols, CV_64F ); - cvTsConvert( &test_mat[TEMP][1], u ); - if( b ) - { - b = cvCreateMat( b->rows, b->cols, CV_64F ); - cvTsConvert( &test_mat[INPUT][1], b ); - } - } - - t0 = cvCreateMat( wdb->cols, nb, CV_64F ); - - if( b ) - cvTsGEMM( u, b, 1., 0, 0., t0, !(flags & CV_SVD_U_T) ? CV_GEMM_A_T : 0 ); - else if( flags & CV_SVD_U_T ) - cvTsCopy( u, t0 ); - else - cvTsTranspose( u, t0 ); - - if( is_float ) - { - cvReleaseMat( &b ); - - if( !symmetric ) - { - cvReleaseMat( &u ); - v = cvCreateMat( v->rows, v->cols, CV_64F ); - } - else - { - v = u; - u = 0; - } - cvTsConvert( &test_mat[TEMP][2], v ); - } - - t1 = cvCreateMat( wdb->rows, nb, CV_64F ); - cvTsGEMM( wdb, t0, 1, 0, 0, t1, 0 ); - - if( !is_float || !symmetric ) - { - cvReleaseMat( &t0 ); - t0 = !is_float ? &test_mat[REF_OUTPUT][0] : cvCreateMat( test_mat[REF_OUTPUT][0].rows, nb, CV_64F ); - } - - cvTsGEMM( v, t1, 1, 0, 0, t0, flags & CV_SVD_V_T ? CV_GEMM_A_T : 0 ); - cvReleaseMat( &t1 ); - - if( t0 != &test_mat[REF_OUTPUT][0] ) - { - cvTsConvert( t0, &test_mat[REF_OUTPUT][0] ); - cvReleaseMat( &t0 ); - } - - if( v != &test_mat[TEMP][2] ) - cvReleaseMat( &v ); - - cvReleaseMat( &wdb ); -} - - -CxCore_SVBkSbTest svbksb_test; - - -// TODO: eigenvv, invsqrt, cbrt, fastarctan, (round, floor, ceil(?)), - -/* End of file. */ - diff --git a/tests/cxcore/src/apca.cpp b/tests/cxcore/src/apca.cpp deleted file mode 100644 index 1299363..0000000 --- a/tests/cxcore/src/apca.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" - -using namespace cv; - -#define CHECK_C - -Size sz( 200, 500); - -class CV_PCATest : public CvTest -{ -public: - CV_PCATest() : CvTest( "pca", "PCA funcs" ) {} -protected: - void run( int); -}; - -#if 0 - -void CV_PCATest::run( int ) -{ - int code = CvTS::OK, err; - int maxComponents = 1; - Mat points( 1000, 3, CV_32FC1); - - RNG rng = *ts->get_rng(); // get ts->rng seed - rng.fill( points, RNG::NORMAL, Scalar::all(0.0), Scalar::all(1.0) ); - - float mp[] = { 3.0f, 3.0f, 3.0f }, cp[] = { 0.5f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.3f }; - Mat mean( 1, 3, CV_32FC1, mp ), - cov( 3, 3, CV_32FC1, cp ); - for( int i = 0; i < points.rows; i++ ) - { - Mat r(1, points.cols, CV_32FC1, points.ptr(i)); - r = r * cov + mean; - } - - PCA pca( points, Mat(), CV_PCA_DATA_AS_ROW, maxComponents ); - - // check project - Mat prjPoints = pca.project( points ); - err = 0; - for( int i = 0; i < prjPoints.rows; i++ ) - { - float val = prjPoints.at(i,0); - if( val > 3.0f || val < -3.0f ) - err++; - } - float projectErr = 0.02f; - if( (float)err > prjPoints.rows * projectErr ) - { - ts->printf( CvTS::LOG, "bad accuracy of project() (real = %f, permissible = %f)", - (float)err/(float)prjPoints.rows, projectErr ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // check backProject - Mat points1 = pca.backProject( prjPoints ); - err = 0; - for( int i = 0; i < points.rows; i++ ) - { - if( fabs(points1.at(i,0) - mean.at(0,0)) > 0.15 || - fabs(points1.at(i,1) - points.at(i,1)) > 0.05 || - fabs(points1.at(i,2) - mean.at(0,2)) > 0.15 ) - err++; - } - float backProjectErr = 0.05f; - if( (float)err > prjPoints.rows*backProjectErr ) - { - ts->printf( CvTS::LOG, "bad accuracy of backProject() (real = %f, permissible = %f)", - (float)err/(float)prjPoints.rows, backProjectErr ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - CvRNG *oldRng = ts->get_rng(); // set ts->rng seed - *oldRng = rng.state; - - ts->set_failed_test_info( code ); -} -#else -void CV_PCATest::run( int ) -{ - int code = CvTS::OK; - - double diffPrjEps, diffBackPrjEps, - prjEps, backPrjEps, - evalEps, evecEps; - int maxComponents = 100; - Mat rPoints(sz, CV_32FC1), rTestPoints(sz, CV_32FC1); - RNG rng = *ts->get_rng(); - - rng.fill( rPoints, RNG::UNIFORM, Scalar::all(0.0), Scalar::all(1.0) ); - rng.fill( rTestPoints, RNG::UNIFORM, Scalar::all(0.0), Scalar::all(1.0) ); - - PCA rPCA( rPoints, Mat(), CV_PCA_DATA_AS_ROW, maxComponents ), cPCA; - - // 1. check C++ PCA & ROW - Mat rPrjTestPoints = rPCA.project( rTestPoints ); - Mat rBackPrjTestPoints = rPCA.backProject( rPrjTestPoints ); - - Mat avg(1, sz.width, CV_32FC1 ); - reduce( rPoints, avg, 0, CV_REDUCE_AVG ); - Mat Q = rPoints - repeat( avg, rPoints.rows, 1 ), Qt = Q.t(), eval, evec; - Q = Qt * Q; - Q = Q /(float)rPoints.rows; - - eigen( Q, eval, evec ); - /*SVD svd(Q); - evec = svd.vt; - eval = svd.w;*/ - - Mat subEval( maxComponents, 1, eval.type(), eval.data ), - subEvec( maxComponents, evec.cols, evec.type(), evec.data ); - -#ifdef CHECK_C - Mat prjTestPoints, backPrjTestPoints, cPoints = rPoints.t(), cTestPoints = rTestPoints.t(); - CvMat _points, _testPoints, _avg, _eval, _evec, _prjTestPoints, _backPrjTestPoints; -#endif - - // check eigen() - double eigenEps = 1e-6; - double err; - for(int i = 0; i < Q.rows; i++ ) - { - Mat v = evec.row(i).t(); - Mat Qv = Q * v; - - Mat lv = eval.at(i,0) * v; - err = norm( Qv, lv ); - if( err > eigenEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of eigen(); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - } - // check pca eigenvalues - evalEps = 1e-6, evecEps = 1; - err = norm( rPCA.eigenvalues, subEval ); - if( err > evalEps ) - { - ts->printf( CvTS::LOG, "pca.eigenvalues is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - // check pca eigenvectors - err = norm( rPCA.eigenvectors, subEvec, CV_RELATIVE_L2 ); - if( err > evecEps ) - { - ts->printf( CvTS::LOG, "pca.eigenvectors is incorrect (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - - prjEps = 1.265, backPrjEps = 1.265; - for( int i = 0; i < rTestPoints.rows; i++ ) - { - // check pca project - Mat subEvec_t = subEvec.t(); - Mat prj = rTestPoints.row(i) - avg; prj *= subEvec_t; - err = norm(rPrjTestPoints.row(i), prj, CV_RELATIVE_L2); - if( err > prjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - // check pca backProject - Mat backPrj = rPrjTestPoints.row(i) * subEvec + avg; - err = norm( rBackPrjTestPoints.row(i), backPrj, CV_RELATIVE_L2 ); - if( err > backPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - } - - // 2. check C++ PCA & COL - cPCA( rPoints.t(), Mat(), CV_PCA_DATA_AS_COL, maxComponents ); - diffPrjEps = 1, diffBackPrjEps = 1; - err = norm(cPCA.project(rTestPoints.t()), rPrjTestPoints.t(), CV_RELATIVE_L2 ); - if( err > diffPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of project() (CV_PCA_DATA_AS_COL); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - err = norm(cPCA.backProject(rPrjTestPoints.t()), rBackPrjTestPoints.t(), CV_RELATIVE_L2 ); - if( err > diffBackPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of backProject() (CV_PCA_DATA_AS_COL); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - -#ifdef CHECK_C - // 3. check C PCA & ROW - _points = rPoints; - _testPoints = rTestPoints; - _avg = avg; - _eval = eval; - _evec = evec; - prjTestPoints.create(rTestPoints.rows, maxComponents, rTestPoints.type() ); - backPrjTestPoints.create(rPoints.size(), rPoints.type() ); - _prjTestPoints = prjTestPoints; - _backPrjTestPoints = backPrjTestPoints; - - cvCalcPCA( &_points, &_avg, &_eval, &_evec, CV_PCA_DATA_AS_ROW ); - cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints ); - cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints ); - - err = norm(prjTestPoints, rPrjTestPoints, CV_RELATIVE_L2); - if( err > diffPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - err = norm(backPrjTestPoints, rBackPrjTestPoints, CV_RELATIVE_L2); - if( err > diffBackPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_ROW); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - - // 3. check C PCA & COL - _points = cPoints; - _testPoints = cTestPoints; - avg = avg.t(); _avg = avg; - eval = eval.t(); _eval = eval; - evec = evec.t(); _evec = evec; - prjTestPoints = prjTestPoints.t(); _prjTestPoints = prjTestPoints; - backPrjTestPoints = backPrjTestPoints.t(); _backPrjTestPoints = backPrjTestPoints; - - cvCalcPCA( &_points, &_avg, &_eval, &_evec, CV_PCA_DATA_AS_COL ); - cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints ); - cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints ); - - err = norm(prjTestPoints, rPrjTestPoints.t(), CV_RELATIVE_L2 ); - if( err > diffPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } - err = norm(backPrjTestPoints, rBackPrjTestPoints.t(), CV_RELATIVE_L2); - if( err > diffBackPrjEps ) - { - ts->printf( CvTS::LOG, "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_COL); err = %f\n", err ); - code = CvTS::FAIL_BAD_ACCURACY; - goto exit_func; - } -#endif - -exit_func: - - CvRNG* _rng = ts->get_rng(); - *_rng = rng.state; - ts->set_failed_test_info( code ); -} - -#endif - -CV_PCATest pca_test; diff --git a/tests/cxcore/src/arand.cpp b/tests/cxcore/src/arand.cpp deleted file mode 100644 index 9ffe764..0000000 --- a/tests/cxcore/src/arand.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" - -using namespace cv; - - -class CV_RandTest : public CvTest -{ -public: - CV_RandTest(); -protected: - void run(int); - bool check_pdf(const Mat& hist, double scale, int dist_type, - double& refval, double& realval); -}; - - -CV_RandTest::CV_RandTest(): -CvTest( "rand", "cvRandArr, cvRNG" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -static double chi2_p95(int n) -{ - static float chi2_tab95[] = { - 3.841f, 5.991f, 7.815f, 9.488f, 11.07f, 12.59f, 14.07f, 15.51f, - 16.92f, 18.31f, 19.68f, 21.03f, 21.03f, 22.36f, 23.69f, 25.00f, - 26.30f, 27.59f, 28.87f, 30.14f, 31.41f, 32.67f, 33.92f, 35.17f, - 36.42f, 37.65f, 38.89f, 40.11f, 41.34f, 42.56f, 43.77f }; - static const double xp = 1.64; - CV_Assert(n >= 1); - - if( n <= 30 ) - return chi2_tab95[n-1]; - return n + sqrt((double)2*n)*xp + 0.6666666666666*(xp*xp - 1); -} - -bool CV_RandTest::check_pdf(const Mat& hist, double scale, - int dist_type, double& refval, double& realval) -{ - Mat hist0(hist.size(), CV_32F); - const int* H = (const int*)hist.data; - float* H0 = ((float*)hist0.data); - int i, hsz = hist.cols; - - double sum = 0; - for( i = 0; i < hsz; i++ ) - sum += H[i]; - CV_Assert( fabs(1./sum - scale) < FLT_EPSILON ); - - if( dist_type == CV_RAND_UNI ) - { - float scale0 = (float)(1./hsz); - for( i = 0; i < hsz; i++ ) - H0[i] = scale0; - } - else - { - double sum = 0, r = (hsz-1.)/2; - double alpha = 2*sqrt(2.)/r, beta = -alpha*r; - for( i = 0; i < hsz; i++ ) - { - double x = i*alpha + beta; - H0[i] = (float)exp(-x*x); - sum += H0[i]; - } - sum = 1./sum; - for( i = 0; i < hsz; i++ ) - H0[i] = (float)(H0[i]*sum); - } - - double chi2 = 0; - for( i = 0; i < hsz; i++ ) - { - double a = H0[i]; - double b = H[i]*scale; - if( a > DBL_EPSILON ) - chi2 += (a - b)*(a - b)/(a + b); - } - realval = chi2; - - double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0)); - refval = chi2_pval*0.01; - return realval <= refval; -} - -void CV_RandTest::run( int ) -{ - static int _ranges[][2] = - {{ 0, 256 }, { -128, 128 }, { 0, 65536 }, { -32768, 32768 }, - { -1000000, 1000000 }, { -1000, 1000 }, { -1000, 1000 }}; - - const int MAX_SDIM = 10; - const int N = 2000000; - const int maxSlice = 1000; - const int MAX_HIST_SIZE = 1000; - int progress = 0; - - CvRNG* rng = ts->get_rng(); - RNG tested_rng = theRNG(); - test_case_count = 200; - - for( int idx = 0; idx < test_case_count; idx++ ) - { - progress = update_progress( progress, idx, test_case_count, 0 ); - ts->update_context( this, idx, false ); - - int depth = cvTsRandInt(rng) % (CV_64F+1); - int c, cn = (cvTsRandInt(rng) % 4) + 1; - int type = CV_MAKETYPE(depth, cn); - int dist_type = cvTsRandInt(rng) % (CV_RAND_NORMAL+1); - int i, k, SZ = N/cn; - Scalar A, B; - - bool do_sphere_test = dist_type == CV_RAND_UNI; - Mat arr[2], hist[4]; - int W[] = {0,0,0,0}; - - arr[0].create(1, SZ, type); - arr[1].create(1, SZ, type); - bool fast_algo = dist_type == CV_RAND_UNI && depth < CV_32F; - - for( c = 0; c < cn; c++ ) - { - int a, b, hsz; - if( dist_type == CV_RAND_UNI ) - { - a = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - - _ranges[depth][0])) + _ranges[depth][0]; - do - { - b = (int)(cvTsRandInt(rng) % (_ranges[depth][1] - - _ranges[depth][0])) + _ranges[depth][0]; - } - while( abs(a-b) <= 1 ); - if( a > b ) - std::swap(a, b); - - unsigned r = (unsigned)(b - a); - fast_algo = fast_algo && r <= 256 && (r & (r-1)) == 0; - hsz = min((unsigned)(b - a), (unsigned)MAX_HIST_SIZE); - do_sphere_test = do_sphere_test && b - a >= 100; - } - else - { - int vrange = _ranges[depth][1] - _ranges[depth][0]; - int meanrange = vrange/16; - int mindiv = MAX(vrange/20, 5); - int maxdiv = MIN(vrange/8, 10000); - - a = cvTsRandInt(rng) % meanrange - meanrange/2 + - (_ranges[depth][0] + _ranges[depth][1])/2; - b = cvTsRandInt(rng) % (maxdiv - mindiv) + mindiv; - hsz = min((unsigned)b*9, (unsigned)MAX_HIST_SIZE); - } - A[c] = a; - B[c] = b; - hist[c].create(1, hsz, CV_32S); - } - - cv::RNG saved_rng = tested_rng; - int maxk = fast_algo ? 0 : 1; - for( k = 0; k <= maxk; k++ ) - { - tested_rng = saved_rng; - int sz = 0, dsz = 0, slice; - for( slice = 0; slice < maxSlice; slice++, sz += dsz ) - { - dsz = slice+1 < maxSlice ? cvTsRandInt(rng) % (SZ - sz + 1) : SZ - sz; - Mat aslice = arr[k].colRange(sz, sz + dsz); - tested_rng.fill(aslice, dist_type, A, B); - } - } - - if( maxk >= 1 && norm(arr[0], arr[1], NORM_INF) != 0 ) - { - ts->printf( CvTS::LOG, "RNG output depends on the array lengths (some generated numbers get lost?)" ); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - - for( c = 0; c < cn; c++ ) - { - const uchar* data = arr[0].data; - int* H = hist[c].ptr(); - int HSZ = hist[c].cols; - double minVal = dist_type == CV_RAND_UNI ? A[c] : A[c] - B[c]*4; - double maxVal = dist_type == CV_RAND_UNI ? B[c] : A[c] + B[c]*4; - double scale = HSZ/(maxVal - minVal); - double delta = -minVal*scale; - - hist[c] = Scalar::all(0); - - for( i = c; i < SZ*cn; i += cn ) - { - double val = depth == CV_8U ? ((const uchar*)data)[i] : - depth == CV_8S ? ((const schar*)data)[i] : - depth == CV_16U ? ((const ushort*)data)[i] : - depth == CV_16S ? ((const short*)data)[i] : - depth == CV_32S ? ((const int*)data)[i] : - depth == CV_32F ? ((const float*)data)[i] : - ((const double*)data)[i]; - int ival = cvFloor(val*scale + delta); - if( (unsigned)ival < (unsigned)HSZ ) - { - H[ival]++; - W[c]++; - } - else if( dist_type == CV_RAND_UNI ) - { - if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) ) - { - H[ival < 0 ? 0 : HSZ-1]++; - W[c]++; - } - else - { - putchar('^'); - } - } - } - - if( dist_type == CV_RAND_UNI && W[c] != SZ ) - { - ts->printf( CvTS::LOG, "Uniform RNG gave values out of the range [%g,%g) on channel %d/%d\n", - A[c], B[c], c, cn); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90) - { - ts->printf( CvTS::LOG, "Normal RNG gave too many values out of the range (%g+4*%g,%g+4*%g) on channel %d/%d\n", - A[c], B[c], A[c], B[c], c, cn); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - double refval = 0, realval = 0; - - if( !check_pdf(hist[c], 1./W[c], dist_type, refval, realval) ) - { - ts->printf( CvTS::LOG, "RNG failed Chi-square test " - "(got %g vs probable maximum %g) on channel %d/%d\n", - realval, refval, c, cn); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - } - - // Monte-Carlo test. Compute volume of SDIM-dimensional sphere - // inscribed in [-1,1]^SDIM cube. - if( do_sphere_test ) - { - int SDIM = cvTsRandInt(rng) % (MAX_SDIM-1) + 2; - int N0 = (SZ*cn/SDIM), N = 0; - double r2 = 0; - const uchar* data = arr[0].data; - double scale[4], delta[4]; - for( c = 0; c < cn; c++ ) - { - scale[c] = 2./(B[c] - A[c]); - delta[c] = -A[c]*scale[c] - 1; - } - - for( i = k = c = 0; i <= SZ*cn - SDIM; i++, k++, c++ ) - { - double val = depth == CV_8U ? ((const uchar*)data)[i] : - depth == CV_8S ? ((const schar*)data)[i] : - depth == CV_16U ? ((const ushort*)data)[i] : - depth == CV_16S ? ((const short*)data)[i] : - depth == CV_32S ? ((const int*)data)[i] : - depth == CV_32F ? ((const float*)data)[i] : ((const double*)data)[i]; - c &= c < cn ? -1 : 0; - val = val*scale[c] + delta[c]; - r2 += val*val; - if( k == SDIM-1 ) - { - N += r2 <= 1; - r2 = 0; - k = -1; - } - } - - double V = ((double)N/N0)*(1 << SDIM); - - // the theoretically computed volume - int sdim = SDIM % 2; - double V0 = sdim + 1; - for( sdim += 2; sdim <= SDIM; sdim += 2 ) - V0 *= 2*CV_PI/sdim; - - if( fabs(V - V0) > 0.3*fabs(V0) ) - { - ts->printf( CvTS::LOG, "RNG failed %d-dim sphere volume test (got %g instead of %g)\n", - SDIM, V, V0); - ts->printf( CvTS::LOG, "depth = %d, N0 = %d\n", depth, N0); - ts->set_failed_test_info( CvTS::FAIL_INVALID_OUTPUT ); - return; - } - } - } -} - -CV_RandTest rand_test; diff --git a/tests/cxcore/src/areduce.cpp b/tests/cxcore/src/areduce.cpp deleted file mode 100644 index c29ec50..0000000 --- a/tests/cxcore/src/areduce.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" - -using namespace cv; - - -class CV_ReduceTest : public CvTest -{ -public: - CV_ReduceTest() : CvTest( "reduce", "reduce" ) {} -protected: - void run( int); - int checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim, double eps ); - int checkCase( int srcType, int dstType, int dim, Size sz ); - int checkDim( int dim, Size sz ); - int checkSize( Size sz ); -}; - -template -void testReduce( const Mat& src, Mat& sum, Mat& avg, Mat& max, Mat& min, int dim ) -{ - assert( src.channels() == 1 ); - if( dim == 0 ) // row - { - sum.create( 1, src.cols, CV_64FC1 ); - max.create( 1, src.cols, CV_64FC1 ); - min.create( 1, src.cols, CV_64FC1 ); - } - else - { - sum.create( src.rows, 1, CV_64FC1 ); - max.create( src.rows, 1, CV_64FC1 ); - min.create( src.rows, 1, CV_64FC1 ); - } - sum.setTo(Scalar(0)); - max.setTo(Scalar(-DBL_MAX)); - min.setTo(Scalar(DBL_MAX)); - - const Mat_& src_ = src; - Mat_& sum_ = (Mat_&)sum; - Mat_& min_ = (Mat_&)min; - Mat_& max_ = (Mat_&)max; - - if( dim == 0 ) - { - for( int ri = 0; ri < src.rows; ri++ ) - { - for( int ci = 0; ci < src.cols; ci++ ) - { - sum_(0, ci) += src_(ri, ci); - max_(0, ci) = std::max( max_(0, ci), (double)src_(ri, ci) ); - min_(0, ci) = std::min( min_(0, ci), (double)src_(ri, ci) ); - } - } - } - else - { - for( int ci = 0; ci < src.cols; ci++ ) - { - for( int ri = 0; ri < src.rows; ri++ ) - { - sum_(ri, 0) += src_(ri, ci); - max_(ri, 0) = std::max( max_(ri, 0), (double)src_(ri, ci) ); - min_(ri, 0) = std::min( min_(ri, 0), (double)src_(ri, ci) ); - } - } - } - sum.convertTo( avg, CV_64FC1 ); - avg = avg * (1.0 / (dim==0 ? (double)src.rows : (double)src.cols)); -} - -void getMatTypeStr( int type, string& str) -{ - str = type == CV_8UC1 ? "CV_8UC1" : - type == CV_8SC1 ? "CV_8SC1" : - type == CV_16UC1 ? "CV_16UC1" : - type == CV_16SC1 ? "CV_16SC1" : - type == CV_32SC1 ? "CV_32SC1" : - type == CV_32FC1 ? "CV_32FC1" : - type == CV_64FC1 ? "CV_64FC1" : "unsupported matrix type"; -} - -int CV_ReduceTest::checkOp( const Mat& src, int dstType, int opType, const Mat& opRes, int dim, double eps ) -{ - int srcType = src.type(); - bool support = false; - if( opType == CV_REDUCE_SUM || opType == CV_REDUCE_AVG ) - { - if( srcType == CV_8U && (dstType == CV_32S || dstType == CV_32F || dstType == CV_64F) ) - support = true; - if( srcType == CV_16U && (dstType == CV_32F || dstType == CV_64F) ) - support = true; - if( srcType == CV_16S && (dstType == CV_32F || dstType == CV_64F) ) - support = true; - if( srcType == CV_32F && (dstType == CV_32F || dstType == CV_64F) ) - support = true; - if( srcType == CV_64F && dstType == CV_64F) - support = true; - } - else if( opType == CV_REDUCE_MAX ) - { - if( srcType == CV_8U && dstType == CV_8U ) - support = true; - if( srcType == CV_32F && dstType == CV_32F ) - support = true; - if( srcType == CV_64F && dstType == CV_64F ) - support = true; - } - else if( opType == CV_REDUCE_MIN ) - { - if( srcType == CV_8U && dstType == CV_8U) - support = true; - if( srcType == CV_32F && dstType == CV_32F) - support = true; - if( srcType == CV_64F && dstType == CV_64F) - support = true; - } - if( !support ) - return CvTS::OK; - - assert( opRes.type() == CV_64FC1 ); - Mat _dst, dst; - reduce( src, _dst, dim, opType, dstType ); - _dst.convertTo( dst, CV_64FC1 ); - if( norm( opRes, dst, NORM_INF ) > eps ) - { - char msg[100]; - const char* opTypeStr = opType == CV_REDUCE_SUM ? "CV_REDUCE_SUM" : - opType == CV_REDUCE_AVG ? "CV_REDUCE_AVG" : - opType == CV_REDUCE_MAX ? "CV_REDUCE_MAX" : - opType == CV_REDUCE_MIN ? "CV_REDUCE_MIN" : "unknown operation type"; - string srcTypeStr, dstTypeStr; - getMatTypeStr( src.type(), srcTypeStr ); - getMatTypeStr( dstType, dstTypeStr ); - const char* dimStr = dim == 0 ? "ROWS" : "COLS"; - - sprintf( msg, "bad accuracy with srcType = %s, dstType = %s, opType = %s, dim = %s", - srcTypeStr.c_str(), dstTypeStr.c_str(), opTypeStr, dimStr ); - ts->printf( CvTS::LOG, msg ); - return CvTS::FAIL_BAD_ACCURACY; - } - return CvTS::OK; -} - -int CV_ReduceTest::checkCase( int srcType, int dstType, int dim, Size sz ) -{ - int code = CvTS::OK, tempCode; - Mat src, sum, avg, max, min; - - src.create( sz, srcType ); - randu( src, Scalar(0), Scalar(100) ); - - if( srcType == CV_8UC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_8SC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_16UC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_16SC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_32SC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_32FC1 ) - testReduce( src, sum, avg, max, min, dim ); - else if( srcType == CV_64FC1 ) - testReduce( src, sum, avg, max, min, dim ); - else - assert( 0 ); - - // 1. sum - tempCode = checkOp( src, dstType, CV_REDUCE_SUM, sum, dim, - srcType == CV_32FC1 && dstType == CV_32FC1 ? 0.05 : FLT_EPSILON ); - code = tempCode != CvTS::OK ? tempCode : code; - - // 2. avg - tempCode = checkOp( src, dstType, CV_REDUCE_AVG, avg, dim, - dstType == CV_32SC1 ? 0.6 : 0.00007 ); - code = tempCode != CvTS::OK ? tempCode : code; - - // 3. max - tempCode = checkOp( src, dstType, CV_REDUCE_MAX, max, dim, FLT_EPSILON ); - code = tempCode != CvTS::OK ? tempCode : code; - - // 4. min - tempCode = checkOp( src, dstType, CV_REDUCE_MIN, min, dim, FLT_EPSILON ); - code = tempCode != CvTS::OK ? tempCode : code; - - return code; -} - -int CV_ReduceTest::checkDim( int dim, Size sz ) -{ - int code = CvTS::OK, tempCode; - - // CV_8UC1 - tempCode = checkCase( CV_8UC1, CV_8UC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_8UC1, CV_32SC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_8UC1, CV_32FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_8UC1, CV_64FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - // CV_16UC1 - tempCode = checkCase( CV_16UC1, CV_32FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_16UC1, CV_64FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - // CV_16SC1 - tempCode = checkCase( CV_16SC1, CV_32FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_16SC1, CV_64FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - // CV_32FC1 - tempCode = checkCase( CV_32FC1, CV_32FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkCase( CV_32FC1, CV_64FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - // CV_64FC1 - tempCode = checkCase( CV_64FC1, CV_64FC1, dim, sz ); - code = tempCode != CvTS::OK ? tempCode : code; - - return code; -} - -int CV_ReduceTest::checkSize( Size sz ) -{ - int code = CvTS::OK, tempCode; - - tempCode = checkDim( 0, sz ); // rows - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkDim( 1, sz ); // cols - code = tempCode != CvTS::OK ? tempCode : code; - - return code; -} - -void CV_ReduceTest::run( int ) -{ - int code = CvTS::OK, tempCode; - - tempCode = checkSize( Size(1,1) ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkSize( Size(1,100) ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkSize( Size(100,1) ); - code = tempCode != CvTS::OK ? tempCode : code; - - tempCode = checkSize( Size(1000,500) ); - code = tempCode != CvTS::OK ? tempCode : code; - - ts->set_failed_test_info( code ); -} - -CV_ReduceTest reduce_test; diff --git a/tests/cxcore/src/asolvepoly.cpp b/tests/cxcore/src/asolvepoly.cpp deleted file mode 100644 index b8f9c6d..0000000 --- a/tests/cxcore/src/asolvepoly.cpp +++ /dev/null @@ -1,168 +0,0 @@ -// 2008-05-14, Xavier Delacour - -#include "cxcoretest.h" - -#include -#include -#include -#include - -typedef std::complex complex_type; - -struct pred_complex -{ - bool operator() (const complex_type& lhs, const complex_type& rhs) const - { - return fabs(lhs.real() - rhs.real()) > fabs(rhs.real())*FLT_EPSILON ? lhs.real() < rhs.real() : lhs.imag() < rhs.imag(); - } -}; - -struct pred_double -{ - bool operator() (const double& lhs, const double& rhs) const - { - return lhs < rhs; - } -}; - -class CV_SolvePolyTest : public CvTest -{ -public: - CV_SolvePolyTest(); - ~CV_SolvePolyTest(); -protected: - virtual void run( int start_from ); -}; - -CV_SolvePolyTest::CV_SolvePolyTest() : CvTest( "solve-poly", "cvSolvePoly" ) {} - -CV_SolvePolyTest::~CV_SolvePolyTest() {} - -void CV_SolvePolyTest::run( int ) -{ - CvRNG rng = cvRNG(); - int fig = 100; - double range = 50; - double err_eps = 1e-4; - - for (int idx = 0, max_idx = 1000, progress = 0; idx < max_idx; ++idx) - { - progress = update_progress(progress, idx-1, max_idx, 0); - int n = cvRandInt(&rng) % 13 + 1; - std::vector r(n), ar(n), c(n + 1, 0); - std::vector a(n + 1), u(n * 2), ar1(n), ar2(n); - - int rr_odds = 3; // odds that we get a real root - for (int j = 0; j < n;) - { - if (cvRandInt(&rng) % rr_odds == 0 || j == n - 1) - r[j++] = cvRandReal(&rng) * range; - else - { - r[j] = complex_type(cvRandReal(&rng) * range, - cvRandReal(&rng) * range + 1); - r[j + 1] = std::conj(r[j]); - j += 2; - } - } - - for (int j = 0, k = 1 << n, jj, kk; j < k; ++j) - { - int p = 0; - complex_type v(1); - for (jj = 0, kk = 1; jj < n && !(j & kk); ++jj, ++p, kk <<= 1) - ; - for (; jj < n; ++jj, kk <<= 1) - { - if (j & kk) - v *= -r[jj]; - else - ++p; - } - c[p] += v; - } - - bool pass = false; - double div = 0, s = 0; - int cubic_case = idx & 1; - for (int maxiter = 100; !pass && maxiter < 10000; maxiter *= 2, cubic_case = (cubic_case + 1) % 2) - { - for (int j = 0; j < n + 1; ++j) - a[j] = c[j].real(); - - CvMat amat, umat; - cvInitMatHeader(&amat, n + 1, 1, CV_64FC1, &a[0]); - cvInitMatHeader(&umat, n, 1, CV_64FC2, &u[0]); - cvSolvePoly(&amat, &umat, maxiter, fig); - - for (int j = 0; j < n; ++j) - ar[j] = complex_type(u[j * 2], u[j * 2 + 1]); - - std::sort(r.begin(), r.end(), pred_complex()); - std::sort(ar.begin(), ar.end(), pred_complex()); - - pass = true; - if( n == 3 ) - { - ar2.resize(n); - cv::Mat _umat2(3, 1, CV_64F, &ar2[0]), umat2 = _umat2; - cvFlip(&amat, &amat, 0); - int nr2; - if( cubic_case == 0 ) - nr2 = cv::solveCubic(cv::Mat(&amat),umat2); - else - nr2 = cv::solveCubic(cv::Mat_(cv::Mat(&amat)), umat2); - cvFlip(&amat, &amat, 0); - if(nr2 > 0) - std::sort(ar2.begin(), ar2.begin()+nr2, pred_double()); - ar2.resize(nr2); - - int nr1 = 0; - for(int j = 0; j < n; j++) - if( fabs(r[j].imag()) < DBL_EPSILON ) - ar1[nr1++] = r[j].real(); - - pass = pass && nr1 == nr2; - if( nr2 > 0 ) - { - div = s = 0; - for(int j = 0; j < nr1; j++) - { - s += fabs(ar1[j]); - div += fabs(ar1[j] - ar2[j]); - } - div /= s; - pass = pass && div < err_eps; - } - } - - div = s = 0; - for (int j = 0; j < n; ++j) - { - s += fabs(r[j].real()) + fabs(r[j].imag()); - div += sqrt(pow(r[j].real() - ar[j].real(), 2) + pow(r[j].imag() - ar[j].imag(), 2)); - } - div /= s; - pass = pass && div < err_eps; - } - - if (!pass) - { - ts->set_failed_test_info(CvTS::FAIL_INVALID_OUTPUT); - ts->printf( CvTS::LOG, "too big diff = %g\n", div ); - - for (size_t j=0;jprintf( CvTS::LOG, "ar2[%d]=%g\n", j, ar2[j]); - ts->printf(CvTS::LOG, "\n"); - - for (size_t j=0;jprintf( CvTS::LOG, "r[%d]=(%g, %g)\n", j, r[j].real(), r[j].imag()); - ts->printf( CvTS::LOG, "\n" ); - for (size_t j=0;jprintf( CvTS::LOG, "ar[%d]=(%g, %g)\n", j, ar[j].real(), ar[j].imag()); - break; - } - } -} - -CV_SolvePolyTest solve_poly_test; diff --git a/tests/cxcore/src/cxcoretest.h b/tests/cxcore/src/cxcoretest.h deleted file mode 100644 index a526ef7..0000000 --- a/tests/cxcore/src/cxcoretest.h +++ /dev/null @@ -1,68 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef _CXCORE_TEST_H_ -#define _CXCORE_TEST_H_ - -#if defined WIN32 || defined _WIN32 -#include -#undef min -#undef max -#endif - -#include "opencv2/core/core.hpp" -#include "opencv2/core/internal.hpp" -#include "cxts.h" - -/****************************************************************************************/ -/* Warnings Disabling */ -/****************************************************************************************/ -#if _MSC_VER > 1000 -#pragma warning(disable : 4514) /* unreferenced inline function has been */ - /* removed */ -#pragma warning(disable : 4127) /* conditional expression is constant */ - /* for no warnings in _ASSERT */ -#pragma warning(disable : 4996) /* deprecated function */ -#endif - -#endif /* _CXCORE_TEST_H_ */ - -/* End of file. */ diff --git a/tests/cxcore/src/cxcoretest_main.cpp b/tests/cxcore/src/cxcoretest_main.cpp deleted file mode 100644 index 4b127b8..0000000 --- a/tests/cxcore/src/cxcoretest_main.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" - -CvTS test_system("core"); - -const char* blacklist[] = -{ - //"matrix-dotproduct", //ticket 447 - //"ds-graphscan", //ticket 504 - //"matrix-invert", //ticket 536 - //"pca", //ticket 566 - //"rand", //ticket 449 - 0 -}; - -int main( int argc, char** argv ) -{ - return test_system.run( argc, argv, blacklist ); -} - -/* End of file. */ diff --git a/tests/cxcore/src/matrix_operations.cpp b/tests/cxcore/src/matrix_operations.cpp deleted file mode 100644 index 49327c3..0000000 --- a/tests/cxcore/src/matrix_operations.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" -#include -#include -#include -#include -#include -#include - -using namespace cv; -using namespace std; - -class CV_MatrOpTest : public CvTest -{ -public: - CV_MatrOpTest(); - ~CV_MatrOpTest(); -protected: - void run(int); - - bool TestMat(); - bool TestMatND(); - bool TestSparseMat(); - - - bool checkMatSetError(const Mat& m1, const Mat& m2); -}; - -CV_MatrOpTest::CV_MatrOpTest(): CvTest( "matrix-operations", "?" ) -{ - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} -CV_MatrOpTest::~CV_MatrOpTest() {} - -bool CV_MatrOpTest::checkMatSetError(const Mat& m1, const Mat& m2) -{ - if (norm(m1, m2, NORM_INF) == 0) - return true; - - ts->set_failed_test_info(CvTS::FAIL_MISMATCH); - return false; -} - -bool CV_MatrOpTest::TestMat() -{ - Mat one_3x1(3, 1, CV_32F, Scalar(1.0)); - Mat shi_3x1(3, 1, CV_32F, Scalar(1.2)); - Mat shi_2x1(2, 1, CV_32F, Scalar(-1)); - Scalar shift = Scalar::all(15); - - float data[] = { sqrt(2.f)/2, -sqrt(2.f)/2, 1.f, sqrt(2.f)/2, sqrt(2.f)/2, 10.f }; - Mat rot_2x3(2, 3, CV_32F, data); - - Mat res = rot_2x3 * (one_3x1 + shi_3x1 + shi_3x1 + shi_3x1) - shi_2x1 + shift; - - Mat tmp, res2; - add(one_3x1, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - add(tmp, shi_3x1, tmp); - gemm(rot_2x3, tmp, 1, shi_2x1, -1, res2, 0); - add(res2, Mat(2, 1, CV_32F, shift), res2); - - if (!checkMatSetError(res, res2)) - return false; - - Mat mat4x4(4, 4, CV_32F); - randu(mat4x4, Scalar(0), Scalar(10)); - - Mat roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2))); - Mat roi2 = mat4x4(Range(1, 3), Range(1, 3)); - - if (!checkMatSetError(roi1, roi2)) - return false; - - if (!checkMatSetError(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size())))) - return false; - - - return true; -} - -bool CV_MatrOpTest::TestMatND() -{ - int sizes[] = { 3, 3, 3}; - cv::MatND nd(3, sizes, CV_32F); - - /* MatND res = nd * nd + nd; - MatND res2; - cv::gemm(nd, nd, 1, nd, 1, res2); - - if (!checkMatSetError(res1, res2)) - return false;*/ - - return true; -} - -bool CV_MatrOpTest::TestSparseMat() -{ - int sizes[] = { 10, 10, 10}; - SparseMat mat(sizeof(sizes)/sizeof(sizes[0]), sizes, CV_32F); - - return true; -} - - - -void CV_MatrOpTest::run( int /* start_from */) -{ - if (!TestMat()) - return; - - if (!TestMatND()) - return; - - if (!TestSparseMat()) - return; - - ts->set_failed_test_info(CvTS::OK); -} - -CV_MatrOpTest cv_MatrOp_test; - - diff --git a/tests/cxcore/src/precomp.cpp b/tests/cxcore/src/precomp.cpp deleted file mode 100644 index da9aa5c..0000000 --- a/tests/cxcore/src/precomp.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "cxcoretest.h" diff --git a/tests/cxts/CMakeLists.txt b/tests/cxts/CMakeLists.txt deleted file mode 100644 index 77a9d5a..0000000 --- a/tests/cxts/CMakeLists.txt +++ /dev/null @@ -1,69 +0,0 @@ -# ---------------------------------------------------------------------------- -# CMake file for cxts. See root CMakeLists.txt -# -# ---------------------------------------------------------------------------- -project(opencv_ts) - -file(GLOB lib_srcs "*.cpp") -source_group("Src" FILES ${lib_srcs}) -file(GLOB lib_hdrs "*.h*") -source_group("Include" FILES ${lib_hdrs}) - -include_directories(. - "${CMAKE_SOURCE_DIR}/modules/core/include") - -if(WIN32 AND MSVC) - set(pch_header "_cxts.h") - set(pch_src "precomp.cpp") - list(REMOVE_ITEM lib_srcs ${CMAKE_CURRENT_SOURCE_DIR}/${pch_src}) - set(lib_srcs ${CMAKE_CURRENT_SOURCE_DIR}/${pch_src} ${lib_srcs}) - foreach(src_file ${lib_srcs}) - if(${src_file} MATCHES ${pch_src}) - set_source_files_properties( - ${src_file} - PROPERTIES - COMPILE_FLAGS "/Yc${pch_header}" - ) - else() - set_source_files_properties( - ${src_file} - PROPERTIES - COMPILE_FLAGS "/Yu${pch_header}" - ) - endif() - endforeach() -endif() - -# ---------------------------------------------------------------------------------- -# Define the library target: -# ---------------------------------------------------------------------------------- -set(the_target "opencv_ts") - -add_library(${the_target} ${lib_srcs} ${lib_hdrs}) - -# For dynamic link numbering convenions -set_target_properties(${the_target} PROPERTIES - VERSION ${OPENCV_VERSION} - SOVERSION ${OPENCV_SOVERSION} - OUTPUT_NAME "${the_target}${OPENCV_DLLVERSION}" - ) - -# Additional target properties -set_target_properties(${the_target} PROPERTIES - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/" - DEFINE_SYMBOL "CVAPI_EXPORTS" - ) - -add_dependencies(${the_target} opencv_core) - -# Add the required libraries for linking: -target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} opencv_core) - -if(WIN32) -install(TARGETS ${the_target} - RUNTIME DESTINATION bin COMPONENT main - LIBRARY DESTINATION lib COMPONENT main - ARCHIVE DESTINATION lib COMPONENT main) -endif() diff --git a/tests/cxts/_cxts.h b/tests/cxts/_cxts.h deleted file mode 100644 index 5735664..0000000 --- a/tests/cxts/_cxts.h +++ /dev/null @@ -1,60 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef __CXTS_INTERNAL_H__ -#define __CXTS_INTERNAL_H__ - -#if (defined WIN32 || defined _WIN32) && (_MSC_VER >= 1200 || defined _ICL) -#pragma warning( disable: 4251 4514 4996 ) -#endif - -#include "cxts.h" -#include "opencv2/core/internal.hpp" -#include -#include -#include -#include -#include -#include -#include - -#endif/*__CXTS_INTERNAL_H__*/ - diff --git a/tests/cxts/cxts.cpp b/tests/cxts/cxts.cpp deleted file mode 100644 index 387e6a6..0000000 --- a/tests/cxts/cxts.cpp +++ /dev/null @@ -1,2182 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "_cxts.h" -#include -#include -#include -#include -#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 -#include -#else -#include -#endif - -CvTest* CvTest::first = 0; -CvTest* CvTest::last = 0; -int CvTest::test_count = 0; - -/*****************************************************************************************\ -* Exception and memory handlers * -\*****************************************************************************************/ - -// a few platform-dependent declarations - -#define CV_TS_NORMAL 0 -#define CV_TS_BLUE 1 -#define CV_TS_GREEN 2 -#define CV_TS_RED 4 - -#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 -#include - -#ifdef _MSC_VER -#include -#endif - -#ifdef _MSC_VER -static void cv_seh_translator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp ) -{ - int code = CvTS::FAIL_EXCEPTION; - switch( pExp->ExceptionRecord->ExceptionCode ) - { - case EXCEPTION_ACCESS_VIOLATION: - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - case EXCEPTION_DATATYPE_MISALIGNMENT: - case EXCEPTION_FLT_STACK_CHECK: - case EXCEPTION_STACK_OVERFLOW: - case EXCEPTION_IN_PAGE_ERROR: - code = CvTS::FAIL_MEMORY_EXCEPTION; - break; - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_UNDERFLOW: - case EXCEPTION_INT_DIVIDE_BY_ZERO: - case EXCEPTION_INT_OVERFLOW: - code = CvTS::FAIL_ARITHM_EXCEPTION; - break; - case EXCEPTION_BREAKPOINT: - case EXCEPTION_ILLEGAL_INSTRUCTION: - case EXCEPTION_INVALID_DISPOSITION: - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - case EXCEPTION_PRIV_INSTRUCTION: - case EXCEPTION_SINGLE_STEP: - code = CvTS::FAIL_EXCEPTION; - } - throw code; -} -#endif - -static void change_color( int color ) -{ - static int normal_attributes = -1; - HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE); - fflush(stdout); - - if( normal_attributes < 0 ) - { - CONSOLE_SCREEN_BUFFER_INFO info; - GetConsoleScreenBufferInfo( hstdout, &info ); - normal_attributes = info.wAttributes; - } - - SetConsoleTextAttribute( hstdout, - (WORD)(color == CV_TS_NORMAL ? normal_attributes : - ((color & CV_TS_BLUE ? FOREGROUND_BLUE : 0)| - (color & CV_TS_GREEN ? FOREGROUND_GREEN : 0)| - (color & CV_TS_RED ? FOREGROUND_RED : 0)|FOREGROUND_INTENSITY)) ); -} - -#else - -#include - -static const int cv_ts_sig_id[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 }; - -static jmp_buf cv_ts_jmp_mark; - -void cv_signal_handler( int sig_code ) -{ - int code = CvTS::FAIL_EXCEPTION; - switch( sig_code ) - { - case SIGFPE: - code = CvTS::FAIL_ARITHM_EXCEPTION; - break; - case SIGSEGV: - case SIGBUS: - code = CvTS::FAIL_ARITHM_EXCEPTION; - break; - case SIGILL: - code = CvTS::FAIL_EXCEPTION; - } - - longjmp( cv_ts_jmp_mark, code ); -} - -static void change_color( int color ) -{ - static const uchar ansi_tab[] = { 30, 34, 32, 36, 31, 35, 33, 37 }; - char buf[16]; - int code = 0; - fflush( stdout ); - if( color != CV_TS_NORMAL ) - code = ansi_tab[color & (CV_TS_BLUE|CV_TS_GREEN|CV_TS_RED)]; - sprintf( buf, "\x1b[%dm", code ); - fputs( buf, stdout ); -} - -#endif - - -// reads 16-digit hexadecimal number (i.e. 64-bit integer) -static int64 read_seed( const char* str ) -{ - int64 val = 0; - if( str && strlen(str) == 16 ) - { - for( int i = 0; str[i]; i++ ) - { - int c = tolower(str[i]); - if( !isxdigit(c) ) - return 0; - val = val * 16 + - (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10); - } - } - return val; -} - - -/***************************** memory manager *****************************/ - -typedef struct CvTestAllocBlock -{ - struct CvTestAllocBlock* prev; - struct CvTestAllocBlock* next; - char* origin; - char* data; - size_t size; - int index; -} -CvTestAllocBlock; - - -class CvTestMemoryManager -{ -public: - CvTestMemoryManager( CvTS* ts ); - virtual ~CvTestMemoryManager(); - - virtual void clear_and_check( int min_index = -1 ); - virtual void start_tracking( int index_to_stop_at=-1 ); - virtual void stop_tracking_and_check(); - int get_alloc_index() { return index; } - - static void* alloc_proxy( size_t size, void* userdata ); - static int free_proxy( void* ptr, void* userdata ); - -protected: - virtual void* alloc( size_t size ); - virtual int free( void* ptr ); - virtual int free_block( CvTestAllocBlock* block ); - - int index; - int track_blocks; - int show_msg_box; - int index_to_stop_at; - const char* guard_pattern; - int guard_size; - int block_align; - enum { MAX_MARKS = 1024 }; - int marks[MAX_MARKS]; - int marks_top; - CvTS* ts; - CvTestAllocBlock* first; - CvTestAllocBlock* last; -}; - - -void* CvTestMemoryManager::alloc_proxy( size_t size, void* userdata ) -{ - return ((CvTestMemoryManager*)userdata)->alloc( size ); -} - - -int CvTestMemoryManager::free_proxy( void* ptr, void* userdata ) -{ - return ((CvTestMemoryManager*)userdata)->free( ptr ); -} - - -CvTestMemoryManager::CvTestMemoryManager( CvTS* _test_system ) -{ - ts = _test_system; - guard_pattern = "THIS IS A GUARD PATTERN!"; - guard_size = (int)strlen(guard_pattern); - block_align = CV_MALLOC_ALIGN; - track_blocks = 0; - marks_top = 0; - first = last = 0; - index = 0; - index_to_stop_at = -1; - show_msg_box = 1; -} - - -CvTestMemoryManager::~CvTestMemoryManager() -{ - clear_and_check(); -} - - -void CvTestMemoryManager::clear_and_check( int min_index ) -{ - int alloc_index = -1; - CvTestAllocBlock* block; - int leak_size = 0, leak_block_count = 0, mem_size = 0; - void* mem_addr = 0; - - while( marks_top > 0 && marks[marks_top - 1] >= min_index ) - marks_top--; - - for( block = last; block != 0; ) - { - CvTestAllocBlock* prev = block->prev; - if( block->index < min_index ) - break; - leak_size += (int)block->size; - leak_block_count++; - alloc_index = block->index; - mem_addr = block->data; - mem_size = (int)block->size; - free_block( block ); - block = prev; - } - track_blocks--; - if( leak_block_count > 0 ) - { - ts->set_failed_test_info( CvTS::FAIL_MEMORY_LEAK, alloc_index ); - ts->printf( CvTS::LOG, "Memory leaks: %u blocks, %u bytes total\n" - "%s leaked block: %p, %u bytes\n", - leak_block_count, leak_size, leak_block_count > 1 ? "The first" : "The", - mem_addr, mem_size ); - } - - index = block ? block->index + 1 : 0; -} - - -void CvTestMemoryManager::start_tracking( int _index_to_stop_at ) -{ - track_blocks--; - marks[marks_top++] = index; - assert( marks_top <= MAX_MARKS ); - track_blocks+=2; - index_to_stop_at = _index_to_stop_at >= index ? _index_to_stop_at : -1; -} - - -void CvTestMemoryManager::stop_tracking_and_check() -{ - if( marks_top > 0 ) - { - int min_index = marks[--marks_top]; - clear_and_check( min_index ); - } -} - - -int CvTestMemoryManager::free_block( CvTestAllocBlock* block ) -{ - int code = 0; - char* data = block->data; - - if( block->origin == 0 || ((size_t)block->origin & (sizeof(double)-1)) != 0 ) - code = CvTS::FAIL_MEMORY_CORRUPTION_BEGIN; - - if( memcmp( data - guard_size, guard_pattern, guard_size ) != 0 ) - code = CvTS::FAIL_MEMORY_CORRUPTION_BEGIN; - else if( memcmp( data + block->size, guard_pattern, guard_size ) != 0 ) - code = CvTS::FAIL_MEMORY_CORRUPTION_END; - - if( code >= 0 ) - { - if( block->prev ) - block->prev->next = block->next; - else if( first == block ) - first = block->next; - - if( block->next ) - block->next->prev = block->prev; - else if( last == block ) - last = block->prev; - - free( block->origin ); - } - else - { - ts->set_failed_test_info( code, block->index ); - ts->printf( CvTS::LOG, "Corrupted block (%s): %p, %u bytes\n", - code == CvTS::FAIL_MEMORY_CORRUPTION_BEGIN ? "beginning" : "end", - block->data, block->size ); - } - - return code; -} - - -void* CvTestMemoryManager::alloc( size_t size ) -{ - char* data; - CvTestAllocBlock* block; - size_t new_size = sizeof(*block) + size + guard_size*2 + block_align + sizeof(size_t)*2; - char* ptr = (char*)malloc( new_size ); - - if( !ptr ) - return 0; - - data = (char*)cvAlignPtr( ptr + sizeof(size_t) + sizeof(*block) + guard_size, block_align ); - block = (CvTestAllocBlock*)cvAlignPtr( data - guard_size - - sizeof(size_t) - sizeof(*block), sizeof(size_t) ); - block->origin = ptr; - block->data = data; - block->size = 0; - block->index = -1; - block->next = block->prev = 0; - memcpy( data - guard_size, guard_pattern, guard_size ); - memcpy( data + size, guard_pattern, guard_size ); - - if( track_blocks > 0 ) - { - track_blocks--; - block->size = size; - - if( index == index_to_stop_at ) - { - if( show_msg_box ) - { - #if defined WIN32 || defined _WIN32 - MessageBox( NULL, "The block that is corrupted and/or not deallocated has been just allocated\n" - "Press Ok to start debugging", "Memory Manager", MB_ICONERROR|MB_OK|MB_SYSTEMMODAL ); - #endif - } - CV_DBG_BREAK(); - } - - block->index = index++; - - block->prev = last; - block->next = 0; - if( last ) - last = last->next = block; - else - first = last = block; - - track_blocks++; - } - - return data; -} - - -int CvTestMemoryManager::free( void* ptr ) -{ - char* data = (char*)ptr; - CvTestAllocBlock* block = (CvTestAllocBlock*) - cvAlignPtr( data - guard_size - sizeof(size_t) - sizeof(*block), sizeof(size_t) ); - - int code = free_block( block ); - if( code < 0 && ts->is_debug_mode() ) - CV_DBG_BREAK(); - return 0; -} - - -/***************************** error handler *****************************/ - -#if 0 -static int cvTestErrorCallback( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ) -{ - if( status < 0 && status != CV_StsBackTrace && status != CV_StsAutoTrace ) - ((CvTS*)userdata)->set_failed_test_info( CvTS::FAIL_ERROR_IN_CALLED_FUNC ); - - // print error message - return cvStdErrReport( status, func_name, err_msg, file_name, line, 0 ); -} -#endif - -/*****************************************************************************************\ -* Base Class for Tests * -\*****************************************************************************************/ - -CvTest::CvTest( const char* _test_name, const char* _test_funcs, const char* _test_descr ) : - name(_test_name ? _test_name : ""), tested_functions(_test_funcs ? _test_funcs : ""), - description(_test_descr ? _test_descr : ""), ts(0) -{ - if( last ) - last->next = this; - else - first = this; - last = this; - test_count++; - ts = 0; - hdr_state = 0; - - timing_param_names = 0; - timing_param_current = 0; - timing_param_seqs = 0; - timing_param_idxs = 0; - timing_param_count = -1; - - test_case_count = -1; - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE; -} - -CvTest::~CvTest() -{ - clear(); -} - -CvTest* CvTest::get_first_test() -{ - return first; -} - -void CvTest::clear() -{ - if( timing_param_current ) - free( timing_param_current ); - if( timing_param_seqs ) - free( timing_param_seqs ); - if( timing_param_idxs ) - free( timing_param_idxs ); - - timing_param_current = 0; - timing_param_seqs = 0; - timing_param_idxs = 0; - timing_param_count = -1; -} - - -int CvTest::init( CvTS* _test_system ) -{ - clear(); - ts = _test_system; - return read_params( ts->get_file_storage() ); -} - - -const char* CvTest::get_parent_name( const char* name, char* buffer ) -{ - const char* dash_pos = strrchr( name ? name : "", '-' ); - if( !dash_pos ) - return 0; - - if( name != (const char*)buffer ) - strncpy( buffer, name, dash_pos - name ); - buffer[dash_pos - name] = '\0'; - return buffer; -} - - -const CvFileNode* CvTest::find_param( CvFileStorage* fs, const char* param_name ) -{ - char buffer[256]; - const char* name = get_name(); - CvFileNode* node = 0; - - for(;;) - { - if( !name ) - break; - node = cvGetFileNodeByName( fs, 0, name ); - if( node ) - { - node = cvGetFileNodeByName( fs, node, param_name ); - if( node ) - break; - } - name = get_parent_name( name, buffer ); - } - - return node; -} - - -void CvTest::start_write_param( CvFileStorage* fs ) -{ - if( hdr_state == 0 ) - { - cvStartWriteStruct( fs, get_name(), CV_NODE_MAP ); - hdr_state = 1; - } -} - - -void CvTest::write_param( CvFileStorage* fs, const char* paramname, int val ) -{ - if( !ts->find_written_param( this, paramname, CV_NODE_INT, &val) ) - { - start_write_param( fs ); - cvWriteInt( fs, paramname, val ); - } -} - - -void CvTest::write_param( CvFileStorage* fs, const char* paramname, double val ) -{ - if( !ts->find_written_param( this, paramname, CV_NODE_REAL, &val) ) - { - start_write_param( fs ); - cvWriteReal( fs, paramname, val ); - } -} - - -void CvTest::write_param( CvFileStorage* fs, const char* paramname, const char* val ) -{ - if( !ts->find_written_param( this, paramname, CV_NODE_STRING, &val) ) - { - start_write_param( fs ); - cvWriteString( fs, paramname, val ); - } -} - - -void CvTest::write_string_list( CvFileStorage* fs, const char* paramname, const char** val, int count ) -{ - if( val ) - { - start_write_param( fs ); - int i; - if( count < 0 ) - count = INT_MAX; - - cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; i < count && val[i] != 0; i++ ) - cvWriteString( fs, 0, val[i] ); - cvEndWriteStruct( fs ); - } -} - - -void CvTest::write_int_list( CvFileStorage* fs, const char* paramname, - const int* val, int count, int stop_value ) -{ - if( val ) - { - start_write_param( fs ); - int i; - if( count < 0 ) - count = INT_MAX; - - cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; i < count && val[i] != stop_value; i++ ) - cvWriteInt( fs, 0, val[i] ); - cvEndWriteStruct( fs ); - } -} - - -void CvTest::write_real_list( CvFileStorage* fs, const char* paramname, - const double* val, int count, double stop_value ) -{ - if( val ) - { - start_write_param( fs ); - int i; - if( count < 0 ) - count = INT_MAX; - - cvStartWriteStruct( fs, paramname, CV_NODE_SEQ + CV_NODE_FLOW ); - for( i = 0; i < count && val[i] != stop_value; i++ ) - cvWriteReal( fs, 0, val[i] ); - cvEndWriteStruct( fs ); - } -} - - -int CvTest::read_params( CvFileStorage* fs ) -{ - int code = 0; - - if(fs == NULL) - return code; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - timing_param_names = find_param( fs, "timing_params" ); - if(!timing_param_names) - return code; - - if( CV_NODE_IS_SEQ(timing_param_names->tag) ) - { - CvSeq* seq = timing_param_names->data.seq; - CvSeqReader reader; - cvStartReadSeq( seq, &reader ); - int i; - - timing_param_count = seq->total; - timing_param_seqs = (const CvFileNode**)malloc( timing_param_count*sizeof(timing_param_seqs[0])); - timing_param_idxs = (int*)malloc( timing_param_count*sizeof(timing_param_idxs[0])); - timing_param_current = (const CvFileNode**)malloc( timing_param_count*sizeof(timing_param_current[0])); - test_case_count = 1; - - for( i = 0; i < timing_param_count; i++ ) - { - CvFileNode* param_name = (CvFileNode*)(reader.ptr); - - if( !CV_NODE_IS_STRING(param_name->tag) ) - { - ts->printf( CvTS::LOG, "ERROR: name of timing parameter #%d is not a string\n", i ); - code = -1; - break; - } - - timing_param_idxs[i] = 0; - timing_param_current[i] = 0; - timing_param_seqs[i] = find_param( fs, param_name->data.str.ptr ); - if( !timing_param_seqs[i] ) - { - ts->printf( CvTS::LOG, "ERROR: timing parameter %s is not found\n", param_name->data.str.ptr ); - code = -1; - break; - } - - if( CV_NODE_IS_SEQ(timing_param_seqs[i]->tag) ) - test_case_count *= timing_param_seqs[i]->data.seq->total; - - CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); - } - - if( i < timing_param_count ) - timing_param_count = 0; - } - else - { - ts->printf( CvTS::LOG, "ERROR: \"timing_params\" is not found" ); - code = -1; - } - } - - return code; -} - - -int CvTest::get_next_timing_param_tuple(void) -{ - bool increment; - int i; - - if( timing_param_count <= 0 || !timing_param_names || !timing_param_seqs ) - return -1; - - increment = timing_param_current[0] != 0; // if already have some valid test tuple, move to the next - for( i = 0; i < timing_param_count; i++ ) - { - const CvFileNode* node = timing_param_seqs[i]; - int total = CV_NODE_IS_SEQ(node->tag) ? node->data.seq->total : 1; - int new_idx = timing_param_idxs[i]; - - if( !timing_param_current[i] ) - timing_param_idxs[i] = new_idx = 0; - else if( increment ) - { - new_idx++; - if( new_idx >= total ) - new_idx = 0; - else if( total > 1 ) - increment = false; - } - - if( !timing_param_current[i] || new_idx != timing_param_idxs[i] ) - { - if( CV_NODE_IS_SEQ(node->tag) ) - timing_param_current[i] = (CvFileNode*)cvGetSeqElem( node->data.seq, new_idx ); - else - timing_param_current[i] = node; - timing_param_idxs[i] = new_idx; - } - } - - return !increment; // return 0 in case of overflow (i.e. if there is no more test cases) -} - - -const CvFileNode* CvTest::find_timing_param( const char* paramname ) -{ - if( timing_param_names ) - { - int i; - CvSeqReader reader; - cvStartReadSeq( timing_param_names->data.seq, &reader, 0 ); - - for( i = 0; i < timing_param_count; i++ ) - { - const char* ptr = ((const CvFileNode*)(reader.ptr))->data.str.ptr; - if( ptr[0] == paramname[0] && strcmp(ptr, paramname) == 0 ) - return timing_param_current[i]; - CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader ); - } - } - return 0; -} - - -int CvTest::write_defaults(CvTS* _ts) -{ - ts = _ts; - hdr_state = 0; - write_default_params( ts->get_file_storage() ); - if( hdr_state ) - cvEndWriteStruct( ts->get_file_storage() ); - return 0; -} - - -int CvTest::write_default_params( CvFileStorage* fs ) -{ - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - write_string_list( fs, "timing_params", default_timing_param_names, timing_param_count ); - return 0; -} - - -bool CvTest::can_do_fast_forward() -{ - return true; -} - - -int CvTest::get_support_testing_modes() -{ - return support_testing_modes; -} - -void CvTest::safe_run( int start_from ) -{ - if(ts->is_debug_mode()) - run( start_from ); - else - { - try - { - #if !defined WIN32 && !defined _WIN32 - int _code = setjmp( cv_ts_jmp_mark ); - if( !_code ) - run( start_from ); - else - throw _code; - #else - run( start_from ); - #endif - } - catch (const cv::Exception& exc) - { - const char* errorStr = cvErrorStr(exc.code); - char buf[1 << 16]; - - sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d", - errorStr, exc.err.c_str(), exc.func.size() > 0 ? - exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line ); - ts->printf(CvTS::LOG, "%s\n", buf); - ts->set_failed_test_info( CvTS::FAIL_ERROR_IN_CALLED_FUNC ); - } - catch (...) - { - ts->set_failed_test_info( CvTS::FAIL_EXCEPTION ); - } - } -} - - -void CvTest::run( int start_from ) -{ - int i, test_case_idx, count = get_test_case_count(); - int64 t_start = cvGetTickCount(); - double freq = cv::getTickFrequency(); - bool ff = can_do_fast_forward(); - int progress = 0, code; - std::vector v_cpe, v_time; - int64 t1 = t_start; - - for( test_case_idx = ff && start_from >= 0 ? start_from : 0; - count < 0 || test_case_idx < count; test_case_idx++ ) - { - ts->update_context( this, test_case_idx, ff ); - progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) ); - - int64 t00 = 0, t0 = 0, t2 = 0, t3 = 0; - double t_acc = 0, t_cpu_acc = 0; - - if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - const int iterations = 20; - code = prepare_test_case( test_case_idx ); - - if( code < 0 || ts->get_err_code() < 0 ) - return; - - if( code == 0 ) - continue; - - v_cpe.resize(0); - v_time.resize(0); - - for( i = 0; i < iterations; i++ ) - { - for(;;) - { - t0 = cv::getTickCount(); - t2 = cv::getCPUTickCount(); - - run_func(); - - t3 = cv::getCPUTickCount(); - t1 = cv::getTickCount(); - - if( ts->get_err_code() < 0 ) - return; - - if( t3 - t2 > 0 && t1 - t0 > 1 ) - break; - } - - if( i == 0 ) - t00 = t0; - - v_cpe.push_back((double)(t3 - t2)); - v_time.push_back((double)(t1 - t0)); - - if( i >= 5 && t1 - t00 > freq*5 ) - break; - } - - std::sort(v_cpe.begin(), v_cpe.end()); - std::sort(v_time.begin(), v_time.end()); - - t_cpu_acc = v_cpe[i/2]; - t_acc = v_time[i/2]; - - print_time( test_case_idx, t_acc, t_cpu_acc ); - } - else - { - code = prepare_test_case( test_case_idx ); - if( code < 0 || ts->get_err_code() < 0 ) - return; - - if( code == 0 ) - continue; - - run_func(); - - if( ts->get_err_code() < 0 ) - return; - - if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 ) - return; - } - } -} - - -void CvTest::run_func(void) -{ - assert(0); -} - - -int CvTest::get_test_case_count(void) -{ - return test_case_count; -} - - -int CvTest::prepare_test_case( int ) -{ - return 0; -} - - -int CvTest::validate_test_results( int ) -{ - return 0; -} - - -void CvTest::print_time( int /*test_case_idx*/, double /*time_usecs*/, double /*time_cpu_clocks*/ ) -{ -} - - -int CvTest::update_progress( int progress, int test_case_idx, int count, double dt ) -{ - int width = 60 - (int)strlen(get_name()); - if( count > 0 ) - { - int t = cvRound( ((double)test_case_idx * width)/count ); - if( t > progress ) - { - ts->printf( CvTS::CONSOLE, "." ); - progress = t; - } - } - else if( cvRound(dt) > progress ) - { - ts->printf( CvTS::CONSOLE, "." ); - progress = cvRound(dt); - } - - return progress; -} - - -CvBadArgTest::CvBadArgTest( const char* _test_name, const char* _test_funcs, const char* _test_descr ) - : CvTest( _test_name, _test_funcs, _test_descr ) -{ - progress = -1; - test_case_idx = -1; - freq = cv::getTickFrequency(); -} - -CvBadArgTest::~CvBadArgTest(void) -{ -} - -int CvBadArgTest::run_test_case( int expected_code, const char* descr ) -{ - double new_t = (double)cv::getTickCount(), dt; - if( test_case_idx < 0 ) - { - test_case_idx = 0; - progress = 0; - dt = 0; - } - else - { - dt = (new_t - t)/(freq*1000); - t = new_t; - } - progress = update_progress(progress, test_case_idx, 0, dt); - - int errcount = 0; - bool thrown = false; - - if(!descr) - descr = ""; - - try - { - run_func(); - } - - catch(const cv::Exception& e) - { - thrown = true; - if( e.code != expected_code ) - { - ts->printf(CvTS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n", - descr, test_case_idx, e.code, expected_code); - errcount = 1; - } - } - - catch(...) - { - thrown = true; - ts->printf(CvTS::LOG, "%s (test case #%d): unknown exception was thrown (the function has likely crashed)\n", - descr, test_case_idx); - errcount = 1; - } - - if(!thrown) - { - ts->printf(CvTS::LOG, "%s (test case #%d): no expected exception was thrown\n", - descr, test_case_idx); - errcount = 1; - } - test_case_idx++; - - return errcount; -} - - -/*****************************************************************************************\ -* Base Class for Test System * -\*****************************************************************************************/ - -/******************************** Constructors/Destructors ******************************/ - -CvTS::CvTS(const char* _module_name) -{ - module_name = _module_name; - start_time = 0; - version = CV_TS_VERSION; - memory_manager = 0; - - /* - memory_manager = new CvTestMemoryManager(this); - cvSetMemoryManager( CvTestMemoryManager::alloc_proxy, - CvTestMemoryManager::free_proxy, - memory_manager );*/ - - ostrm_suffixes[SUMMARY_IDX] = ".sum"; - ostrm_suffixes[LOG_IDX] = ".log"; - ostrm_suffixes[CSV_IDX] = ".csv"; - ostrm_suffixes[CONSOLE_IDX] = 0; - - ostrm_base_name = 0; - - memset( output_streams, 0, sizeof(output_streams) ); - memset( ¶ms, 0, sizeof(params) ); - - selected_tests = new CvTestPtrVec(); - failed_tests = new CvTestInfoVec(); - written_params = new CvTestPtrVec(); - - clear(); - - return; -} // ctor - - -void CvTS::clear(void) -{ - int i; - CvTest* test; - - for( test = get_first_test(); test != 0; test = test->get_next() ) - test->clear(); - - for( i = 0; i <= CONSOLE_IDX; i++ ) - { - if( i == LOG_IDX ) - fflush( stderr ); - else if( i == CONSOLE_IDX ) - fflush( stdout ); - - if( i < CONSOLE_IDX && output_streams[i].f ) - { - fclose( output_streams[i].f ); - output_streams[i].f = 0; - } - - if( i == LOG_IDX && output_streams[i].default_handle > 0 ) - { - dup2( output_streams[i].default_handle, 2 ); - output_streams[i].default_handle = 0; - } - output_streams[i].enable = 1; - } - - cvReleaseFileStorage( &fs ); - - selected_tests->clear(); - failed_tests->clear(); - - if( ostrm_base_name ) - { - free( ostrm_base_name ); - ostrm_base_name = 0; - } - - params.rng_seed = 0; - params.debug_mode = -1; - params.print_only_failed = 0; - params.skip_header = -1; - params.ignore_blacklist = -1; - params.test_mode = CORRECTNESS_CHECK_MODE; - params.timing_mode = MIN_TIME; - params.use_optimized = -1; - params.color_terminal = 1; - - if( memory_manager ) - memory_manager->clear_and_check(); -} // clear() - - -CvTS::~CvTS(void) -{ - clear(); - set_data_path(0); - - if( written_params ) - { - for( int i = 0; i < written_params->size(); i++ ) - free( written_params->at(i) ); - delete written_params; - } - - delete selected_tests; - delete failed_tests; - - return; -} // dtor - - -const char* CvTS::str_from_code( int code ) -{ - switch( code ) - { - case OK: return "Ok"; - case FAIL_GENERIC: return "Generic/Unknown"; - case FAIL_MISSING_TEST_DATA: return "No test data"; - case FAIL_INVALID_TEST_DATA: return "Invalid test data"; - case FAIL_ERROR_IN_CALLED_FUNC: return "cvError invoked"; - case FAIL_EXCEPTION: return "Hardware/OS exception"; - case FAIL_MEMORY_EXCEPTION: return "Invalid memory access"; - case FAIL_ARITHM_EXCEPTION: return "Arithmetic exception"; - case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)"; - case FAIL_MEMORY_CORRUPTION_END: return "Corrupted memblock (end)"; - case FAIL_MEMORY_LEAK: return "Memory leak"; - case FAIL_INVALID_OUTPUT: return "Invalid function output"; - case FAIL_MISMATCH: return "Unexpected output"; - case FAIL_BAD_ACCURACY: return "Bad accuracy"; - case FAIL_HANG: return "Infinite loop(?)"; - case FAIL_BAD_ARG_CHECK: return "Incorrect handling of bad arguments"; - default: return "Generic/Unknown"; - } -} - -/************************************** Running tests **********************************/ - -void CvTS::make_output_stream_base_name( const char* config_name ) -{ - int k, len = (int)strlen( config_name ); - - if( ostrm_base_name ) - free( ostrm_base_name ); - - for( k = len-1; k >= 0; k-- ) - { - char c = config_name[k]; - if( c == '.' || c == '/' || c == '\\' || c == ':' ) - break; - } - - if( k > 0 && config_name[k] == '.' ) - len = k; - - ostrm_base_name = (char*)malloc( len + 1 ); - memcpy( ostrm_base_name, config_name, len ); - ostrm_base_name[len] = '\0'; -} - - -void CvTS::set_handlers( bool on ) -{ - if( on ) - { - cvSetErrMode( CV_ErrModeParent ); - cvRedirectError( cvStdErrReport ); - #if defined WIN32 || defined _WIN32 - #ifdef _MSC_VER - _set_se_translator( cv_seh_translator ); - #endif - #else - for( int i = 0; cv_ts_sig_id[i] >= 0; i++ ) - signal( cv_ts_sig_id[i], cv_signal_handler ); - #endif - } - else - { - cvSetErrMode( CV_ErrModeLeaf ); - cvRedirectError( cvGuiBoxReport ); - #if defined WIN32 || defined _WIN32 - #ifdef _MSC_VER - _set_se_translator( 0 ); - #endif - #else - for( int i = 0; cv_ts_sig_id[i] >= 0; i++ ) - signal( cv_ts_sig_id[i], SIG_DFL ); - #endif - } -} - - -void CvTS::set_data_path( const char* data_path ) -{ - if( data_path == params.data_path ) - return; - - if( params.data_path ) - delete[] params.data_path; - if( data_path ) - { - int size = (int)strlen(data_path)+1; - bool append_slash = data_path[size-1] != '/' && data_path[size-1] != '\\'; - params.data_path = new char[size+1]; - memcpy( params.data_path, data_path, size ); - if( append_slash ) - strcat( params.data_path, "/" ); - } -} - - -typedef struct CvTsParamVal -{ - const char* fullname; - const void* val; - -} CvTsParamVal; - - -int CvTS::find_written_param( CvTest* test, const char* paramname, int valtype, const void* val ) -{ - const char* testname = test->get_name(); - bool add_to_list = test->get_func_list()[0] == '\0'; - char buffer[256]; - int paramname_len = (int)strlen(paramname); - int paramval_len = valtype == CV_NODE_INT ? (int)sizeof(int) : - valtype == CV_NODE_REAL ? (int)sizeof(double) : -1; - const char* name = CvTest::get_parent_name( testname, buffer ); - - if( !fs ) - return -1; - - if( paramval_len < 0 ) - { - assert(0); // unsupported parameter type - return -1; - } - - while( name ) - { - int i, len = (int)strlen(buffer); - buffer[len] = '.'; - memcpy( buffer + len + 1, paramname, paramname_len + 1 ); - for( i = 0; i < written_params->size(); i++ ) - { - CvTsParamVal* param = (CvTsParamVal*)written_params->at(i); - if( strcmp( param->fullname, buffer ) == 0 ) - { - if( (paramval_len > 0 && memcmp( param->val, val, paramval_len ) == 0) || - (paramval_len < 0 && strcmp( (const char*)param->val, (const char*)val ) == 0) ) - return 1; - break; - } - } - if( i < written_params->size() ) - break; - buffer[len] = '\0'; - name = CvTest::get_parent_name( buffer, buffer ); - } - - if( add_to_list ) - { - int bufsize, fullname_len = (int)strlen(testname) + paramname_len + 2; - CvTsParamVal* param; - if( paramval_len < 0 ) - paramval_len = (int)strlen((const char*)val) + 1; - bufsize = sizeof(*param) + fullname_len + paramval_len; - param = (CvTsParamVal*)malloc(bufsize); - param->fullname = (const char*)(param + 1); - param->val = param->fullname + fullname_len; - sprintf( (char*)param->fullname, "%s.%s", testname, paramname ); - memcpy( (void*)param->val, val, paramval_len ); - written_params->push( param ); - } - - return 0; -} - - -#ifndef MAX_PATH -#define MAX_PATH 1024 -#endif - -static int CV_CDECL cmp_test_names( const void* a, const void* b ) -{ - return strcmp( (*(const CvTest**)a)->get_name(), (*(const CvTest**)b)->get_name() ); -} - -int CvTS::run( int argc, char** argv, const char** blacklist ) -{ - time( &start_time ); - - int i, write_params = 0; - int list_tests = 0; - CvTestPtrVec all_tests; - CvTest* test; - - // 0. reset all the parameters, reorder tests - clear(); - -/*#if defined WIN32 || defined _WIN32 - cv::setBreakOnError(true); -#endif*/ - - for( test = get_first_test(), i = 0; test != 0; test = test->get_next(), i++ ) - all_tests.push(test); - - if( all_tests.size() > 0 && all_tests.data() ) - qsort( all_tests.data(), all_tests.size(), sizeof(CvTest*), cmp_test_names ); - - // 1. parse command line options - for( i = 1; i < argc; i++ ) - { - if( strcmp( argv[i], "-h" ) == 0 || strcmp( argv[i], "--help" ) == 0 ) - { - print_help(); - return 0; - } - else if( strcmp( argv[i], "-f" ) == 0 ) - config_name = argv[++i]; - else if( strcmp( argv[i], "-w" ) == 0 ) - write_params = 1; - else if( strcmp( argv[i], "-t" ) == 0 ) - params.test_mode = TIMING_MODE; - else if( strcmp( argv[i], "-O0" ) == 0 || strcmp( argv[i], "-O1" ) == 0 ) - params.use_optimized = argv[i][2] - '0'; - else if( strcmp( argv[i], "-l" ) == 0 ) - list_tests = 1; - else if( strcmp( argv[i], "-d" ) == 0 ) - set_data_path(argv[++i]); - else if( strcmp( argv[i], "-nc" ) == 0 ) - params.color_terminal = 0; - else if( strcmp( argv[i], "-nh" ) == 0 ) - params.skip_header = 1; - else if( strcmp( argv[i], "-nb" ) == 0 ) - params.ignore_blacklist = 1; - else if( strcmp( argv[i], "-r" ) == 0 ) - params.debug_mode = 0; - else if( strcmp( argv[i], "-tn" ) == 0 ) - { - params.test_filter_pattern = argv[++i]; - params.test_filter_mode = CHOOSE_TESTS; - } - else if( strcmp( argv[i], "-seed" ) == 0 ) - { - params.rng_seed = read_seed(argv[++i]); - if( params.rng_seed == 0 ) - fprintf(stderr, "Invalid or zero RNG seed. Will use the seed from the config file or default one\n"); - } - } - - // this is the fallback for the current OpenCV autotools setup - if( !params.data_path || !params.data_path[0] ) - { - char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH"); - char buf[1024]; - if( datapath_dir ) - { - sprintf( buf, "%s/%s", datapath_dir, module_name ? module_name : "" ); - //printf( LOG + SUMMARY, "Data Path = %s\n", buf); - set_data_path(buf); - } - } - - if( write_params ) - { - if( !config_name ) - { - printf( LOG, "ERROR: output config name is not specified\n" ); - return -1; - } - - fs = cvOpenFileStorage( config_name, 0, CV_STORAGE_WRITE ); - if( !fs ) - { - printf( LOG, "ERROR: could not open config file %s\n", config_name ); - return -1; - } - - cvWriteComment( fs, CV_TS_VERSION " config file", 0 ); - cvStartWriteStruct( fs, "common", CV_NODE_MAP ); - write_default_params( fs ); - cvEndWriteStruct( fs ); - - for( i = 0; i < all_tests.size(); i++ ) - { - test = (CvTest*)all_tests[i]; - if( !(test->get_support_testing_modes() & get_testing_mode()) ) - continue; - - test->write_defaults( this ); - test->clear(); - } - - cvReleaseFileStorage( &fs ); - - return 0; - } - - if( !config_name ) - ; - //printf( LOG, "WARNING: config name is not specified, using default parameters\n" ); - else - { - // 2. read common parameters of test system - fs = cvOpenFileStorage( config_name, 0, CV_STORAGE_READ ); - if( !fs ) - { - printf( LOG, "ERROR: could not open config file %s", config_name ); - return -1; - } - } - - if( params.test_mode == CORRECTNESS_CHECK_MODE || fs ) - { - // in the case of algorithmic tests we always run read_params, - // even if there is no config file - if( read_params(fs) < 0 ) - return -1; - } - - if( !ostrm_base_name ) - make_output_stream_base_name( config_name ? config_name : argv[0] ); - - ostream_testname_mask = -1; // disable printing test names at initial stage - - // 3. open file streams - for( i = 0; i < CONSOLE_IDX; i++ ) - { - char filename[MAX_PATH]; - sprintf( filename, "%s%s", ostrm_base_name, ostrm_suffixes[i] ); - output_streams[i].f = fopen( filename, "wt" ); - if( !output_streams[i].f ) - { - printf( LOG, "ERROR: could not open %s\n", filename ); - return -1; - } - - if( i == LOG_IDX ) - { - // redirect stderr to log file - fflush( stderr ); - output_streams[i].default_handle = dup(2); - dup2( fileno(output_streams[i].f), 2 ); - } - } - - int filter_state = 0; - - // 4. traverse through the list of all registered tests. - // Initialize the selected tests and put them into the separate sequence - for( i = 0; i < all_tests.size(); i++ ) - { - test = (CvTest*)all_tests[i]; - if( !(test->get_support_testing_modes() & get_testing_mode()) ) - continue; - - if( strcmp( test->get_func_list(), "" ) != 0 && filter(test, filter_state, blacklist) ) - { - if( test->init(this) >= 0 ) - { - selected_tests->push( test ); - if( list_tests ) - ::printf( "%s\n", test->get_name() ); - } - else - printf( LOG, "WARNING: an error occured during test %s initialization\n", test->get_name() ); - } - } - - if( list_tests ) - { - clear(); - return 0; - } - - // 5. setup all the neccessary handlers and print header - set_handlers( !params.debug_mode ); - - if( params.use_optimized == 0 ) - cvUseOptimized(0); - - if( !params.skip_header ) - print_summary_header( SUMMARY + LOG + CONSOLE + CSV ); - rng = params.rng_seed; - update_context( 0, -1, true ); - - // 6. run all the tests - for( i = 0; i < selected_tests->size(); i++ ) - { - CvTest* test = (CvTest*)selected_tests->at(i); - int code; - CvTestInfo temp; - - if( memory_manager ) - memory_manager->start_tracking(); - - update_context( test, -1, true ); - current_test_info.rng_seed0 = current_test_info.rng_seed; - - ostream_testname_mask = 0; // reset "test name was printed" flags - logbuf = std::string(); - if( output_streams[LOG_IDX].f ) - fflush( output_streams[LOG_IDX].f ); - - temp = current_test_info; - test->safe_run(0); - if( get_err_code() >= 0 ) - { - update_context( test, -1, false ); - current_test_info.rng_seed = temp.rng_seed; - current_test_info.base_alloc_index = temp.base_alloc_index; - } - - test->clear(); - - if( memory_manager ) - memory_manager->stop_tracking_and_check(); - - code = get_err_code(); - if( code >= 0 ) - { - if( !params.print_only_failed ) - { - printf( SUMMARY + CONSOLE, "\t" ); - set_color( CV_TS_GREEN ); - printf( SUMMARY + CONSOLE, "Ok\n" ); - set_color( CV_TS_NORMAL ); - } - } - else - { - printf( SUMMARY + CONSOLE, "\t" ); - set_color( CV_TS_RED ); - printf( SUMMARY + CONSOLE, "FAIL(%s)\n", str_from_code(code) ); - set_color( CV_TS_NORMAL ); - printf( LOG, "context: test case = %d, seed = %08x%08x\n", - current_test_info.test_case_idx, - (unsigned)(current_test_info.rng_seed>>32), - (unsigned)(current_test_info.rng_seed)); - if(logbuf.size() > 0) - { - printf( SUMMARY + CONSOLE, ">>>\n%s\n", logbuf.c_str()); - } - failed_tests->push(current_test_info); - if( params.rerun_immediately ) - break; - } - } - - ostream_testname_mask = -1; - print_summary_tailer( SUMMARY + CONSOLE + LOG ); - - if( !params.debug_mode && (params.rerun_failed || params.rerun_immediately) ) - { - set_handlers(0); - update_context( 0, -1, true ); - for( i = 0; i < failed_tests->size(); i++ ) - { - CvTestInfo info = failed_tests->at(i); - if( (info.code == FAIL_MEMORY_CORRUPTION_BEGIN || - info.code == FAIL_MEMORY_CORRUPTION_END || - info.code == FAIL_MEMORY_LEAK) && memory_manager ) - memory_manager->start_tracking( info.alloc_index - info.base_alloc_index - + memory_manager->get_alloc_index() ); - rng = info.rng_seed; - test->safe_run( info.test_case_idx ); - } - } - - int nfailed = failed_tests ? (int)failed_tests->size() : 0; - - clear(); - - return nfailed; -} - - -void CvTS::print_help(void) -{ - ::printf( - "Usage: [{-h|--help}][-l] [-r] [-w] [-t] [-f ] [-d ] [-O{0|1}] [-tn ]\n\n" - "-d - specify the test data path\n" - "-f - use parameters from the provided XML/YAML config file\n" - " instead of the default parameters\n" - "-h or --help - print this help information\n" - "-l - list all the registered tests or subset of the tests,\n" - " selected in the config file, and exit\n" - "-tn - only run a specific test\n" - "-nc - do not use colors in the console output\n" - "-nh - do not print the header\n" - "-O{0|1} - disable/enable on-fly detection of IPP and other\n" - " supported optimized libs. It's enabled by default\n" - "-r - continue running tests after OS/Hardware exception occured\n" - "-t - switch to the performance testing mode instead of\n" - " the default algorithmic/correctness testing mode\n" - "-w - write default parameters of the algorithmic or\n" - " performance (when -t is passed) tests to the specifed\n" - " config file (see -f) and exit\n\n" - //"Test data path and config file can also be specified by the environment variables 'config' and 'datapath'.\n\n" - ); -} - - -#if defined WIN32 || defined _WIN32 -const char* default_data_path = "../tests/cv/testdata/"; -#else -const char* default_data_path = "../../../../tests/cv/testdata/"; -#endif - - -int CvTS::read_params( CvFileStorage* fs ) -{ - CvFileNode* node = fs ? cvGetFileNodeByName( fs, 0, "common" ) : 0; - - if(params.debug_mode < 0) - params.debug_mode = cvReadIntByName( fs, node, "debug_mode", 1 ) != 0; - - if( params.skip_header < 0 ) - params.skip_header = cvReadIntByName( fs, node, "skip_header", 0 ) > 0; - - if( params.ignore_blacklist < 0 ) - params.ignore_blacklist = cvReadIntByName( fs, node, "ignore_blacklist", 0 ) > 0; - - params.print_only_failed = cvReadIntByName( fs, node, "print_only_failed", 0 ) != 0; - params.rerun_failed = cvReadIntByName( fs, node, "rerun_failed", 0 ) != 0; - params.rerun_immediately = cvReadIntByName( fs, node, "rerun_immediately", 0 ) != 0; - const char* str = cvReadStringByName( fs, node, "filter_mode", "tests" ); - params.test_filter_mode = strcmp( str, "functions" ) == 0 ? CHOOSE_FUNCTIONS : CHOOSE_TESTS; - - str = cvReadStringByName( fs, node, "test_mode", params.test_mode == TIMING_MODE ? "timing" : "correctness" ); - - params.test_mode = strcmp( str, "timing" ) == 0 || strcmp( str, "performance" ) == 0 ? - TIMING_MODE : CORRECTNESS_CHECK_MODE; - - str = cvReadStringByName( fs, node, "timing_mode", params.timing_mode == AVG_TIME ? "avg" : "min" ); - - params.timing_mode = strcmp( str, "average" ) == 0 || strcmp( str, "avg" ) == 0 ? AVG_TIME : MIN_TIME; - params.test_filter_pattern = params.test_filter_pattern != 0 && - strlen(params.test_filter_pattern) > 0 ? params.test_filter_pattern : - cvReadStringByName( fs, node, params.test_filter_mode == CHOOSE_FUNCTIONS ? - "functions" : "tests", "" ); - params.resource_path = cvReadStringByName( fs, node, "." ); - - if( params.use_optimized < 0 ) - params.use_optimized = cvReadIntByName( fs, node, "use_optimized", -1 ); - - if( !params.data_path || !params.data_path[0] ) - { - const char* data_path = - cvReadStringByName( fs, node, "data_path", default_data_path ); - set_data_path(data_path); - } - - params.test_case_count_scale = cvReadRealByName( fs, node, "test_case_count_scale", 1. ); - - if( params.test_case_count_scale <= 0 ) - params.test_case_count_scale = 1.; - - str = cvReadStringByName( fs, node, "seed", 0 ); - - if( str && params.rng_seed == 0 ) - params.rng_seed = read_seed(str); - - if( params.rng_seed == 0 ) - params.rng_seed = cvGetTickCount(); - - str = cvReadStringByName( fs, node, "output_file_base_name", 0 ); - if( str ) - make_output_stream_base_name( str ); - - return 0; -} - - -void CvTS::write_default_params( CvFileStorage* fs ) -{ - read_params(0); // fill parameters with default values - - cvWriteInt( fs, "debug_mode", params.debug_mode ); - cvWriteInt( fs, "skip_header", params.skip_header ); - cvWriteInt( fs, "print_only_failed", params.print_only_failed ); - cvWriteInt( fs, "rerun_failed", params.rerun_failed ); - cvWriteInt( fs, "rerun_immediately", params.rerun_immediately ); - cvWriteString( fs, "filter_mode", params.test_filter_mode == CHOOSE_FUNCTIONS ? "functions" : "tests" ); - cvWriteString( fs, "test_mode", params.test_mode == TIMING_MODE ? "timing" : "correctness" ); - cvWriteString( fs, "data_path", params.data_path ? params.data_path : default_data_path, 1 ); - if( params.test_mode == TIMING_MODE ) - cvWriteString( fs, "timing_mode", params.timing_mode == AVG_TIME ? "avg" : "min" ); - // test_filter, seed & output_file_base_name are not written -} - - -void CvTS::enable_output_streams( int stream_mask, int value ) -{ - for( int i = 0; i < MAX_IDX; i++ ) - if( stream_mask & (1 << i) ) - output_streams[i].enable = value != 0; -} - - -void CvTS::update_context( CvTest* test, int test_case_idx, bool update_ts_context ) -{ - current_test_info.test = test; - current_test_info.test_case_idx = test_case_idx; - current_test_info.alloc_index = 0; - current_test_info.code = 0; - cvSetErrStatus( CV_StsOk ); - if( update_ts_context ) - { - current_test_info.rng_seed = rng; - current_test_info.base_alloc_index = memory_manager ? - memory_manager->get_alloc_index() : 0; - } -} - - -void CvTS::set_failed_test_info( int fail_code, int alloc_index ) -{ - if( fail_code == FAIL_MEMORY_CORRUPTION_BEGIN || - fail_code == FAIL_MEMORY_CORRUPTION_END || - current_test_info.code >= 0 ) - { - current_test_info.code = fail_code; - current_test_info.alloc_index = alloc_index; - } -} - - -const char* CvTS::get_libs_info( const char** addon_modules ) -{ - const char* all_info = 0; - cvGetModuleInfo( 0, &all_info, addon_modules ); - return all_info; -} - - -void CvTS::print_summary_header( int streams ) -{ - char csv_header[256], *ptr = csv_header; - int i; -#ifdef HAVE_IPP - const IppLibraryVersion* ippver = ippGetLibVersion(); -#endif - - printf( streams, "Engine: %s\n", version ); - time_t t1; - time( &t1 ); - struct tm *t2 = localtime( &t1 ); - char buf[1024]; - strftime( buf, sizeof(buf)-1, "%c", t2 ); - printf( streams, "Execution Date & Time: %s\n", buf ); - printf( streams, "Config File: %s\n", config_name ); - const char* plugins = 0; - const char* lib_verinfo = get_libs_info( &plugins ); - printf( streams, "Tested Libraries: %s\n", lib_verinfo ); - printf( streams, "Optimized Low-level Plugin\'s: %s\n", plugins ); - printf( streams, "=================================================\n"); -#ifdef HAVE_IPP - printf( streams, "Built with Intel(R) IPP\n" ); - printf( streams, " %s {%d.%d.%d.%d %s}\n", ippver->Version, ippver->major, ippver->minor, ippver->majorBuild, ippver->build, ippver->BuildDate ); - printf( streams, "=================================================\n"); -#endif - sprintf( ptr, "funcName,dataType,channels,size," ); - ptr += strlen(ptr); - - for( i = 0; i < CvTest::TIMING_EXTRA_PARAMS; i++ ) - { - sprintf( ptr, "param%d,", i ); - ptr += strlen(ptr); - } - - sprintf( ptr, "CPE,Time(uSecs)" ); - printf( CSV, "%s\n", csv_header ); -} - - -void CvTS::print_summary_tailer( int streams ) -{ - printf( streams, "=================================================\n"); - if( selected_tests && failed_tests ) - { - time_t end_time; - time( &end_time ); - double total_time = difftime( end_time, start_time ); - printf( streams, "Summary: %d out of %d tests failed\n", - failed_tests->size(), selected_tests->size() ); - int minutes = cvFloor(total_time/60.); - int seconds = cvRound(total_time - minutes*60); - int hours = minutes / 60; - minutes %= 60; - printf( streams, "Running time: %02d:%02d:%02d\n", hours, minutes, seconds ); - } -} - -#if defined _MSC_VER && _MSC_VER < 1400 -#undef vsnprintf -#define vsnprintf _vsnprintf -#endif - -void CvTS::vprintf( int streams, const char* fmt, va_list l ) -{ - if( streams ) - { - char str[1 << 14]; - vsnprintf( str, sizeof(str)-1, fmt, l ); - - for( int i = 0; i < MAX_IDX; i++ ) - { - if( (streams & (1 << i)) && output_streams[i].enable ) - { - FILE* f = i == CONSOLE_IDX ? stdout : - i == LOG_IDX ? stderr : output_streams[i].f; - if( f ) - { - if( i != CSV_IDX && !(ostream_testname_mask & (1 << i)) && current_test_info.test ) - { - fprintf( f, "-------------------------------------------------\n" ); - if( i == CONSOLE_IDX || i == SUMMARY_IDX ) - fprintf( f, "[%08x%08x]\n", (int)(current_test_info.rng_seed0 >> 32), - (int)(current_test_info.rng_seed0)); - fprintf( f, "%s: ", current_test_info.test->get_name() ); - fflush( f ); - ostream_testname_mask |= 1 << i; - if( i == LOG_IDX ) - logbuf = std::string(); - } - fputs( str, f ); - if( i == LOG_IDX ) - logbuf += std::string(str); - if( i == CONSOLE_IDX ) - fflush(f); - } - } - } - } -} - - -void CvTS::printf( int streams, const char* fmt, ... ) -{ - if( streams ) - { - va_list l; - va_start( l, fmt ); - vprintf( streams, fmt, l ); - va_end( l ); - } -} - - -void CvTS::set_color(int color) -{ - if( params.color_terminal ) - change_color(color); -} - - -static char* cv_strnstr( const char* str, int len, - const char* pattern, - int pattern_len = -1, - int whole_word = 1 ) -{ - int i; - - if( len < 0 && pattern_len < 0 ) - return (char*)strstr( str, pattern ); - - if( len < 0 ) - len = (int)strlen( str ); - - if( pattern_len < 0 ) - pattern_len = (int)strlen( pattern ); - - for( i = 0; i < len - pattern_len + 1; i++ ) - { - int j = i + pattern_len; - if( str[i] == pattern[0] && - memcmp( str + i, pattern, pattern_len ) == 0 && - (!whole_word || - ((i == 0 || (!isalnum(str[i-1]) && str[i-1] != '_')) && - (j == len || (!isalnum(str[j]) && str[j] != '_'))))) - return (char*)(str + i); - } - - return 0; -} - - -int CvTS::filter( CvTest* test, int& filter_state, const char** blacklist ) -{ - const char* pattern = params.test_filter_pattern; - const char* test_name = test->get_name(); - int inverse = 0; - int greater_or_equal = 0; - - if( blacklist && !params.ignore_blacklist ) - { - for( ; *blacklist != 0; blacklist++ ) - { - if( strcmp( *blacklist, test_name ) == 0 ) - return 0; - } - } - - if( pattern && pattern[0] == '!' ) - { - inverse = 1; - pattern++; - } - - if( pattern && pattern[0] == '>' ) - { - greater_or_equal = 1; - pattern++; - if( pattern[0] == '=' ) - { - greater_or_equal = 2; - pattern++; - } - } - - if( !pattern || strcmp( pattern, "" ) == 0 || strcmp( pattern, "*" ) == 0 ) - return 1 ^ inverse; - - if( params.test_filter_mode == CHOOSE_TESTS ) - { - int found = 0; - - while( pattern && *pattern ) - { - char *ptr, *endptr = (char*)strchr( pattern, ',' ); - int len, have_wildcard; - int t_name_len; - - if( endptr ) - *endptr = '\0'; - - ptr = (char*)strchr( pattern, '*' ); - if( ptr ) - { - len = (int)(ptr - pattern); - have_wildcard = 1; - } - else - { - len = (int)strlen( pattern ); - have_wildcard = 0; - } - - t_name_len = (int)strlen( test_name ); - found = (t_name_len == len || (have_wildcard && t_name_len > len)) && - (len == 0 || memcmp( test_name, pattern, len ) == 0); - if( endptr ) - { - *endptr = ','; - pattern = endptr + 1; - while( isspace(*pattern) ) - pattern++; - } - - if( found || !endptr ) - break; - } - - if( greater_or_equal == 0 ) - return found ^ inverse; - if( filter_state ) - return inverse^1; - if( !found ) - return inverse; - if( greater_or_equal == 1 ) - { - filter_state = 1; - return inverse; - } - else - { - assert(filter_state == 2); - filter_state = 1; - return inverse ^ 1; - } - } - else - { - assert( params.test_filter_mode == CHOOSE_FUNCTIONS ); - int glob_len = (int)strlen( pattern ); - const char* ptr = test->get_func_list(); - const char *tmp_ptr; - - while( ptr && *ptr ) - { - const char* endptr = ptr - 1; - const char* name_ptr; - const char* name_first_match; - int name_len; - char c; - - do c = *++endptr; - while( isspace(c) ); - - if( !c ) - break; - - assert( isalpha(c) ); - name_ptr = endptr; - - do c = *++endptr; - while( isalnum(c) || c == '_' ); - - if( c == ':' ) // class - { - assert( endptr[1] == ':' ); - endptr = endptr + 2; - name_len = (int)(endptr - name_ptr); - - // find the first occurence of the class name - // in pattern - name_first_match = cv_strnstr( pattern, - glob_len, name_ptr, name_len, 1 ); - - if( *endptr == '*' ) - { - if( name_first_match ) - return 1 ^ inverse; - } - else - { - assert( *endptr == '{' ); // a list of methods - - if( !name_first_match ) - { - // skip all the methods, if there is no such a class name - // in pattern - endptr = strchr( endptr, '}' ); - assert( endptr != 0 ); - endptr--; - } - - for( ;; ) - { - const char* method_name_ptr; - int method_name_len; - - do c = *++endptr; - while( isspace(c) ); - - if( c == '}' ) - break; - assert( isalpha(c) ); - - method_name_ptr = endptr; - - do c = *++endptr; - while( isalnum(c) || c == '_' ); - - method_name_len = (int)(endptr - method_name_ptr); - - // search for class_name::* or - // class_name::{...method_name...} - tmp_ptr = name_first_match; - do - { - const char* tmp_ptr2; - tmp_ptr += name_len; - if( *tmp_ptr == '*' ) - return 1; - assert( *tmp_ptr == '{' ); - tmp_ptr2 = strchr( tmp_ptr, '}' ); - assert( tmp_ptr2 ); - - if( cv_strnstr( tmp_ptr, (int)(tmp_ptr2 - tmp_ptr) + 1, - method_name_ptr, method_name_len, 1 )) - return 1 ^ inverse; - - tmp_ptr = cv_strnstr( tmp_ptr2, glob_len - - (int)(tmp_ptr2 - pattern), - name_ptr, name_len, 1 ); - } - while( tmp_ptr ); - - endptr--; - do c = *++endptr; - while( isspace(c) ); - - if( c != ',' ) - endptr--; - } - } - } - else - { - assert( !c || isspace(c) || c == ',' ); - name_len = (int)(endptr - name_ptr); - tmp_ptr = pattern; - - for(;;) - { - const char *tmp_ptr2, *tmp_ptr3; - - tmp_ptr = cv_strnstr( tmp_ptr, glob_len - - (int)(tmp_ptr - pattern), name_ptr, name_len, 1 ); - - if( !tmp_ptr ) - break; - - // make sure it is not a method - tmp_ptr2 = strchr( tmp_ptr, '}' ); - if( !tmp_ptr2 ) - return 1 ^ inverse; - - tmp_ptr3 = strchr( tmp_ptr, '{' ); - if( tmp_ptr3 < tmp_ptr2 ) - return 1 ^ inverse; - - tmp_ptr = tmp_ptr2 + 1; - } - - endptr--; - } - - do c = *++endptr; - while( isspace(c) ); - - if( c == ',' ) - endptr++; - ptr = endptr; - } - - return 0 ^ inverse; - } -} - -/* End of file. */ diff --git a/tests/cxts/cxts.h b/tests/cxts/cxts.h deleted file mode 100644 index 6e24704..0000000 --- a/tests/cxts/cxts.h +++ /dev/null @@ -1,837 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef __CXTS_H__ -#define __CXTS_H__ - -#include "opencv2/core/core.hpp" -#include "opencv2/core/core_c.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#if _MSC_VER >= 1200 -#pragma warning( disable: 4710 ) -#endif - -#define CV_TS_VERSION "CxTest 0.1" - -#define __BEGIN__ __CV_BEGIN__ -#define __END__ __CV_END__ -#define EXIT __CV_EXIT__ - -// Helper class for growing vector (to avoid dependency from STL) -template < typename T > class CvTestVec -{ -public: - CvTestVec() { _max_size = _size = 0; _buf = 0; } - ~CvTestVec() { delete[] _buf; } - T& operator []( int i ) { assert( (unsigned)i < (unsigned)_size ); return _buf[i]; } - T at( int i ) { assert( (unsigned)i < (unsigned)_size ); return _buf[i]; } - T pop() { assert( _size > 0 ); return _buf[--_size]; } - void push( const T& elem ) - { - if( _size >= _max_size ) - { - int i, _new_size = _max_size < 16 ? 16 : _max_size*3/2; - T* temp = new T[_new_size]; - for( i = 0; i < _size; i++ ) - temp[i] = _buf[i]; - delete[] _buf; - _max_size = _new_size; - _buf = temp; - } - _buf[_size++] = elem; - } - - int size() { return _size; } - T* data() { return _buf; } - void clear() { _size = 0; } - -protected: - T* _buf; - int _size, _max_size; -}; - -/*****************************************************************************************\ -* Base class for tests * -\*****************************************************************************************/ - -class CvTest; -class CvTS; - -class CV_EXPORTS CvTest -{ -public: - // constructor(s) and destructor - CvTest( const char* test_name, const char* test_funcs, const char* test_descr = "" ); - virtual ~CvTest(); - - virtual int init( CvTS* system ); - - // writes default parameters to file storage - virtual int write_defaults(CvTS* ts); - - // the main procedure of the test - virtual void run( int start_from ); - - // the wrapper for run that cares of exceptions - virtual void safe_run( int start_from ); - - const char* get_name() const { return name; } - const char* get_func_list() const { return tested_functions; } - const char* get_description() const { return description; } - const char* get_group_name( char* buffer ) const; - CvTest* get_next() { return next; } - static CvTest* get_first_test(); - static const char* get_parent_name( const char* name, char* buffer ); - - // returns true if and only if the different test cases do not depend on each other - // (so that test system could get right to a problematic test case) - virtual bool can_do_fast_forward(); - - // deallocates all the memory. - // called by init() (before initialization) and by the destructor - virtual void clear(); - - // returns the testing modes supported by the particular test - int get_support_testing_modes(); - - enum { TIMING_EXTRA_PARAMS=5 }; - -protected: - static CvTest* first; - static CvTest* last; - static int test_count; - CvTest* next; - - const char** default_timing_param_names; // the names of timing parameters to write - const CvFileNode* timing_param_names; // and the read param names - const CvFileNode** timing_param_current; // the current tuple of timing parameters - const CvFileNode** timing_param_seqs; // the array of parameter sequences - int* timing_param_idxs; // the array of indices - int timing_param_count; // the number of parameters in the tuple - int support_testing_modes; - - int test_case_count; // the total number of test cases - - // called from write_defaults - virtual int write_default_params(CvFileStorage* fs); - - // read test params - virtual int read_params( CvFileStorage* fs ); - - // returns the number of tests or -1 if it is unknown a-priori - virtual int get_test_case_count(); - - // prepares data for the next test case. rng seed is updated by the function - virtual int prepare_test_case( int test_case_idx ); - - // checks if the test output is valid and accurate - virtual int validate_test_results( int test_case_idx ); - - // calls the tested function. the method is called from run_test_case() - virtual void run_func(); // runs tested func(s) - - // prints results of timing test - virtual void print_time( int test_case_idx, double time_usecs, double time_cpu_clocks ); - - // updates progress bar - virtual int update_progress( int progress, int test_case_idx, int count, double dt ); - - // finds test parameter - const CvFileNode* find_param( CvFileStorage* fs, const char* param_name ); - - // writes parameters - void write_param( CvFileStorage* fs, const char* paramname, int val ); - void write_param( CvFileStorage* fs, const char* paramname, double val ); - void write_param( CvFileStorage* fs, const char* paramname, const char* val ); - void write_string_list( CvFileStorage* fs, const char* paramname, const char** val, int count=-1 ); - void write_int_list( CvFileStorage* fs, const char* paramname, const int* val, - int count, int stop_value=INT_MIN ); - void write_real_list( CvFileStorage* fs, const char* paramname, const double* val, - int count, double stop_value=DBL_MIN ); - void start_write_param( CvFileStorage* fs ); - - // returns the specified parameter from the current parameter tuple - const CvFileNode* find_timing_param( const char* paramname ); - - // gets the next tuple of timing parameters - int get_next_timing_param_tuple(); - - // name of the test (it is possible to locate a test by its name) - const char* name; - - // comma-separated list of functions that are invoked - // (and, thus, tested explicitly or implicitly) by the test - // methods of classes can be grouped using {}. - // a few examples: - // "cvCanny, cvAdd, cvSub, cvMul" - // "CvImage::{Create, CopyOf}, cvMatMulAdd, CvCalibFilter::{PushFrame, SetCameraCount}" - const char* tested_functions; - - // description of the test - const char* description; - - // pointer to the system that includes the test - CvTS* ts; - - int hdr_state; -}; - - -/*****************************************************************************************\ -* Information about a failed test * -\*****************************************************************************************/ - -typedef struct CvTestInfo -{ - // pointer to the test - CvTest* test; - - // failure code (CV_FAIL*) - int code; - - // seed value right before the data for the failed test case is prepared. - uint64 rng_seed; - - // seed value right before running the test - uint64 rng_seed0; - - // index of test case, can be then passed to CvTest::proceed_to_test_case() - int test_case_idx; - - // index of the corrupted or leaked block - int alloc_index; - - // index of the first block in the group - // (used to adjust alloc_index when some test/test cases are skipped). - int base_alloc_index; -} -CvTestInfo; - -/*****************************************************************************************\ -* Base Class for test system * -\*****************************************************************************************/ - -class CvTestMemoryManager; - -typedef CvTestVec CvTestIntVec; -typedef CvTestVec CvTestPtrVec; -typedef CvTestVec CvTestInfoVec; - -class CV_EXPORTS CvTS -{ -public: - - // constructor(s) and destructor - CvTS(const char* _module_name=0); - virtual ~CvTS(); - - enum - { - NUL=0, - SUMMARY_IDX=0, - SUMMARY=1 << SUMMARY_IDX, - LOG_IDX=1, - LOG=1 << LOG_IDX, - CSV_IDX=2, - CSV=1 << CSV_IDX, - CONSOLE_IDX=3, - CONSOLE=1 << CONSOLE_IDX, - MAX_IDX=4 - }; - - // low-level printing functions that are used by individual tests and by the system itself - virtual void printf( int streams, const char* fmt, ... ); - virtual void vprintf( int streams, const char* fmt, va_list arglist ); - - // runs the tests (the whole set or some selected tests) - virtual int run( int argc, char** argv, const char** blacklist=0 ); - - // updates the context: current test, test case, rng state - virtual void update_context( CvTest* test, int test_case_idx, bool update_ts_context ); - - const CvTestInfo* get_current_test_info() { return ¤t_test_info; } - - // sets information about a failed test - virtual void set_failed_test_info( int fail_code, int alloc_index = -1 ); - - // types of tests - enum - { - CORRECTNESS_CHECK_MODE = 1, - TIMING_MODE = 2 - }; - - // the modes of timing tests: - enum { AVG_TIME = 1, MIN_TIME = 2 }; - - // test error codes - enum - { - // everything is Ok - OK=0, - - // generic error: stub value to be used - // temporarily if the error's cause is unknown - FAIL_GENERIC=-1, - - // the test is missing some essential data to proceed further - FAIL_MISSING_TEST_DATA=-2, - - // the tested function raised an error via cxcore error handler - FAIL_ERROR_IN_CALLED_FUNC=-3, - - // an exception has been raised; - // for memory and arithmetic exception - // there are two specialized codes (see below...) - FAIL_EXCEPTION=-4, - - // a memory exception - // (access violation, access to missed page, stack overflow etc.) - FAIL_MEMORY_EXCEPTION=-5, - - // arithmetic exception (overflow, division by zero etc.) - FAIL_ARITHM_EXCEPTION=-6, - - // the tested function corrupted memory (no exception have been raised) - FAIL_MEMORY_CORRUPTION_BEGIN=-7, - FAIL_MEMORY_CORRUPTION_END=-8, - - // the tested function (or test ifself) do not deallocate some memory - FAIL_MEMORY_LEAK=-9, - - // the tested function returned invalid object, e.g. matrix, containing NaNs, - // structure with NULL or out-of-range fields (while it should not) - FAIL_INVALID_OUTPUT=-10, - - // the tested function returned valid object, but it does not match to - // the original (or produced by the test) object - FAIL_MISMATCH=-11, - - // the tested function returned valid object (a single number or numerical array), - // but it differs too much from the original (or produced by the test) object - FAIL_BAD_ACCURACY=-12, - - // the tested function hung. Sometimes, can be determined by unexpectedly long - // processing time (in this case there should be possibility to interrupt such a function - FAIL_HANG=-13, - - // unexpected responce on passing bad arguments to the tested function - // (the function crashed, proceed succesfully (while it should not), or returned - // error code that is different from what is expected) - FAIL_BAD_ARG_CHECK=-14, - - // the test data (in whole or for the particular test case) is invalid - FAIL_INVALID_TEST_DATA=-15, - - // the test has been skipped because it is not in the selected subset of the tests to run, - // because it has been run already within the same run with the same parameters, or because - // of some other reason and this is not considered as an error. - // Normally CvTS::run() (or overrided method in the derived class) takes care of what - // needs to be run, so this code should not occur. - SKIPPED=1 - }; - - // get file storage - CvFileStorage* get_file_storage() { return fs; } - - // get RNG to generate random input data for a test - CvRNG* get_rng() { return &rng; } - - // returns the current error code - int get_err_code() { return current_test_info.code; } - - // retrieves the first registered test - CvTest* get_first_test() { return CvTest::get_first_test(); } - - // retrieves one of global options of the test system - int is_debug_mode() { return params.debug_mode; } - - // returns the current testing mode - int get_testing_mode() { return params.test_mode; } - - // returns the current timing mode - int get_timing_mode() { return params.timing_mode; } - - // returns the test extensivity scale - double get_test_case_count_scale() { return params.test_case_count_scale; } - - int find_written_param( CvTest* test, const char* paramname, - int valtype, const void* val ); - - const char* get_data_path() { return params.data_path ? params.data_path : ""; } - -protected: - // deallocates memory buffers and closes all the streams; - // called by init() and from destructor. It does not remove any tests!!! - virtual void clear(); - - // retrieves information about the test libraries (names, versions, build dates etc.) - virtual const char* get_libs_info( const char** loaded_ipp_modules ); - - // returns textual description of failure code - virtual const char* str_from_code( int code ); - - // prints header of summary of test suite run. - // It goes before the results of individual tests and contains information about tested libraries - // (as reported by get_libs_info()), information about test environment (CPU, test machine name), - // date and time etc. - virtual void print_summary_header( int streams ); - - // prints tailer of summary of test suite run. - // it goes after the results of individual tests and contains the number of - // failed tests, total running time, exit code (whether the system has been crashed, - // interrupted by the user etc.), names of files with additional information etc. - virtual void print_summary_tailer( int streams ); - - // reads common parameters of the test system; called from init() - virtual int read_params( CvFileStorage* fs ); - - // checks, whether the test needs to be run (1) or not (0); called from run() - virtual int filter( CvTest* test, int& filter_state, const char** blacklist=0 ); - - // makes base name of output files - virtual void make_output_stream_base_name( const char* config_name ); - - // forms default test configuration file that can be - // customized further - virtual void write_default_params( CvFileStorage* fs ); - - // enables/disables the specific output stream[s] - virtual void enable_output_streams( int streams, int flag ); - - // sets memory and exception handlers - virtual void set_handlers( bool on ); - - // changes the path to test data files - virtual void set_data_path( const char* data_path ); - - // prints the information about command-line parameters - virtual void print_help(); - - // changes the text color in console - virtual void set_color(int color); - - // a sequence of tests to run - CvTestPtrVec* selected_tests; - - // a sequence of written test params - CvTestPtrVec* written_params; - - // a sequence of failed tests - CvTestInfoVec* failed_tests; - - // base name for output streams - char* ostrm_base_name; - const char* ostrm_suffixes[MAX_IDX]; - - // parameters that can be read from file storage - CvFileStorage* fs; - - enum { CHOOSE_TESTS = 0, CHOOSE_FUNCTIONS = 1 }; - - // common parameters: - struct - { - // if non-zero, the tests are run in unprotected mode to debug possible crashes, - // otherwise the system tries to catch the exceptions and continue with other tests - int debug_mode; - - // if > 0, the header is not print - int skip_header; - - // if > 0, the blacklist is ignored - int ignore_blacklist; - - // if non-zero, the system includes only failed tests into summary - bool print_only_failed; - - // rerun failed tests in debug mode - bool rerun_failed; - - // if non-zero, the failed tests are rerun immediately - bool rerun_immediately; - - // choose_tests or choose_functions; - int test_filter_mode; - - // correctness or performance [or bad-arg, stress etc.] - int test_mode; - - // timing mode - int timing_mode; - - // pattern for choosing tests - const char* test_filter_pattern; - - // RNG seed, passed to and updated by every test executed. - uint64 rng_seed; - - // relative or absolute path of directory containing subfolders with test data - const char* resource_path; - - // whether to use IPP, MKL etc. or not - int use_optimized; - - // extensivity of the tests, scale factor for test_case_count - double test_case_count_scale; - - // the path to data files used by tests - char* data_path; - - // whether the output to console should be colored - int color_terminal; - } - params; - - // these are allocated within a test to try keep them valid in case of stack corruption - CvRNG rng; - - // test system start time - time_t start_time; - - // test system version (=CV_TS_VERSION by default) - const char* version; - - // name of config file - const char* config_name; - - const char* module_name; - - // information about the current test - CvTestInfo current_test_info; - - // memory manager used to detect memory corruptions and leaks - CvTestMemoryManager* memory_manager; - - // output streams - struct StreamInfo - { - FILE* f; - //const char* filename; - int default_handle; // for stderr - int enable; - }; - - StreamInfo output_streams[MAX_IDX]; - int ostream_testname_mask; - std::string logbuf; -}; - - -/*****************************************************************************************\ -* Subclass of CvTest for testing functions that process dense arrays * -\*****************************************************************************************/ - -class CV_EXPORTS CvArrTest : public CvTest -{ -public: - // constructor(s) and destructor - CvArrTest( const char* test_name, const char* test_funcs, const char* test_descr = "" ); - virtual ~CvArrTest(); - - virtual int write_default_params( CvFileStorage* fs ); - virtual void clear(); - -protected: - - virtual int read_params( CvFileStorage* fs ); - virtual int prepare_test_case( int test_case_idx ); - virtual int validate_test_results( int test_case_idx ); - - virtual void prepare_to_validation( int test_case_idx ); - virtual void get_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types ); - virtual void get_timing_test_array_types_and_sizes( int test_case_idx, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ); - virtual void fill_array( int test_case_idx, int i, int j, CvMat* arr ); - virtual void get_minmax_bounds( int i, int j, int type, CvScalar* low, CvScalar* high ); - virtual double get_success_error_level( int test_case_idx, int i, int j ); - virtual void print_time( int test_case_idx, double time_usecs, double time_cpu_clocks ); - virtual void print_timing_params( int test_case_idx, char* ptr, int params_left=TIMING_EXTRA_PARAMS ); - - bool cvmat_allowed; - bool iplimage_allowed; - bool optional_mask; - bool element_wise_relative_error; - - int min_log_array_size; - int max_log_array_size; - - int max_arr; // = MAX_ARR by default, the number of different types of arrays - int max_hdr; // size of header buffer - enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR }; - - const CvSize* size_list; - const CvSize* whole_size_list; - const int* depth_list; - const int* cn_list; - - CvTestPtrVec* test_array; - CvMat* test_mat[MAX_ARR]; - CvMat* hdr; - float buf[4]; -}; - - -class CV_EXPORTS CvBadArgTest : public CvTest -{ -public: - // constructor(s) and destructor - CvBadArgTest( const char* test_name, const char* test_funcs, const char* test_descr = "" ); - virtual ~CvBadArgTest(); - -protected: - virtual int run_test_case( int expected_code, const char* descr ); - virtual void run_func(void) = 0; - int test_case_idx; - int progress; - double t, freq; - - template - int run_test_case( int expected_code, const char* descr, F f) - { - double new_t = (double)cv::getTickCount(), dt; - if( test_case_idx < 0 ) - { - test_case_idx = 0; - progress = 0; - dt = 0; - } - else - { - dt = (new_t - t)/(freq*1000); - t = new_t; - } - progress = update_progress(progress, test_case_idx, 0, dt); - - int errcount = 0; - bool thrown = false; - if(!descr) - descr = ""; - - try - { - f(); - } - catch(const cv::Exception& e) - { - thrown = true; - if( e.code != expected_code ) - { - ts->printf(CvTS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n", - descr, test_case_idx, e.code, expected_code); - errcount = 1; - } - } - catch(...) - { - thrown = true; - ts->printf(CvTS::LOG, "%s (test case #%d): unknown exception was thrown (the function has likely crashed)\n", - descr, test_case_idx); - errcount = 1; - } - if(!thrown) - { - ts->printf(CvTS::LOG, "%s (test case #%d): no expected exception was thrown\n", - descr, test_case_idx); - errcount = 1; - } - test_case_idx++; - - return errcount; - } -}; - -/****************************************************************************************\ -* Utility Functions * -\****************************************************************************************/ - -CV_EXPORTS const char* cvTsGetTypeName( int type ); -CV_EXPORTS int cvTsTypeByName( const char* type_name ); - -inline int cvTsClipInt( int val, int min_val, int max_val ) -{ - if( val < min_val ) - val = min_val; - if( val > max_val ) - val = max_val; - return val; -} - -// return min & max values for given type, e.g. for CV_8S ~ -128 and 127, respectively. -CV_EXPORTS double cvTsMinVal( int type ); -CV_EXPORTS double cvTsMaxVal( int type ); - -// returns c-norm of the array -CV_EXPORTS double cvTsMaxVal( const CvMat* arr ); - -inline CvMat* cvTsGetMat( const CvMat* arr, CvMat* stub, int* coi=0 ) -{ - return cvGetMat( arr, stub, coi ); -} - -// fills array with random numbers -CV_EXPORTS void cvTsRandUni( CvRNG* rng, CvMat* a, CvScalar param1, CvScalar param2 ); - -inline unsigned cvTsRandInt( CvRNG* rng ) -{ - uint64 temp = *rng; - temp = (uint64)(unsigned)temp*1554115554 + (temp >> 32); - *rng = temp; - return (unsigned)temp; -} - -inline double cvTsRandReal( CvRNG* rng ) -{ - return cvTsRandInt( rng ) * 2.3283064365386962890625e-10 /* 2^-32 */; -} - -// fills c with zeros -CV_EXPORTS void cvTsZero( CvMat* c, const CvMat* mask=0 ); - -// initializes scaled identity matrix -CV_EXPORTS void cvTsSetIdentity( CvMat* c, CvScalar diag_value ); - -// copies a to b (whole matrix or only the selected region) -CV_EXPORTS void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask=0 ); - -// converts one array to another -CV_EXPORTS void cvTsConvert( const CvMat* src, CvMat* dst ); - -// working with multi-channel arrays -CV_EXPORTS void cvTsExtract( const CvMat* a, CvMat* plane, int coi ); -CV_EXPORTS void cvTsInsert( const CvMat* plane, CvMat* a, int coi ); - -// c = alpha*a + beta*b + gamma -CV_EXPORTS void cvTsAdd( const CvMat* a, CvScalar alpha, const CvMat* b, CvScalar beta, - CvScalar gamma, CvMat* c, int calc_abs ); - -// c = a*b*alpha -CV_EXPORTS void cvTsMul( const CvMat* _a, const CvMat* _b, CvScalar alpha, CvMat* _c ); - -// c = a*alpha/b -CV_EXPORTS void cvTsDiv( const CvMat* _a, const CvMat* _b, CvScalar alpha, CvMat* _c ); - -enum { CV_TS_MIN = 0, CV_TS_MAX = 1 }; - -// min/max -CV_EXPORTS void cvTsMinMax( const CvMat* _a, const CvMat* _b, CvMat* _c, int op_type ); -CV_EXPORTS void cvTsMinMaxS( const CvMat* _a, double scalar, CvMat* _c, int op_type ); - -// checks that the array does not have NaNs and/or Infs and all the elements are -// within [min_val,max_val). idx is the index of the first "bad" element. -CV_EXPORTS int cvTsCheck( const CvMat* data, double min_val, double max_val, CvPoint* idx ); - -// compares two arrays. max_diff is the maximum actual difference, -// success_err_level is maximum allowed difference, idx is the index of the first -// element for which difference is >success_err_level -// (or index of element with the maximum difference) -CV_EXPORTS int cvTsCmpEps( const CvMat* data, const CvMat* etalon, double* max_diff, - double success_err_level, CvPoint* idx, - bool element_wise_relative_error ); - -// a wrapper for the previous function. in case of error prints the message to log file. -CV_EXPORTS int cvTsCmpEps2( CvTS* ts, const CvArr* _a, const CvArr* _b, double success_err_level, - bool element_wise_relative_error, const char* desc ); - -CV_EXPORTS int cvTsCmpEps2_64f( CvTS* ts, const double* val, const double* ref_val, int len, - double eps, const char* param_name ); - -// compares two arrays. the result is 8s image that takes values -1, 0, 1 -CV_EXPORTS void cvTsCmp( const CvMat* a, const CvMat* b, CvMat* result, int cmp_op ); - -// compares array and a scalar. -CV_EXPORTS void cvTsCmpS( const CvMat* a, double fval, CvMat* result, int cmp_op ); - -// retrieves C, L1 or L2 norm of array or its region -CV_EXPORTS double cvTsNorm( const CvMat* _arr, const CvMat* _mask, int norm_type, int coi ); - -// retrieves mean, standard deviation and the number of nonzero mask pixels -CV_EXPORTS int cvTsMeanStdDevNonZero( const CvMat* _arr, const CvMat* _mask, - CvScalar* _mean, CvScalar* _stddev, int coi ); - -// retrieves global extremums and their positions -CV_EXPORTS void cvTsMinMaxLoc( const CvMat* _arr, const CvMat* _mask, - double* _minval, double* _maxval, - CvPoint* _minidx, CvPoint* _maxidx, int coi ); - -enum { CV_TS_LOGIC_AND = 0, CV_TS_LOGIC_OR = 1, CV_TS_LOGIC_XOR = 2, CV_TS_LOGIC_NOT = 3 }; - -CV_EXPORTS void cvTsLogic( const CvMat* a, const CvMat* b, CvMat* c, int logic_op ); -CV_EXPORTS void cvTsLogicS( const CvMat* a, CvScalar s, CvMat* c, int logic_op ); - -enum { CV_TS_GEMM_A_T = 1, CV_TS_GEMM_B_T = 2, CV_TS_GEMM_C_T = 4 }; - -CV_EXPORTS void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha, - const CvMat* c, double beta, CvMat* d, int flags ); - -CV_EXPORTS void cvTsConvolve2D( const CvMat* a, CvMat* b, const CvMat* kernel, CvPoint anchor ); -// op_type == CV_TS_MIN/CV_TS_MAX -CV_EXPORTS void cvTsMinMaxFilter( const CvMat* a, CvMat* b, - const IplConvKernel* element, int op_type ); - -enum { CV_TS_BORDER_REPLICATE=0, CV_TS_BORDER_REFLECT=1, CV_TS_BORDER_FILL=2 }; - -CV_EXPORTS void cvTsPrepareToFilter( const CvMat* a, CvMat* b, CvPoint ofs, - int border_mode = CV_TS_BORDER_REPLICATE, - CvScalar fill_val=cvScalarAll(0)); - -CV_EXPORTS double cvTsCrossCorr( const CvMat* a, const CvMat* b ); - -CV_EXPORTS CvMat* cvTsSelect( const CvMat* a, CvMat* header, CvRect rect ); - -CV_EXPORTS CvMat* cvTsTranspose( const CvMat* a, CvMat* b ); -CV_EXPORTS void cvTsFlip( const CvMat* a, CvMat* b, int flip_type ); - -CV_EXPORTS void cvTsTransform( const CvMat* a, CvMat* b, const CvMat* transmat, const CvMat* shift ); - -// modifies values that are close to zero -CV_EXPORTS void cvTsPatchZeros( CvMat* mat, double level ); - -#endif/*__CXTS_H__*/ - diff --git a/tests/cxts/cxts_arrtest.cpp b/tests/cxts/cxts_arrtest.cpp deleted file mode 100644 index 324d032..0000000 --- a/tests/cxts/cxts_arrtest.cpp +++ /dev/null @@ -1,691 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "_cxts.h" - -static const int default_test_case_count = 500; -static const int default_max_log_array_size = 9; - -CvArrTest::CvArrTest( const char* _test_name, const char* _test_funcs, const char* _test_descr ) : - CvTest( _test_name, _test_funcs, _test_descr ) -{ - test_case_count = default_test_case_count; - - iplimage_allowed = true; - cvmat_allowed = true; - optional_mask = false; - min_log_array_size = 0; - max_log_array_size = default_max_log_array_size; - element_wise_relative_error = true; - - size_list = 0; - whole_size_list = 0; - depth_list = 0; - cn_list = 0; - - max_arr = MAX_ARR; - test_array = new CvTestPtrVec[max_arr]; - max_hdr = 0; - hdr = 0; - - support_testing_modes = CvTS::CORRECTNESS_CHECK_MODE + CvTS::TIMING_MODE; -} - - -CvArrTest::~CvArrTest() -{ - clear(); - delete[] test_array; - test_array = 0; -} - - -int CvArrTest::write_default_params( CvFileStorage* fs ) -{ - int code = CvTest::write_default_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - write_param( fs, "min_log_array_size", min_log_array_size ); - write_param( fs, "max_log_array_size", max_log_array_size ); - } - else if( ts->get_testing_mode() == CvTS::TIMING_MODE ) - { - int i; - - start_write_param( fs ); // make sure we have written the entry header containing the test name - if( size_list ) - { - cvStartWriteStruct( fs, "size", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; size_list[i].width >= 0; i++ ) - { - cvStartWriteStruct( fs, 0, CV_NODE_SEQ+CV_NODE_FLOW ); - cvWriteInt( fs, 0, size_list[i].width ); - cvWriteInt( fs, 0, size_list[i].height ); - if( whole_size_list && - (whole_size_list[i].width > size_list[i].width || - whole_size_list[i].height > size_list[i].height) ) - { - cvWriteInt( fs, 0, whole_size_list[i].width ); - cvWriteInt( fs, 0, whole_size_list[i].height ); - } - cvEndWriteStruct( fs ); - } - cvEndWriteStruct(fs); - } - - if( depth_list ) - { - cvStartWriteStruct( fs, "depth", CV_NODE_SEQ+CV_NODE_FLOW ); - for( i = 0; depth_list[i] >= 0; i++ ) - cvWriteString( fs, 0, cvTsGetTypeName(depth_list[i]) ); - cvEndWriteStruct(fs); - } - - write_int_list( fs, "channels", cn_list, -1, -1 ); - - if( optional_mask ) - { - static const int use_mask[] = { 0, 1 }; - write_int_list( fs, "use_mask", use_mask, 2 ); - } - } - return 0; -} - - -void CvArrTest::clear() -{ - if( test_array ) - { - int i, j, n; - - for( i = 0; i < max_arr; i++ ) - { - n = test_array[i].size(); - for( j = 0; j < n; j++ ) - cvRelease( &test_array[i][j] ); - } - } - delete[] hdr; - hdr = 0; - max_hdr = 0; - CvTest::clear(); -} - - -int CvArrTest::read_params( CvFileStorage* fs ) -{ - int code = CvTest::read_params( fs ); - if( code < 0 ) - return code; - - if( ts->get_testing_mode() == CvTS::CORRECTNESS_CHECK_MODE ) - { - min_log_array_size = cvReadInt( find_param( fs, "min_log_array_size" ), min_log_array_size ); - max_log_array_size = cvReadInt( find_param( fs, "max_log_array_size" ), max_log_array_size ); - test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count ); - test_case_count = cvRound( test_case_count*ts->get_test_case_count_scale() ); - - min_log_array_size = cvTsClipInt( min_log_array_size, 0, 20 ); - max_log_array_size = cvTsClipInt( max_log_array_size, min_log_array_size, 20 ); - test_case_count = cvTsClipInt( test_case_count, 0, 100000 ); - } - - return code; -} - - -void CvArrTest::get_test_array_types_and_sizes( int /*test_case_idx*/, CvSize** sizes, int** types ) -{ - CvRNG* rng = ts->get_rng(); - CvSize size; - double val; - int i, j; - - val = cvRandReal(rng) * (max_log_array_size - min_log_array_size) + min_log_array_size; - size.width = cvRound( exp(val*CV_LOG2) ); - val = cvRandReal(rng) * (max_log_array_size - min_log_array_size) + min_log_array_size; - size.height = cvRound( exp(val*CV_LOG2) ); - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - for( j = 0; j < count; j++ ) - { - sizes[i][j] = size; - types[i][j] = CV_8UC1; - } - } -} - - -void CvArrTest::get_timing_test_array_types_and_sizes( int /*test_case_idx*/, CvSize** sizes, int** types, - CvSize** whole_sizes, bool *are_images ) -{ - const CvFileNode* size_node = find_timing_param( "size" ); - const CvFileNode* depth_node = find_timing_param( "depth" ); - const CvFileNode* channels_node = find_timing_param( "channels" ); - int i, j; - int depth = 0, channels = 1; - CvSize size = {1,1}, whole_size = size; - - if( size_node && CV_NODE_IS_SEQ(size_node->tag) ) - { - CvSeq* seq = size_node->data.seq; - size.width = cvReadInt((const CvFileNode*)cvGetSeqElem(seq,0), 1); - size.height = cvReadInt((const CvFileNode*)cvGetSeqElem(seq,1), 1); - whole_size = size; - if( seq->total > 2 ) - { - whole_size.width = cvReadInt((const CvFileNode*)cvGetSeqElem(seq,2), 1); - whole_size.height = cvReadInt((const CvFileNode*)cvGetSeqElem(seq,3), 1); - whole_size.width = MAX( whole_size.width, size.width ); - whole_size.height = MAX( whole_size.height, size.height ); - } - } - - if( depth_node && CV_NODE_IS_STRING(depth_node->tag) ) - { - depth = cvTsTypeByName( depth_node->data.str.ptr ); - if( depth < 0 || depth > CV_64F ) - depth = 0; - } - - if( channels_node && CV_NODE_IS_INT(channels_node->tag) ) - { - channels = cvReadInt( channels_node, 1 ); - if( channels < 0 || channels > CV_CN_MAX ) - channels = 1; - } - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - for( j = 0; j < count; j++ ) - { - sizes[i][j] = size; - whole_sizes[i][j] = whole_size; - if( i != MASK ) - types[i][j] = CV_MAKETYPE(depth,channels); - else - types[i][j] = CV_8UC1; - if( i == REF_OUTPUT || i == REF_INPUT_OUTPUT ) - sizes[i][j] = cvSize(0,0); - } - } - - if( are_images ) - *are_images = false; // by default CvMat is used in performance tests -} - - -void CvArrTest::print_timing_params( int /*test_case_idx*/, char* ptr, int params_left ) -{ - int i; - for( i = 0; i < params_left; i++ ) - { - sprintf( ptr, "-," ); - ptr += 2; - } -} - - -void CvArrTest::print_time( int test_case_idx, double time_clocks, double time_cpu_clocks ) -{ - int in_type = -1, out_type = -1; - CvSize size = { -1, -1 }; - const CvFileNode* size_node = find_timing_param( "size" ); - char str[1024], *ptr = str; - int len; - bool have_mask; - double cpe; - - if( size_node ) - { - if( !CV_NODE_IS_SEQ(size_node->tag) ) - { - size.width = cvReadInt(size_node,-1); - size.height = 1; - } - else - { - size.width = cvReadInt((const CvFileNode*)cvGetSeqElem(size_node->data.seq,0),-1); - size.height = cvReadInt((const CvFileNode*)cvGetSeqElem(size_node->data.seq,1),-1); - } - } - - if( test_array[INPUT].size() ) - { - in_type = CV_MAT_TYPE(test_mat[INPUT][0].type); - if( size.width == -1 ) - size = cvGetMatSize(&test_mat[INPUT][0]); - } - - if( test_array[OUTPUT].size() ) - { - out_type = CV_MAT_TYPE(test_mat[OUTPUT][0].type); - if( in_type < 0 ) - in_type = out_type; - if( size.width == -1 ) - size = cvGetMatSize(&test_mat[OUTPUT][0]); - } - - if( out_type < 0 && test_array[INPUT_OUTPUT].size() ) - { - out_type = CV_MAT_TYPE(test_mat[INPUT_OUTPUT][0].type); - if( in_type < 0 ) - in_type = out_type; - if( size.width == -1 ) - size = cvGetMatSize(&test_mat[INPUT_OUTPUT][0]); - } - - have_mask = test_array[MASK].size() > 0 && test_array[MASK][0] != 0; - - if( in_type < 0 && out_type < 0 ) - return; - - if( out_type < 0 ) - out_type = in_type; - - ptr = strchr( (char*)tested_functions, ',' ); - if( ptr ) - { - len = (int)(ptr - tested_functions); - strncpy( str, tested_functions, len ); - } - else - { - len = (int)strlen( tested_functions ); - strcpy( str, tested_functions ); - } - ptr = str + len; - *ptr = '\0'; - if( have_mask ) - { - sprintf( ptr, "(Mask)" ); - ptr += strlen(ptr); - } - *ptr++ = ','; - sprintf( ptr, "%s", cvTsGetTypeName(in_type) ); - ptr += strlen(ptr); - - if( CV_MAT_DEPTH(out_type) != CV_MAT_DEPTH(in_type) ) - { - sprintf( ptr, "%s", cvTsGetTypeName(out_type) ); - ptr += strlen(ptr); - } - *ptr++ = ','; - - sprintf( ptr, "C%d", CV_MAT_CN(in_type) ); - ptr += strlen(ptr); - - if( CV_MAT_CN(out_type) != CV_MAT_CN(in_type) ) - { - sprintf( ptr, "C%d", CV_MAT_CN(out_type) ); - ptr += strlen(ptr); - } - *ptr++ = ','; - - sprintf( ptr, "%dx%d,", size.width, size.height ); - ptr += strlen(ptr); - - print_timing_params( test_case_idx, ptr ); - ptr += strlen(ptr); - cpe = time_cpu_clocks / ((double)size.width * size.height); - if( cpe >= 100 ) - sprintf( ptr, "%.0f,", cpe ); - else - sprintf( ptr, "%.1f,", cpe ); - ptr += strlen(ptr); - sprintf( ptr, "%g", time_clocks*1e6/cv::getTickFrequency() ); - - ts->printf( CvTS::CSV, "%s\n", str ); -} - - -static const int icvTsTypeToDepth[] = -{ - IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U, IPL_DEPTH_16S, - IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F -}; - - -int CvArrTest::prepare_test_case( int test_case_idx ) -{ - int code = 1; - CvSize** sizes = (CvSize**)malloc( max_arr*sizeof(sizes[0]) ); - CvSize** whole_sizes = (CvSize**)malloc( max_arr*sizeof(whole_sizes[0]) ); - int** types = (int**)malloc( max_arr*sizeof(types[0]) ); - int i, j, total = 0; - CvRNG* rng = ts->get_rng(); - bool is_image = false; - bool is_timing_test = false; - - CV_FUNCNAME( "CvArrTest::prepare_test_case" ); - - __BEGIN__; - - is_timing_test = ts->get_testing_mode() == CvTS::TIMING_MODE; - - if( is_timing_test ) - { - if( !get_next_timing_param_tuple() ) - { - code = -1; - EXIT; - } - } - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - count = MAX(count, 1); - sizes[i] = (CvSize*)malloc( count*sizeof(sizes[i][0]) ); - types[i] = (int*)malloc( count*sizeof(types[i][0]) ); - whole_sizes[i] = (CvSize*)malloc( count*sizeof(whole_sizes[i][0]) ); - } - - if( !is_timing_test ) - get_test_array_types_and_sizes( test_case_idx, sizes, types ); - else - { - get_timing_test_array_types_and_sizes( test_case_idx, sizes, types, - whole_sizes, &is_image ); - } - - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - total += count; - for( j = 0; j < count; j++ ) - { - unsigned t = cvRandInt(rng); - bool create_mask = true, use_roi = false; - CvSize size = sizes[i][j], whole_size = size; - CvRect roi = {0,0,0,0}; - - if( !is_timing_test ) - { - is_image = !cvmat_allowed ? true : iplimage_allowed ? (t & 1) != 0 : false; - create_mask = (t & 6) == 0; // ~ each of 3 tests will use mask - use_roi = (t & 8) != 0; - if( use_roi ) - { - whole_size.width += cvRandInt(rng) % 10; - whole_size.height += cvRandInt(rng) % 10; - } - } - else - { - whole_size = whole_sizes[i][j]; - use_roi = whole_size.width != size.width || whole_size.height != size.height; - create_mask = cvReadInt(find_timing_param( "use_mask" ),0) != 0; - } - - cvRelease( &test_array[i][j] ); - if( size.width > 0 && size.height > 0 && - types[i][j] >= 0 && (i != MASK || create_mask) ) - { - if( use_roi ) - { - roi.width = size.width; - roi.height = size.height; - if( whole_size.width > size.width ) - { - if( !is_timing_test ) - roi.x = cvRandInt(rng) % (whole_size.width - size.width); - else - roi.x = 1; - } - - if( whole_size.height > size.height ) - { - if( !is_timing_test ) - roi.y = cvRandInt(rng) % (whole_size.height - size.height); - else - roi.y = 1; - } - } - - if( is_image ) - { - CV_CALL( test_array[i][j] = cvCreateImage( whole_size, - icvTsTypeToDepth[CV_MAT_DEPTH(types[i][j])], - CV_MAT_CN(types[i][j]) )); - if( use_roi ) - cvSetImageROI( (IplImage*)test_array[i][j], roi ); - } - else - { - CV_CALL( test_array[i][j] = cvCreateMat( whole_size.height, - whole_size.width, types[i][j] )); - if( use_roi ) - { - CvMat submat, *mat = (CvMat*)test_array[i][j]; - cvGetSubRect( test_array[i][j], &submat, roi ); - submat.refcount = mat->refcount; - *mat = submat; - } - } - } - } - } - - if( total > max_hdr ) - { - delete hdr; - max_hdr = total; - hdr = new CvMat[max_hdr]; - } - - total = 0; - for( i = 0; i < max_arr; i++ ) - { - int count = test_array[i].size(); - test_mat[i] = count > 0 ? hdr + total : 0; - for( j = 0; j < count; j++ ) - { - CvArr* arr = test_array[i][j]; - CvMat* mat = &test_mat[i][j]; - if( !arr ) - memset( mat, 0, sizeof(*mat) ); - else if( CV_IS_MAT( arr )) - { - *mat = *(CvMat*)arr; - mat->refcount = 0; - } - else - cvGetMat( arr, mat, 0, 0 ); - if( mat->data.ptr ) - fill_array( test_case_idx, i, j, mat ); - } - total += count; - } - - __END__; - - for( i = 0; i < max_arr; i++ ) - { - if( sizes ) - free( sizes[i] ); - if( whole_sizes ) - free( whole_sizes[i] ); - if( types ) - free( types[i] ); - } - - free( sizes ); - free( whole_sizes ); - free( types ); - - return code; -} - - -void CvArrTest::get_minmax_bounds( int i, int /*j*/, int type, CvScalar* low, CvScalar* high ) -{ - double l, u; - - if( i == MASK ) - { - l = -2; - u = 2; - } - else - { - l = cvTsMinVal(type); - u = cvTsMaxVal(type); - } - - *low = cvScalarAll(l); - *high = cvScalarAll(u); -} - - -void CvArrTest::fill_array( int /*test_case_idx*/, int i, int j, CvMat* arr ) -{ - if( i == REF_INPUT_OUTPUT ) - cvTsCopy( &test_mat[INPUT_OUTPUT][j], arr, 0 ); - else if( i == INPUT || i == INPUT_OUTPUT || i == MASK ) - { - int type = cvGetElemType( arr ); - CvScalar low, high; - - get_minmax_bounds( i, j, type, &low, &high ); - cvTsRandUni( ts->get_rng(), arr, low, high ); - } -} - - -double CvArrTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - int elem_depth = CV_MAT_DEPTH(cvGetElemType(test_array[i][j])); - assert( i == OUTPUT || i == INPUT_OUTPUT ); - return elem_depth < CV_32F ? 0 : elem_depth == CV_32F ? FLT_EPSILON*100: DBL_EPSILON*5000; -} - - -void CvArrTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - assert(0); -} - - -int CvArrTest::validate_test_results( int test_case_idx ) -{ - static const char* arr_names[] = { "input", "input/output", "output", - "ref input/output", "ref output", - "temporary", "mask" }; - int i, j; - prepare_to_validation( test_case_idx ); - - for( i = 0; i < 2; i++ ) - { - int i0 = i == 0 ? OUTPUT : INPUT_OUTPUT; - int i1 = i == 0 ? REF_OUTPUT : REF_INPUT_OUTPUT; - int count = test_array[i0].size(); - - assert( count == test_array[i1].size() ); - for( j = 0; j < count; j++ ) - { - double err_level; - CvPoint idx = {0,0}; - double max_diff = 0; - int code; - char msg[100]; - - if( !test_array[i1][j] ) - continue; - - err_level = get_success_error_level( test_case_idx, i0, j ); - code = cvTsCmpEps( &test_mat[i0][j], &test_mat[i1][j], &max_diff, err_level, &idx, - element_wise_relative_error ); - - switch( code ) - { - case -1: - sprintf( msg, "Too big difference (=%g)", max_diff ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - case -2: - strcpy( msg, "Invalid output" ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - case -3: - strcpy( msg, "Invalid output in the reference array" ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - default: - continue; - } - ts->printf( CvTS::LOG, "%s in %s array %d at (%d,%d)\n", msg, - arr_names[i0], j, idx.x, idx.y ); - for( i0 = 0; i0 < max_arr; i0++ ) - { - int count = test_array[i0].size(); - if( i0 == REF_INPUT_OUTPUT || i0 == OUTPUT || i0 == TEMP ) - continue; - for( i1 = 0; i1 < count; i1++ ) - { - CvArr* arr = test_array[i0][i1]; - if( arr ) - { - CvSize size = cvGetSize(arr); - int type = cvGetElemType(arr); - ts->printf( CvTS::LOG, "%s array %d type=%sC%d, size=(%d,%d)\n", - arr_names[i0], i1, cvTsGetTypeName(type), - CV_MAT_CN(type), size.width, size.height ); - } - } - } - ts->set_failed_test_info( code ); - return code; - } - } - - return 0; -} - -/* End of file. */ diff --git a/tests/cxts/cxts_math.cpp b/tests/cxts/cxts_math.cpp deleted file mode 100644 index 1fad827..0000000 --- a/tests/cxts/cxts_math.cpp +++ /dev/null @@ -1,3429 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "_cxts.h" - -/****************************************************************************************\ -* Utility Functions * -\****************************************************************************************/ - -const char* cvTsGetTypeName( int type ) -{ - static const char* type_names[] = { "8u", "8s", "16u", "16s", "32s", "32f", "64f", "ptr" }; - return type_names[CV_MAT_DEPTH(type)]; -} - - -int cvTsTypeByName( const char* name ) -{ - int i; - for( i = 0; i < CV_DEPTH_MAX; i++ ) - if( strcmp(name, cvTsGetTypeName(i)) == 0 ) - return i; - return -1; -} - - -void cvTsRandUni( CvRNG* rng, CvMat* a, CvScalar param0, CvScalar param1 ) -{ - int i, j, k, cn, ncols; - CvScalar scale = param0; - CvScalar delta = param1; - double C = 1./(65536.*65536.); - - cn = CV_MAT_CN(a->type); - ncols = a->cols*cn; - - for( k = 0; k < 4; k++ ) - { - double s = scale.val[k] - delta.val[k]; - if( s >= 0 ) - scale.val[k] = s; - else - { - delta.val[k] = scale.val[k]; - scale.val[k] = -s; - } - scale.val[k] *= C; - } - - for( i = 0; i < a->rows; i++ ) - { - uchar* data = a->data.ptr + i*a->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - int val = cvFloor( cvTsRandInt(rng)*scale.val[k] + delta.val[k] ); - ((uchar*)data)[j + k] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - int val = cvFloor( cvTsRandInt(rng)*scale.val[k] + delta.val[k] ); - ((schar*)data)[j + k] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - int val = cvFloor( cvTsRandInt(rng)*scale.val[k] + delta.val[k] ); - ((ushort*)data)[j + k] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - int val = cvFloor( cvTsRandInt(rng)*scale.val[k] + delta.val[k] ); - ((short*)data)[j + k] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - int val = cvFloor( cvTsRandInt(rng)*scale.val[k] + delta.val[k] ); - ((int*)data)[j + k] = val; - } - break; - case CV_32F: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - double val = cvTsRandInt(rng)*scale.val[k] + delta.val[k]; - ((float*)data)[j + k] = (float)val; - } - break; - case CV_64F: - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - { - double val = cvTsRandInt(rng); - val = (val + cvTsRandInt(rng)*C)*scale.val[k] + delta.val[k]; - ((double*)data)[j + k] = val; - } - break; - default: - assert(0); - return; - } - } -} - - -void cvTsZero( CvMat* c, const CvMat* mask ) -{ - int i, j, elem_size = CV_ELEM_SIZE(c->type), width = c->cols; - - for( i = 0; i < c->rows; i++ ) - { - if( !mask ) - memset( c->data.ptr + i*c->step, 0, width*elem_size ); - else - { - const uchar* mrow = mask->data.ptr + mask->step*i; - uchar* cptr = c->data.ptr + c->step*i; - for( j = 0; j < width; j++, cptr += elem_size ) - if( mrow[j] ) - memset( cptr, 0, elem_size ); - } - } -} - - -// initializes scaled identity matrix -void cvTsSetIdentity( CvMat* c, CvScalar diag_value ) -{ - int i, width; - cvTsZero( c ); - width = MIN(c->rows, c->cols); - for( i = 0; i < width; i++ ) - cvSet2D( c, i, i, diag_value ); -} - - -// copies selected region of one array to another array -void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask ) -{ - int i = 0, j = 0, k; - int el_size, ncols; - - el_size = CV_ELEM_SIZE(a->type); - ncols = a->cols; - if( mask ) - { - assert( CV_ARE_SIZES_EQ(a,mask) && - (CV_MAT_TYPE(mask->type) == CV_8UC1 || - CV_MAT_TYPE(mask->type) == CV_8SC1 )); - } - - assert( CV_ARE_TYPES_EQ(a,b) && CV_ARE_SIZES_EQ(a,b) ); - - if( !mask ) - ncols *= el_size; - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - - if( !mask ) - memcpy( b_data, a_data, ncols ); - else - { - uchar* m_data = mask->data.ptr + mask->step*i; - - for( j = 0; j < ncols; j++, b_data += el_size, a_data += el_size ) - { - if( m_data[j] ) - { - for( k = 0; k < el_size; k++ ) - b_data[k] = a_data[k]; - } - } - } - } -} - - -void cvTsConvert( const CvMat* a, CvMat* b ) -{ - int i, j, ncols = b->cols*CV_MAT_CN(b->type); - double* buf = 0; - - assert( CV_ARE_SIZES_EQ(a,b) && CV_ARE_CNS_EQ(a,b) ); - buf = (double*)cvStackAlloc(ncols*sizeof(buf[0])); - - for( i = 0; i < b->rows; i++ ) - { - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - buf[j] = ((uchar*)a_data)[j]; - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((schar*)a_data)[j]; - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - buf[j] = ((ushort*)a_data)[j]; - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((short*)a_data)[j]; - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((int*)a_data)[j]; - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - buf[j] = ((float*)a_data)[j]; - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - buf[j] = ((double*)a_data)[j]; - break; - default: - assert(0); - return; - } - - switch( CV_MAT_DEPTH(b->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((uchar*)b_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((schar*)b_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((ushort*)b_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((short*)b_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((int*)b_data)[j] = CV_CAST_32S(val); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - ((float*)b_data)[j] = CV_CAST_32F(buf[j]); - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - ((double*)b_data)[j] = CV_CAST_64F(buf[j]); - break; - default: - assert(0); - } - } -} - - -// extracts a single channel from a multi-channel array -void cvTsExtract( const CvMat* a, CvMat* b, int coi ) -{ - int i = 0, j = 0, k; - int el_size, el_size1, ncols; - - el_size = CV_ELEM_SIZE(a->type); - el_size1 = CV_ELEM_SIZE(b->type); - ncols = a->cols; - - assert( CV_ARE_DEPTHS_EQ(a,b) && CV_ARE_SIZES_EQ(a,b) && - (unsigned)coi < (unsigned)CV_MAT_CN(a->type) && - CV_MAT_CN(b->type) == 1 ); - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - a_data += el_size1*coi; - for( j = 0; j < ncols; j++, b_data += el_size1, a_data += el_size ) - { - for( k = 0; k < el_size1; k++ ) - b_data[k] = a_data[k]; - } - } -} - -// replaces a single channel in a multi-channel array -void cvTsInsert( const CvMat* a, CvMat* b, int coi ) -{ - int i = 0, j = 0, k; - int el_size, el_size1, ncols; - - el_size = CV_ELEM_SIZE(b->type); - el_size1 = CV_ELEM_SIZE(a->type); - ncols = a->cols; - - assert( CV_ARE_DEPTHS_EQ(a,b) && CV_ARE_SIZES_EQ(a,b) && - (unsigned)coi < (unsigned)CV_MAT_CN(b->type) && - CV_MAT_CN(a->type) == 1 ); - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - b_data += el_size1*coi; - for( j = 0; j < ncols; j++, b_data += el_size, a_data += el_size1 ) - { - for( k = 0; k < el_size1; k++ ) - b_data[k] = a_data[k]; - } - } -} - - -// c = alpha*a + beta*b + gamma -void cvTsAdd( const CvMat* a, CvScalar alpha, const CvMat* b, CvScalar beta, - CvScalar gamma, CvMat* c, int calc_abs ) -{ - int i, j, k, cn, ncols; - double* buf = 0; - double* alpha_buf = 0; - double* beta_buf = 0; - double* gamma_buf = 0; - - if( !c ) - { - assert(0); - return; - } - - cn = CV_MAT_CN(c->type); - ncols = c->cols; - - if( !a ) - { - a = b; - alpha = beta; - b = 0; - beta = cvScalar(0); - } - - if( a ) - { - assert( CV_ARE_SIZES_EQ(a,c) && CV_MAT_CN(a->type) == cn ); - buf = (double*)malloc( a->cols * cn * sizeof(buf[0]) ); - alpha_buf = (double*)malloc( a->cols * cn * sizeof(alpha_buf[0]) ); - } - - if( b ) - { - assert( CV_ARE_SIZES_EQ(b,c) && CV_MAT_CN(b->type) == cn ); - beta_buf = (double*)malloc( b->cols * cn * sizeof(beta_buf[0]) ); - } - - ncols *= cn; - gamma_buf = (double*)malloc( ncols * sizeof(gamma_buf[0]) ); - if( !buf ) - buf = gamma_buf; - - if( !a && !b && calc_abs ) - { - for( k = 0; k < cn; k++ ) - gamma.val[k] = fabs(gamma.val[k]); - } - - for( i = 0; i < 1 + (a != 0) + (b != 0); i++ ) - { - double* scalar_buf = i == 0 ? gamma_buf : i == 1 ? alpha_buf : beta_buf; - CvScalar scalar = i == 0 ? gamma : i == 1 ? alpha : beta; - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - scalar_buf[j + k] = scalar.val[k]; - } - - for( i = 0; i < c->rows; i++ ) - { - uchar* c_data = c->data.ptr + i*c->step; - - if( a ) - { - uchar* a_data = a->data.ptr + i*a->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - buf[j] = ((uchar*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((schar*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - buf[j] = ((ushort*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((short*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - buf[j] = ((int*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - buf[j] = ((float*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - buf[j] = ((double*)a_data)[j]*alpha_buf[j] + gamma_buf[j]; - break; - default: - assert(0); - return; - } - } - - if( b ) - { - uchar* b_data = b->data.ptr + i*b->step; - - switch( CV_MAT_DEPTH(b->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - buf[j] += ((uchar*)b_data)[j]*beta_buf[j]; - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - buf[j] += ((schar*)b_data)[j]*beta_buf[j]; - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - buf[j] += ((ushort*)b_data)[j]*beta_buf[j]; - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - buf[j] += ((short*)b_data)[j]*beta_buf[j]; - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - buf[j] += ((int*)b_data)[j]*beta_buf[j]; - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - buf[j] += ((float*)b_data)[j]*beta_buf[j]; - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - buf[j] += ((double*)b_data)[j]*beta_buf[j]; - break; - default: - assert(0); - return; - } - } - - if( a || b ) - { - if( calc_abs ) - { - for( j = 0; j < ncols; j++ ) - buf[j] = fabs(buf[j]); - } - } - else if( i > 0 ) - { - memcpy( c_data, c_data - c->step, c->cols*CV_ELEM_SIZE(c->type) ); - continue; - } - - switch( CV_MAT_DEPTH(c->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((uchar*)c_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((schar*)c_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((ushort*)c_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((short*)c_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((int*)c_data)[j] = CV_CAST_32S(val); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - ((float*)c_data)[j] = CV_CAST_32F(buf[j]); - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - ((double*)c_data)[j] = CV_CAST_64F(buf[j]); - break; - default: - assert(0); - } - } - - if( buf && buf != gamma_buf ) - free( buf ); - if( gamma_buf ) - free( gamma_buf ); - if( alpha_buf ) - free( alpha_buf ); - if( beta_buf ) - free( beta_buf ); -} - - -// c = a*b*alpha -void cvTsMul( const CvMat* a, const CvMat* b, CvScalar alpha, CvMat* c ) -{ - int i, j, k, cn, ncols; - double* buf = 0; - double* alpha_buf = 0; - - if( !a || !b || !c ) - { - assert(0); - return; - } - - assert( CV_ARE_SIZES_EQ(a,c) && CV_ARE_SIZES_EQ(b,c) && - CV_ARE_TYPES_EQ(a,b) && CV_ARE_CNS_EQ(a,c) ); - - cn = CV_MAT_CN(c->type); - ncols = c->cols * cn; - alpha_buf = (double*)malloc( ncols * sizeof(alpha_buf[0]) ); - buf = (double*)malloc( ncols * sizeof(buf[0]) ); - - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - alpha_buf[j + k] = alpha.val[k]; - - for( i = 0; i < c->rows; i++ ) - { - uchar* c_data = c->data.ptr + i*c->step; - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((uchar*)a_data)[j])*((uchar*)b_data)[j]; - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((schar*)a_data)[j])*((schar*)b_data)[j]; - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((ushort*)a_data)[j])*((ushort*)b_data)[j]; - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((short*)a_data)[j])*((short*)b_data)[j]; - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((int*)a_data)[j])*((int*)b_data)[j]; - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((float*)a_data)[j])*((float*)b_data)[j]; - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - buf[j] = (alpha_buf[j]*((double*)a_data)[j])*((double*)b_data)[j]; - break; - default: - assert(0); - return; - } - - switch( CV_MAT_DEPTH(c->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((uchar*)c_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((schar*)c_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((ushort*)c_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((short*)c_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((int*)c_data)[j] = CV_CAST_32S(val); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - ((float*)c_data)[j] = CV_CAST_32F(buf[j]); - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - ((double*)c_data)[j] = CV_CAST_64F(buf[j]); - break; - default: - assert(0); - } - } - - if( alpha_buf ) - free( alpha_buf ); - - if( buf ) - free( buf ); -} - - -// c = a*alpha/b -void cvTsDiv( const CvMat* a, const CvMat* b, CvScalar alpha, CvMat* c ) -{ - int i, j, k, cn, ncols; - double* buf = 0; - double* alpha_buf = 0; - - if( !b || !c ) - { - assert(0); - return; - } - - if( a ) - { - assert( CV_ARE_SIZES_EQ(a,c) && - CV_ARE_TYPES_EQ(a,b) && CV_ARE_CNS_EQ(a,c) ); - } - - assert( CV_ARE_SIZES_EQ(b,c) && CV_ARE_CNS_EQ(b,c) ); - - cn = CV_MAT_CN(c->type); - ncols = c->cols * cn; - alpha_buf = (double*)malloc( ncols * sizeof(alpha_buf[0]) ); - buf = (double*)malloc( ncols * sizeof(buf[0]) ); - - for( j = 0; j < ncols; j += cn ) - for( k = 0; k < cn; k++ ) - alpha_buf[j + k] = alpha.val[k]; - - for( i = 0; i < c->rows; i++ ) - { - uchar* c_data = c->data.ptr + i*c->step; - uchar* a_data = a ? a->data.ptr + i*a->step : 0; - uchar* b_data = b->data.ptr + i*b->step; - - switch( CV_MAT_DEPTH(b->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int denom = ((uchar*)b_data)[j]; - int num = a_data ? ((uchar*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int denom = ((schar*)b_data)[j]; - int num = a_data ? ((schar*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int denom = ((ushort*)b_data)[j]; - int num = a_data ? ((ushort*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int denom = ((short*)b_data)[j]; - int num = a_data ? ((short*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int denom = ((int*)b_data)[j]; - int num = a_data ? ((int*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - double denom = ((float*)b_data)[j]; - double num = a_data ? ((float*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double denom = ((double*)b_data)[j]; - double num = a_data ? ((double*)a_data)[j] : 1; - buf[j] = !denom ? 0 : (alpha_buf[j]*num/denom); - } - break; - default: - assert(0); - return; - } - - switch( CV_MAT_DEPTH(c->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((uchar*)c_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((schar*)c_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((ushort*)c_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((short*)c_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int val = cvRound(buf[j]); - ((int*)c_data)[j] = CV_CAST_32S(val); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - ((float*)c_data)[j] = CV_CAST_32F(buf[j]); - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - ((double*)c_data)[j] = CV_CAST_64F(buf[j]); - break; - default: - assert(0); - } - } - - if( alpha_buf ) - free( alpha_buf ); - - if( buf ) - free( buf ); -} - - -// c = min(a,b) or c = max(a,b) -void cvTsMinMax( const CvMat* a, const CvMat* b, CvMat* c, int op_type ) -{ - int i, j, ncols; - int calc_max = op_type == CV_TS_MAX; - - if( !a || !b || !c ) - { - assert(0); - return; - } - - assert( CV_ARE_SIZES_EQ(a,c) && CV_ARE_TYPES_EQ(a,c) && - CV_ARE_SIZES_EQ(b,c) && CV_ARE_TYPES_EQ(b,c) && - CV_MAT_CN(a->type) == 1 ); - ncols = c->cols; - - for( i = 0; i < c->rows; i++ ) - { - uchar* c_data = c->data.ptr + i*c->step; - uchar* a_data = a->data.ptr + i*a->step; - uchar* b_data = b->data.ptr + i*b->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int aj = ((uchar*)a_data)[j]; - int bj = ((uchar*)b_data)[j]; - ((uchar*)c_data)[j] = (uchar)(calc_max ? MAX(aj, bj) : MIN(aj,bj)); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((schar*)a_data)[j]; - int bj = ((schar*)b_data)[j]; - ((schar*)c_data)[j] = (schar)(calc_max ? MAX(aj, bj) : MIN(aj,bj)); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int aj = ((ushort*)a_data)[j]; - int bj = ((ushort*)b_data)[j]; - ((ushort*)c_data)[j] = (ushort)(calc_max ? MAX(aj, bj) : MIN(aj,bj)); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((short*)a_data)[j]; - int bj = ((short*)b_data)[j]; - ((short*)c_data)[j] = (short)(calc_max ? MAX(aj, bj) : MIN(aj,bj)); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((int*)a_data)[j]; - int bj = ((int*)b_data)[j]; - ((int*)c_data)[j] = calc_max ? MAX(aj, bj) : MIN(aj,bj); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - float aj = ((float*)a_data)[j]; - float bj = ((float*)b_data)[j]; - ((float*)c_data)[j] = calc_max ? MAX(aj, bj) : MIN(aj,bj); - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double aj = ((double*)a_data)[j]; - double bj = ((double*)b_data)[j]; - ((double*)c_data)[j] = calc_max ? MAX(aj, bj) : MIN(aj,bj); - } - break; - default: - assert(0); - return; - } - } -} - -// c = min(a,b) or c = max(a,b) -void cvTsMinMaxS( const CvMat* a, double s, CvMat* c, int op_type ) -{ - int i, j, ncols; - int calc_max = op_type == CV_TS_MAX; - float fs = (float)s; - int is = cvRound(s); - - if( !a || !c ) - { - assert(0); - return; - } - - assert( CV_ARE_SIZES_EQ(a,c) && CV_ARE_TYPES_EQ(a,c) && - CV_MAT_CN(a->type) == 1 ); - ncols = c->cols; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - is = CV_CAST_8U(is); - break; - case CV_8S: - is = CV_CAST_8S(is); - break; - case CV_16U: - is = CV_CAST_16U(is); - break; - case CV_16S: - is = CV_CAST_16S(is); - break; - default: - ; - } - - for( i = 0; i < c->rows; i++ ) - { - uchar* c_data = c->data.ptr + i*c->step; - uchar* a_data = a->data.ptr + i*a->step; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int aj = ((uchar*)a_data)[j]; - ((uchar*)c_data)[j] = (uchar)(calc_max ? MAX(aj, is) : MIN(aj, is)); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((schar*)a_data)[j]; - ((schar*)c_data)[j] = (schar)(calc_max ? MAX(aj, is) : MIN(aj, is)); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int aj = ((ushort*)a_data)[j]; - ((ushort*)c_data)[j] = (ushort)(calc_max ? MAX(aj, is) : MIN(aj, is)); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((short*)a_data)[j]; - ((short*)c_data)[j] = (short)(calc_max ? MAX(aj, is) : MIN(aj, is)); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int aj = ((int*)a_data)[j]; - ((int*)c_data)[j] = calc_max ? MAX(aj, is) : MIN(aj, is); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - float aj = ((float*)a_data)[j]; - ((float*)c_data)[j] = calc_max ? MAX(aj, fs) : MIN(aj, fs); - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double aj = ((double*)a_data)[j]; - ((double*)c_data)[j] = calc_max ? MAX(aj, s) : MIN(aj, s); - } - break; - default: - assert(0); - return; - } - } -} - -// checks that the array does not have NaNs and/or Infs and all the elements are -// within [min_val,max_val). idx is the index of the first "bad" element. -int cvTsCheck( const CvMat* a, double min_val, double max_val, CvPoint* idx ) -{ - int i = 0, j = 0; - int cn, ncols; - int imin = 0, imax = 0; - cn = CV_MAT_CN(a->type); - ncols = a->cols*cn; - - if( CV_MAT_DEPTH(a->type) <= CV_32S ) - { - imin = cvCeil(min_val); - imax = cvFloor(max_val); - } - - for( i = 0; i < a->rows; i++ ) - { - uchar* data = a->data.ptr + a->step*i; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = ((uchar*)data)[j]; - if( val < imin || imax < val ) - goto _exit_; - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = ((schar*)data)[j]; - if( val < imin || imax < val ) - goto _exit_; - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = ((ushort*)data)[j]; - if( val < imin || imax < val ) - goto _exit_; - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = ((short*)data)[j]; - if( val < imin || imax < val ) - goto _exit_; - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int val = ((int*)data)[j]; - if( val < imin || imax < val ) - goto _exit_; - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - double val = ((float*)data)[j]; - if( cvIsNaN(val) || cvIsInf(val) || val < min_val || max_val < val ) - goto _exit_; - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double val = ((double*)data)[j]; - if( cvIsNaN(val) || cvIsInf(val) || val < min_val || max_val < val ) - goto _exit_; - } - break; - default: - assert(0); - return -1; - } - } - - return 0; -_exit_: - - idx->x = j; - idx->y = i; - return -1; -} - -// compares two arrays. max_diff is the maximum actual difference, -// success_err_level is maximum allowed difference, idx is the index of the first -// element for which difference is >success_err_level -// (or index of element with the maximum difference) -int cvTsCmpEps( const CvMat* check_arr, const CvMat* etalon, double* _max_diff, - double success_err_level, CvPoint* _idx, bool element_wise_relative_error ) -{ - int i = 0, j = 0; - int cn, ncols; - double maxdiff = 0; - double maxval = 0; - int imaxdiff = 0; - int ilevel = 0; - int result = -1; - CvPoint stub, *idx = _idx ? _idx : &stub; - - cn = CV_MAT_CN(check_arr->type); - ncols = check_arr->cols*cn; - - *idx = cvPoint(0,0); - - assert( CV_ARE_TYPES_EQ(check_arr,etalon) && CV_ARE_SIZES_EQ(check_arr,etalon) ); - - if( CV_MAT_DEPTH(check_arr->type) < CV_32S ) - ilevel = cvFloor(success_err_level); - - if( CV_MAT_DEPTH(check_arr->type) >= CV_32F && !element_wise_relative_error ) - { - double maxval0 = 1.; - maxval = cvTsNorm( etalon, 0, CV_C, 0 ); - maxval = MAX(maxval, maxval0); - } - - for( i = 0; i < check_arr->rows; i++ ) - { - uchar* a_data = check_arr->data.ptr + check_arr->step*i; - uchar* b_data = etalon->data.ptr + etalon->step*i; - - switch( CV_MAT_DEPTH(check_arr->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int val = abs(((uchar*)a_data)[j] - ((uchar*)b_data)[j]); - if( val > imaxdiff ) - { - imaxdiff = val; - *idx = cvPoint(j,i); - if( val > ilevel ) - goto _exit_; - } - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int val = abs(((schar*)a_data)[j] - ((schar*)b_data)[j]); - if( val > imaxdiff ) - { - imaxdiff = val; - *idx = cvPoint(j,i); - if( val > ilevel ) - goto _exit_; - } - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int val = abs(((ushort*)a_data)[j] - ((ushort*)b_data)[j]); - if( val > imaxdiff ) - { - imaxdiff = val; - *idx = cvPoint(j,i); - if( val > ilevel ) - goto _exit_; - } - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int val = abs(((short*)a_data)[j] - ((short*)b_data)[j]); - if( val > imaxdiff ) - { - imaxdiff = val; - *idx = cvPoint(j,i); - if( val > ilevel ) - goto _exit_; - } - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - double val = fabs((double)((int*)a_data)[j] - (double)((int*)b_data)[j]); - if( val > maxdiff ) - { - maxdiff = val; - *idx = cvPoint(j,i); - if( val > success_err_level ) - goto _exit_; - } - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - double a_val = ((float*)a_data)[j]; - double b_val = ((float*)b_data)[j]; - double threshold; - if( ((int*)a_data)[j] == ((int*)b_data)[j] ) - continue; - if( cvIsNaN(a_val) || cvIsInf(a_val) ) - { - result = -2; - *idx = cvPoint(j,i); - goto _exit_; - } - if( cvIsNaN(b_val) || cvIsInf(b_val) ) - { - result = -3; - *idx = cvPoint(j,i); - goto _exit_; - } - a_val = fabs(a_val - b_val); - threshold = element_wise_relative_error ? fabs(b_val) + 1 : maxval; - if( a_val > threshold*success_err_level ) - { - maxdiff = a_val/threshold; - *idx = cvPoint(j,i); - goto _exit_; - } - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double a_val = ((double*)a_data)[j]; - double b_val = ((double*)b_data)[j]; - double threshold; - if( ((int64*)a_data)[j] == ((int64*)b_data)[j] ) - continue; - if( cvIsNaN(a_val) || cvIsInf(a_val) ) - { - result = -2; - *idx = cvPoint(j,i); - goto _exit_; - } - if( cvIsNaN(b_val) || cvIsInf(b_val) ) - { - result = -3; - *idx = cvPoint(j,i); - goto _exit_; - } - a_val = fabs(a_val - b_val); - threshold = element_wise_relative_error ? fabs(b_val) + 1 : maxval; - if( a_val > threshold*success_err_level ) - { - maxdiff = a_val/threshold; - *idx = cvPoint(j,i); - goto _exit_; - } - } - break; - default: - assert(0); - return -1; - } - } - - result = 0; -_exit_: - - if( CV_MAT_DEPTH(check_arr->type) < CV_32S ) - maxdiff = imaxdiff; - - if( result < -1 ) - maxdiff = exp(1000.); - *_max_diff = maxdiff; - return result; -} - - -int cvTsCmpEps2( CvTS* ts, const CvArr* _a, const CvArr* _b, double success_err_level, - bool element_wise_relative_error, const char* desc ) -{ - char msg[100]; - double diff = 0; - CvMat astub, bstub, *a, *b; - CvPoint idx = {0,0}; - int code; - - a = cvGetMat( _a, &astub ); - b = cvGetMat( _b, &bstub ); - code = cvTsCmpEps( a, b, &diff, success_err_level, &idx, - element_wise_relative_error ); - - switch( code ) - { - case -1: - sprintf( msg, "%s: Too big difference (=%g)", desc, diff ); - code = CvTS::FAIL_BAD_ACCURACY; - break; - case -2: - sprintf( msg, "%s: Invalid output", desc ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - case -3: - sprintf( msg, "%s: Invalid reference output", desc ); - code = CvTS::FAIL_INVALID_OUTPUT; - break; - default: - ; - } - - if( code < 0 ) - { - if( a->rows == 1 && a->cols == 1 ) - { - assert( idx.x == 0 && idx.y == 0 ); - ts->printf( CvTS::LOG, "%s\n", msg ); - } - else if( a->rows == 1 || a->cols == 1 ) - { - assert( idx.x == 0 || idx.y == 0 ); - ts->printf( CvTS::LOG, "%s at element %d\n", msg, idx.x + idx.y ); - } - else - ts->printf( CvTS::LOG, "%s at (%d,%d)\n", msg, idx.x, idx.y ); - } - - return code; -} - - -int cvTsCmpEps2_64f( CvTS* ts, const double* val, const double* ref_val, int len, - double eps, const char* param_name ) -{ - CvMat _val = cvMat( 1, len, CV_64F, (void*)val ); - CvMat _ref_val = cvMat( 1, len, CV_64F, (void*)ref_val ); - - return cvTsCmpEps2( ts, &_val, &_ref_val, eps, true, param_name ); -} - -// compares two arrays. the result is 8s image that takes values -1, 0, 1 -void cvTsCmp( const CvMat* a, const CvMat* b, CvMat* result, int cmp_op ) -{ - int i = 0, j = 0, ncols; - ncols = a->cols; - - assert( CV_ARE_TYPES_EQ(a,b) && CV_ARE_SIZES_EQ(a,b) && CV_MAT_CN(a->type) == 1 ); - assert( CV_ARE_SIZES_EQ(a,result) && - (CV_MAT_TYPE(result->type) == CV_8UC1 || - CV_MAT_TYPE(result->type) == CV_8SC1 )); - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - schar* r_data = (schar*)(result->data.ptr + result->step*i); - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((uchar*)a_data)[j]; - int b_val = ((uchar*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((schar*)a_data)[j]; - int b_val = ((schar*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((ushort*)a_data)[j]; - int b_val = ((ushort*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((short*)a_data)[j]; - int b_val = ((short*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((int*)a_data)[j]; - int b_val = ((int*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - float a_val = ((float*)a_data)[j]; - float b_val = ((float*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double a_val = ((double*)a_data)[j]; - double b_val = ((double*)b_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,b_val); - } - break; - default: - assert(0); - } - - switch( cmp_op ) - { - case CV_CMP_EQ: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] == 0 ? -1 : 0); - break; - case CV_CMP_NE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] != 0 ? -1 : 0); - break; - case CV_CMP_LT: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] < 0 ? -1 : 0); - break; - case CV_CMP_LE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] <= 0 ? -1 : 0); - break; - case CV_CMP_GE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] >= 0 ? -1 : 0); - break; - case CV_CMP_GT: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] > 0 ? -1 : 0); - break; - default: - ; - } - } -} - -// compares two arrays. the result is 8s image that takes values -1, 0, 1 -void cvTsCmpS( const CvMat* a, double fval, CvMat* result, int cmp_op ) -{ - int i = 0, j = 0; - int ncols, ival = 0; - ncols = a->cols; - - if( CV_MAT_DEPTH(a->type) <= CV_32S ) - ival = cvRound(fval); - - assert( CV_MAT_CN(a->type) == 1 ); - assert( CV_ARE_SIZES_EQ(a,result) && - (CV_MAT_TYPE(result->type) == CV_8UC1 || - CV_MAT_TYPE(result->type) == CV_8SC1 )); - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - schar* r_data = (schar*)(result->data.ptr + result->step*i); - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((uchar*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,ival); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((schar*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,ival); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((ushort*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,ival); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((short*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,ival); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int a_val = ((int*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,ival); - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - float a_val = ((float*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,fval); - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double a_val = ((double*)a_data)[j]; - r_data[j] = (schar)CV_CMP(a_val,fval); - } - break; - default: - assert(0); - } - - switch( cmp_op ) - { - case CV_CMP_EQ: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] == 0 ? -1 : 0); - break; - case CV_CMP_NE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] != 0 ? -1 : 0); - break; - case CV_CMP_LT: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] < 0 ? -1 : 0); - break; - case CV_CMP_LE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] <= 0 ? -1 : 0); - break; - case CV_CMP_GE: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] >= 0 ? -1 : 0); - break; - case CV_CMP_GT: - for( j = 0; j < ncols; j++ ) - r_data[j] = (schar)(r_data[j] > 0 ? -1 : 0); - break; - default: - ; - } - } -} - - -// calculates norm of a matrix -double cvTsNorm( const CvMat* arr, const CvMat* mask, int norm_type, int coi ) -{ - int i = 0, j = 0, k; - int depth, cn0, cn, ncols, el_size1; - int inorm = 0; - double fnorm = 0; - void* buffer = 0; - uchar* zerobuf = 0; - - cn0 = cn = CV_MAT_CN(arr->type); - ncols = arr->cols*cn; - depth = CV_MAT_DEPTH(arr->type); - el_size1 = CV_ELEM_SIZE(depth); - zerobuf = (uchar*)cvStackAlloc(el_size1*cn); - memset( zerobuf, 0, el_size1*cn); - - if( mask ) - { - assert( CV_ARE_SIZES_EQ( arr, mask ) && CV_IS_MASK_ARR(mask) ); - buffer = cvStackAlloc( el_size1*ncols ); - } - - if( coi == 0 ) - cn = 1; - - for( i = 0; i < arr->rows; i++ ) - { - const uchar* data = arr->data.ptr + arr->step*i + (coi - (coi != 0))*el_size1; - - if( mask ) - { - const uchar* mdata = mask->data.ptr + mask->step*i; - switch( depth ) - { - case CV_8U: - case CV_8S: - for( j = 0; j < ncols; j += cn0 ) - { - const uchar* src = *mdata++ ? (uchar*)data + j : zerobuf; - for( k = 0; k < cn0; k++ ) - ((uchar*)buffer)[j+k] = src[k]; - } - break; - case CV_16U: - case CV_16S: - for( j = 0; j < ncols; j += cn0 ) - { - const short* src = *mdata++ ? (short*)data + j : (short*)zerobuf; - for( k = 0; k < cn0; k++ ) - ((short*)buffer)[j+k] = src[k]; - } - break; - case CV_32S: - case CV_32F: - for( j = 0; j < ncols; j += cn0 ) - { - const int* src = *mdata++ ? (int*)data + j : (int*)zerobuf; - for( k = 0; k < cn0; k++ ) - ((int*)buffer)[j+k] = src[k]; - } - break; - case CV_64F: - for( j = 0; j < ncols; j += cn0 ) - { - const double* src = *mdata++ ? (double*)data + j : (double*)zerobuf; - for( k = 0; k < cn0; k++ ) - ((double*)buffer)[j+k] = src[k]; - } - break; - default: - assert(0); - return -1; - } - data = (const uchar*)buffer; - } - - switch( depth ) - { - case CV_8U: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - int val = ((const uchar*)data)[j]; - inorm = MAX( inorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = ((const uchar*)data)[j]; - inorm += val; - } - fnorm += inorm; - } - else - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = ((const uchar*)data)[j]; - inorm += val*val; - } - fnorm += inorm; - } - break; - case CV_8S: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - int val = abs(((const schar*)data)[j]); - inorm = MAX( inorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = abs(((const schar*)data)[j]); - inorm += val; - } - fnorm += inorm; - } - else - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = ((const schar*)data)[j]; - inorm += val*val; - } - fnorm += inorm; - } - break; - case CV_16U: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - int val = ((const ushort*)data)[j]; - inorm = MAX( inorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = ((const ushort*)data)[j]; - inorm += val; - } - fnorm += inorm; - } - else - { - for( j = 0; j < ncols; j += cn ) - { - double val = ((const ushort*)data)[j]; - fnorm += val*val; - } - } - break; - case CV_16S: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - int val = abs(((const short*)data)[j]); - inorm = MAX( inorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - inorm = 0; - for( j = 0; j < ncols; j += cn ) - { - int val = abs(((const short*)data)[j]); - inorm += val; - } - fnorm += inorm; - } - else - { - for( j = 0; j < ncols; j += cn ) - { - double val = ((const short*)data)[j]; - fnorm += val*val; - } - } - break; - case CV_32S: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - int val = abs(((const int*)data)[j]); - inorm = MAX( inorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - for( j = 0; j < ncols; j += cn ) - { - double val = fabs((double)((const int*)data)[j]); - fnorm += val; - } - } - else - { - for( j = 0; j < ncols; j += cn ) - { - double val = ((const int*)data)[j]; - fnorm += val*val; - } - } - break; - case CV_32F: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - double val = fabs((double)((const float*)data)[j]); - fnorm = MAX( fnorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - for( j = 0; j < ncols; j += cn ) - { - double val = fabs((double)((const float*)data)[j]); - fnorm += val; - } - } - else - { - for( j = 0; j < ncols; j += cn ) - { - double val = ((const float*)data)[j]; - fnorm += val*val; - } - } - break; - case CV_64F: - if( norm_type == CV_C ) - { - for( j = 0; j < ncols; j += cn ) - { - double val = fabs(((const double*)data)[j]); - fnorm = MAX( fnorm, val ); - } - } - else if( norm_type == CV_L1 ) - { - for( j = 0; j < ncols; j += cn ) - { - double val = fabs(((const double*)data)[j]); - fnorm += val; - } - } - else - { - for( j = 0; j < ncols; j += cn ) - { - double val = ((const double*)data)[j]; - fnorm += val*val; - } - } - break; - default: - assert(0); - return -1; - } - } - - if( norm_type == CV_L2 ) - fnorm = sqrt( fnorm ); - else if( depth < CV_32F && norm_type == CV_C ) - fnorm = inorm; - - return fnorm; -} - - -// retrieves mean, standard deviation and the number of nonzero mask pixels -int cvTsMeanStdDevNonZero( const CvMat* arr, const CvMat* mask, - CvScalar* _mean, CvScalar* _stddev, int coi ) -{ - int i = 0, j = 0, k; - int depth, cn0, cn, cols, ncols, el_size1; - CvScalar sum = cvScalar(0), sqsum = cvScalar(0); - double inv_area; - int isum[4], isqsum[4]; - int nonzero = 0; - uchar* maskbuf = 0; - - cn0 = cn = CV_MAT_CN(arr->type); - cols = arr->cols; - ncols = arr->cols*cn; - depth = CV_MAT_DEPTH(arr->type); - el_size1 = CV_ELEM_SIZE(depth); - if( mask ) - { - assert( CV_ARE_SIZES_EQ( arr, mask ) && CV_IS_MASK_ARR(mask) ); - } - else - { - maskbuf = (uchar*)cvStackAlloc( cols ); - memset( maskbuf, 1, cols ); - nonzero = cols*arr->rows; - } - - if( coi != 0 ) - cn = 1; - - for( i = 0; i < arr->rows; i++ ) - { - const uchar* data = arr->data.ptr + arr->step*i + (coi - (coi != 0))*el_size1; - const uchar* mdata; - - if( mask ) - { - mdata = mask->data.ptr + mask->step*i; - for( j = 0; j < cols; j++ ) - nonzero += mdata[j] != 0; - } - else - { - mdata = maskbuf; - } - - // if only a number of pixels in the mask is needed, skip the rest of the loop body - if( !_mean && !_stddev ) - continue; - - switch( depth ) - { - case CV_8U: - for( k = 0; k < cn; k++ ) - isum[k] = isqsum[k] = 0; - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - int val = ((const uchar*)data)[j+k]; - isum[k] += val; - isqsum[k] += val*val; - } - } - for( k = 0; k < cn; k++ ) - { - sum.val[k] += isum[k]; - sqsum.val[k] += isqsum[k]; - } - break; - case CV_8S: - for( k = 0; k < cn; k++ ) - isum[k] = isqsum[k] = 0; - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - int val = ((const schar*)data)[j+k]; - isum[k] += val; - isqsum[k] += val*val; - } - } - for( k = 0; k < cn; k++ ) - { - sum.val[k] += isum[k]; - sqsum.val[k] += isqsum[k]; - } - break; - case CV_16U: - for( k = 0; k < cn; k++ ) - isum[k] = 0; - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - int val = ((const ushort*)data)[j+k]; - isum[k] += val; - sqsum.val[k] += ((double)val)*val; - } - } - for( k = 0; k < cn; k++ ) - sum.val[k] += isum[k]; - break; - case CV_16S: - for( k = 0; k < cn; k++ ) - isum[k] = 0; - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - int val = ((const short*)data)[j+k]; - isum[k] += val; - sqsum.val[k] += ((double)val)*val; - } - } - for( k = 0; k < cn; k++ ) - sum.val[k] += isum[k]; - break; - case CV_32S: - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - double val = ((const int*)data)[j+k]; - sum.val[k] += val; - sqsum.val[k] += val*val; - } - } - break; - case CV_32F: - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - double val = ((const float*)data)[j+k]; - sum.val[k] += val; - sqsum.val[k] += val*val; - } - } - break; - case CV_64F: - for( j = 0; j < ncols; j += cn0 ) - if( *mdata++ ) - { - for( k = 0; k < cn; k++ ) - { - double val = ((const double*)data)[j+k]; - sum.val[k] += val; - sqsum.val[k] += val*val; - } - } - break; - default: - assert(0); - return -1; - } - } - - inv_area = nonzero ? 1./nonzero : 0.; - for( k = 0; k < cn; k++ ) - { - sum.val[k] *= inv_area; - double t = sqsum.val[k]*inv_area - sum.val[k]*sum.val[k]; - sqsum.val[k] = sqrt(MAX(t, 0)); - } - if( _mean ) - *_mean = sum; - if( _stddev ) - *_stddev = sqsum; - return nonzero; -} - -// retrieves global extremums and their positions -void cvTsMinMaxLoc( const CvMat* arr, const CvMat* mask, - double* _minval, double* _maxval, - CvPoint* _minidx, CvPoint* _maxidx, int coi ) -{ - int i = 0, j = 0; - int depth, cn, cols, ncols, el_size1; - CvPoint minidx = {-1,-1}, maxidx = {-1,-1}; - uchar* maskbuf = 0; - int iminval = INT_MAX, imaxval = INT_MIN; - double minval = DBL_MAX, maxval = -minval; - - cn = CV_MAT_CN(arr->type); - cols = arr->cols; - ncols = arr->cols*cn; - depth = CV_MAT_DEPTH(arr->type); - el_size1 = CV_ELEM_SIZE(depth); - - if( mask ) - { - assert( CV_ARE_SIZES_EQ( arr, mask ) && CV_IS_MASK_ARR(mask) ); - } - else - { - maskbuf = (uchar*)cvStackAlloc( cols ); - memset( maskbuf, 1, cols ); - } - - if( coi == 0 && cn > 1 ) - { - assert(0); - return; - } - - for( i = 0; i < arr->rows; i++ ) - { - const uchar* data = arr->data.ptr + arr->step*i + (coi - (coi != 0))*el_size1; - const uchar* mdata = mask ? mask->data.ptr + mask->step*i : maskbuf; - - switch( depth ) - { - case CV_8U: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - int val = ((const uchar*)data)[j]; - if( val < iminval && *mdata ) - { - iminval = val; - minidx = cvPoint(j,i); - } - if( val > imaxval && *mdata ) - { - imaxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_8S: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - int val = ((const schar*)data)[j]; - if( val < iminval && *mdata ) - { - iminval = val; - minidx = cvPoint(j,i); - } - if( val > imaxval && *mdata ) - { - imaxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_16U: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - int val = ((const ushort*)data)[j]; - if( val < iminval && *mdata ) - { - iminval = val; - minidx = cvPoint(j,i); - } - if( val > imaxval && *mdata ) - { - imaxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_16S: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - int val = ((const short*)data)[j]; - if( val < iminval && *mdata ) - { - iminval = val; - minidx = cvPoint(j,i); - } - if( val > imaxval && *mdata ) - { - imaxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_32S: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - int val = ((const int*)data)[j]; - if( val < iminval && *mdata ) - { - iminval = val; - minidx = cvPoint(j,i); - } - if( val > imaxval && *mdata ) - { - imaxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_32F: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - float val = ((const float*)data)[j]; - if( val < minval && *mdata ) - { - minval = val; - minidx = cvPoint(j,i); - } - if( val > maxval && *mdata ) - { - maxval = val; - maxidx = cvPoint(j,i); - } - } - break; - case CV_64F: - for( j = 0; j < ncols; j += cn, mdata++ ) - { - double val = ((const double*)data)[j]; - if( val < minval && *mdata ) - { - minval = val; - minidx = cvPoint(j,i); - } - if( val > maxval && *mdata ) - { - maxval = val; - maxidx = cvPoint(j,i); - } - } - break; - default: - assert(0); - return; - } - } - - if( minidx.x < 0 ) - minval = maxval = 0; - else - { - if( depth < CV_32F ) - minval = iminval, maxval = imaxval; - minidx.x /= cn; - maxidx.x /= cn; - } - - if( _minval ) - *_minval = minval; - - if( _maxval ) - *_maxval = maxval; - - if( _minidx ) - *_minidx = minidx; - - if( _maxidx ) - *_maxidx = maxidx; -} - - -void cvTsLogic( const CvMat* a, const CvMat* b, CvMat* c, int logic_op ) -{ - int i = 0, j = 0, ncols; - ncols = a->cols*CV_ELEM_SIZE(a->type); - - assert( CV_ARE_TYPES_EQ(a,b) && CV_ARE_SIZES_EQ(a,b) ); - assert( CV_ARE_TYPES_EQ(a,c) && CV_ARE_SIZES_EQ(a,c) ); - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - uchar* c_data = c->data.ptr + c->step*i; - - switch( logic_op ) - { - case CV_TS_LOGIC_AND: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] & b_data[j]); - break; - case CV_TS_LOGIC_OR: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] | b_data[j]); - break; - case CV_TS_LOGIC_XOR: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] ^ b_data[j]); - break; - default: - assert(0); - return; - } - } -} - -void cvTsLogicS( const CvMat* a, CvScalar s, CvMat* c, int logic_op ) -{ - int i = 0, j = 0, k; - int cn, ncols, elem_size; - uchar* b_data; - union - { - uchar ptr[4]; - schar c[4]; - short s[4]; - ushort w[4]; - int i[4]; - float f[4]; - double d[4]; - } buf; - cn = CV_MAT_CN(a->type); - elem_size = CV_ELEM_SIZE(a->type); - ncols = a->cols * elem_size; - b_data = (uchar*)malloc( ncols ); - - assert( CV_ARE_TYPES_EQ(a,c) && CV_ARE_SIZES_EQ(a,c) ); - - if( logic_op == CV_TS_LOGIC_NOT ) - { - memset( b_data, -1, ncols ); - logic_op = CV_TS_LOGIC_XOR; - } - else - { - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( k = 0; k < cn; k++ ) - { - int val = cvRound(s.val[k]); - buf.ptr[k] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( k = 0; k < cn; k++ ) - { - int val = cvRound(s.val[k]); - buf.c[k] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( k = 0; k < cn; k++ ) - { - int val = cvRound(s.val[k]); - buf.w[k] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( k = 0; k < cn; k++ ) - { - int val = cvRound(s.val[k]); - buf.s[k] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( k = 0; k < cn; k++ ) - { - int val = cvRound(s.val[k]); - buf.i[k] = CV_CAST_32S(val); - } - break; - case CV_32F: - for( k = 0; k < cn; k++ ) - { - double val = s.val[k]; - buf.f[k] = CV_CAST_32F(val); - } - break; - case CV_64F: - for( k = 0; k < cn; k++ ) - { - double val = s.val[k]; - buf.d[k] = CV_CAST_64F(val); - } - break; - default: - assert(0); - return; - } - - for( j = 0; j < ncols; j += elem_size ) - memcpy( b_data + j, buf.ptr, elem_size ); - } - - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* c_data = c->data.ptr + c->step*i; - - switch( logic_op ) - { - case CV_TS_LOGIC_AND: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] & b_data[j]); - break; - case CV_TS_LOGIC_OR: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] | b_data[j]); - break; - case CV_TS_LOGIC_XOR: - for( j = 0; j < ncols; j++ ) - c_data[j] = (uchar)(a_data[j] ^ b_data[j]); - break; - default: - assert(0); - return; - } - } - - if( b_data ) - free( b_data ); -} - - -void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha, - const CvMat* c, double beta, CvMat* d, int flags ) -{ - int i, j, k; - int a_rows, a_cols, b_rows, b_cols; - int c_rows, c_cols, d_rows, d_cols; - int cn, el_size; - int a_step, a_delta, b_step, b_delta; - int c_step, c_delta, d_step; - - a_rows = a->rows; a_cols = a->cols; - cn = CV_MAT_CN(a->type); - el_size = CV_ELEM_SIZE(a->type & ~CV_MAT_CN_MASK); - a_step = a->step / el_size; a_delta = cn; - d_rows = d->rows; d_cols = d->cols; - b_rows = b->rows; b_cols = b->cols; - b_step = b->step / el_size; b_delta = cn; - c_rows = c ? c->rows : 0; c_cols = c ? c->cols : 0; - c_step = c ? c->step / el_size : 0; c_delta = c ? cn : 0; - d_step = d->step / el_size; - - assert( CV_ARE_TYPES_EQ(a,b) && CV_ARE_TYPES_EQ(a,d) ); - assert( CV_MAT_CN(a->type) <= 2 ); - - if( flags & CV_TS_GEMM_A_T ) - { - CV_SWAP( a_rows, a_cols, i ); - CV_SWAP( a_step, a_delta, i ); - } - - if( flags & CV_TS_GEMM_B_T ) - { - CV_SWAP( b_rows, b_cols, i ); - CV_SWAP( b_step, b_delta, i ); - } - - if( flags & CV_TS_GEMM_C_T ) - { - CV_SWAP( c_rows, c_cols, i ); - CV_SWAP( c_step, c_delta, i ); - } - - assert( a_rows == d_rows && a_cols == b_rows && b_cols == d_cols ); - assert( a->data.ptr != d->data.ptr && b->data.ptr != d->data.ptr ); - - if( c ) - { - assert( CV_ARE_TYPES_EQ(a,c) && c_rows == d_rows && c_cols == d_cols ); - assert( c->data.ptr != d->data.ptr || (flags & CV_TS_GEMM_C_T) == 0 ); - } - - if( CV_MAT_DEPTH(a->type) == CV_32F ) - { - float* a_data0 = a->data.fl; - float* b_data0 = b->data.fl; - float* c_data0 = c ? c->data.fl : 0; - float* d_data = d->data.fl; - - for( i = 0; i < d_rows; i++, d_data += d_step, c_data0 += c_step, a_data0 += a_step ) - { - for( j = 0; j < d_cols; j++ ) - { - float* a_data = a_data0; - float* b_data = b_data0 + j*b_delta; - float* c_data = c_data0 + j*c_delta; - - if( cn == 1 ) - { - double s = 0; - for( k = 0; k < a_cols; k++ ) - { - s += ((double)a_data[0])*b_data[0]; - a_data += a_delta; - b_data += b_step; - } - d_data[j] = (float)(s*alpha + (c_data ? c_data[0]*beta : 0)); - } - else - { - double s_re = 0, s_im = 0; - - for( k = 0; k < a_cols; k++ ) - { - s_re += ((double)a_data[0])*b_data[0] - ((double)a_data[1])*b_data[1]; - s_im += ((double)a_data[0])*b_data[1] + ((double)a_data[1])*b_data[0]; - a_data += a_delta; - b_data += b_step; - } - - s_re *= alpha; - s_im *= alpha; - - if( c_data ) - { - s_re += c_data[0]*beta; - s_im += c_data[1]*beta; - } - - d_data[j*2] = (float)s_re; - d_data[j*2+1] = (float)s_im; - } - } - } - } - else if( CV_MAT_DEPTH(a->type) == CV_64F ) - { - double* a_data0 = a->data.db; - double* b_data0 = b->data.db; - double* c_data0 = c ? c->data.db : 0; - double* d_data = d->data.db; - - for( i = 0; i < d_rows; i++, d_data += d_step, c_data0 += c_step, a_data0 += a_step ) - { - for( j = 0; j < d_cols; j++ ) - { - double* a_data = a_data0; - double* b_data = b_data0 + j*b_delta; - double* c_data = c_data0 + j*c_delta; - - if( cn == 1 ) - { - double s = 0; - for( k = 0; k < a_cols; k++ ) - { - s += a_data[0]*b_data[0]; - a_data += a_delta; - b_data += b_step; - } - d_data[j] = s*alpha + (c_data ? c_data[0]*beta : 0); - } - else - { - double s_re = 0, s_im = 0; - - for( k = 0; k < a_cols; k++ ) - { - s_re += a_data[0]*b_data[0] - a_data[1]*b_data[1]; - s_im += a_data[0]*b_data[1] + a_data[1]*b_data[0]; - a_data += a_delta; - b_data += b_step; - } - s_re *= alpha; - s_im *= alpha; - - if( c_data ) - { - s_re += c_data[0]*beta; - s_im += c_data[1]*beta; - } - - d_data[j*2] = s_re; - d_data[j*2+1] = s_im; - } - } - } - } - else - { - assert(0); - } -} - - -CvMat* cvTsSelect( const CvMat* a, CvMat* header, CvRect rect ) -{ - CvMat h; - int el_size; - - h = cvMat( rect.height, rect.width, a->type ); - el_size = CV_ELEM_SIZE(a->type); - - h.data.ptr = a->data.ptr + rect.y*a->step + rect.x*el_size; - h.step = rect.height > 1 ? a->step : 0; - h.type &= ~CV_MAT_CONT_FLAG; - if( rect.height == 1 || h.step == h.cols*el_size ) - h.type |= CV_MAT_CONT_FLAG; - *header = h; - return header; -} - - -double cvTsMinVal( int type ) -{ - switch( CV_MAT_DEPTH(type) ) - { - case CV_8U: - return 0; - case CV_8S: - return -128; - case CV_16U: - return 0; - case CV_16S: - return -32768; - case CV_32S: - return -1000000; - case CV_32F: - return -1000.; - case CV_64F: - return -1000.; - } - return log(-1.); -} - - -double cvTsMaxVal( int type ) -{ - switch( CV_MAT_DEPTH(type) ) - { - case CV_8U: - return 256; - case CV_8S: - return 128; - case CV_16U: - return 65536; - case CV_16S: - return 32768; - case CV_32S: - return 1000000; - case CV_32F: - return 1000.; - case CV_64F: - return 1000.; - } - return log(-1.); -} - - -void cvTsPrepareToFilter( const CvMat* a, CvMat* b, CvPoint ofs, - int border_mode, CvScalar fill_val ) -{ - int i, j, dir; - CvMat temp, temp2; - - assert( 0 <= ofs.x && ofs.x <= b->cols - a->cols && - 0 <= ofs.y && ofs.y <= b->rows - a->rows ); - - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y, a->cols, a->rows )); - cvTsCopy( a, &temp, 0 ); - - assert( border_mode == CV_TS_BORDER_FILL || - border_mode == CV_TS_BORDER_REPLICATE || - border_mode == CV_TS_BORDER_REFLECT ); - - if( ofs.y > 0 ) - { - if( border_mode == CV_TS_BORDER_FILL ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, 0, a->cols, ofs.y )); - cvTsAdd( 0, cvScalar(0), 0, cvScalar(0), fill_val, &temp, 0 ); - } - else if( border_mode == CV_TS_BORDER_REPLICATE || a->rows == 1 ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y, a->cols, 1 )); - for( i = ofs.y-1; i >= 0; i-- ) - { - cvTsSelect( b, &temp2, cvRect( ofs.x, i, a->cols, 1 )); - cvTsCopy( &temp, &temp2, 0 ); - } - } - else if( border_mode == CV_TS_BORDER_REFLECT ) - { - j = 1; dir = 1; - for( i = ofs.y-1; i >= 0; i-- ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y+j, a->cols, 1 )); - cvTsSelect( b, &temp2, cvRect( ofs.x, i, a->cols, 1 )); - cvTsCopy( &temp, &temp2, 0 ); - if( (unsigned)(j + dir) >= (unsigned)a->rows ) - dir = -dir; - j += dir; - } - } - } - - ofs.y += a->rows; - if( ofs.y < b->rows ) - { - if( border_mode == CV_TS_BORDER_FILL ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y, a->cols, b->rows - ofs.y )); - cvTsAdd( 0, cvScalar(0), 0, cvScalar(0), fill_val, &temp, 0 ); - } - else if( border_mode == CV_TS_BORDER_REPLICATE || a->rows == 1 ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y - 1, a->cols, 1 )); - for( i = ofs.y; i < b->rows; i++ ) - { - cvTsSelect( b, &temp2, cvRect( ofs.x, i, a->cols, 1 )); - cvTsCopy( &temp, &temp2, 0 ); - } - } - else - { - j = a->rows - 2; dir = -1; - for( i = ofs.y; i < b->rows; i++ ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, ofs.y-a->rows+j, a->cols, 1 )); - cvTsSelect( b, &temp2, cvRect( ofs.x, i, a->cols, 1 )); - cvTsCopy( &temp, &temp2, 0 ); - if( (unsigned)(j + dir) >= (unsigned)a->rows ) - dir = -dir; - j += dir; - } - } - } - - if( ofs.x > 0 ) - { - if( border_mode == CV_TS_BORDER_FILL ) - { - cvTsSelect( b, &temp, cvRect( 0, 0, ofs.x, b->rows )); - cvTsAdd( 0, cvScalar(0), 0, cvScalar(0), fill_val, &temp, 0 ); - } - else if( border_mode == CV_TS_BORDER_REPLICATE || a->cols == 1 ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, 0, 1, b->rows )); - for( i = ofs.x-1; i >= 0; i-- ) - { - cvTsSelect( b, &temp2, cvRect( i, 0, 1, b->rows )); - cvTsCopy( &temp, &temp2, 0 ); - } - } - else if( border_mode == CV_TS_BORDER_REFLECT ) - { - j = 1; dir = 1; - for( i = ofs.x-1; i >= 0; i-- ) - { - cvTsSelect( b, &temp, cvRect( ofs.x+j, 0, 1, b->rows )); - cvTsSelect( b, &temp2, cvRect( i, 0, 1, b->rows )); - cvTsCopy( &temp, &temp2, 0 ); - if( (unsigned)(j + dir) >= (unsigned)a->cols ) - dir = -dir; - j += dir; - } - } - } - - ofs.x += a->cols; - if( ofs.x < b->cols ) - { - if( border_mode == CV_TS_BORDER_FILL ) - { - cvTsSelect( b, &temp, cvRect( ofs.x, 0, b->cols - ofs.x, b->rows )); - cvTsAdd( 0, cvScalar(0), 0, cvScalar(0), fill_val, &temp, 0 ); - } - else if( border_mode == CV_TS_BORDER_REPLICATE || a->cols == 1 ) - { - cvTsSelect( b, &temp, cvRect( ofs.x-1, 0, 1, b->rows )); - for( i = ofs.x; i < b->cols; i++ ) - { - cvTsSelect( b, &temp2, cvRect( i, 0, 1, b->rows )); - cvTsCopy( &temp, &temp2, 0 ); - } - } - else if( border_mode == CV_TS_BORDER_REFLECT ) - { - j = a->cols - 2; dir = -1; - for( i = ofs.x; i < b->cols; i++ ) - { - cvTsSelect( b, &temp, cvRect( ofs.x-a->cols+j, 0, 1, b->rows )); - cvTsSelect( b, &temp2, cvRect( i, 0, 1, b->rows )); - cvTsCopy( &temp, &temp2, 0 ); - if( (unsigned)(j + dir) >= (unsigned)a->cols ) - dir = -dir; - j += dir; - } - } - } -} - - -void cvTsConvolve2D( const CvMat* a, CvMat* b, const CvMat* kernel, CvPoint anchor ) -{ - int i, j, k; - int cn, ncols, a_step; - int ker_size = kernel->rows*kernel->cols; - int* offset = (int*)malloc( ker_size*sizeof(offset[0])); - float* k_data = (float*)malloc( ker_size*sizeof(k_data[0])); - int all_same = 1; - float first = kernel->data.fl[0]; - uchar *a_data, *b_data; - - cn = CV_MAT_CN(a->type); - ncols = b->cols*cn; - a_step = a->step / CV_ELEM_SIZE(a->type & ~CV_MAT_CN_MASK); - - assert( a->cols == b->cols + kernel->cols - 1 && - a->rows == b->rows + kernel->rows - 1 && CV_ARE_TYPES_EQ( a, b ) ); - assert( CV_MAT_TYPE(kernel->type) == CV_32FC1 ); - assert( 0 <= anchor.x && anchor.x < kernel->cols && - 0 <= anchor.y && anchor.y < kernel->rows ); - - for( i = 0, k = 0; i < kernel->rows; i++ ) - for( j = 0; j < kernel->cols; j++ ) - { - float f = ((float*)(kernel->data.ptr + kernel->step*i))[j]; - if( f ) - { - k_data[k] = f; - offset[k++] = (i - anchor.y)*a_step + (j - anchor.x)*cn; - } - if( f != first ) - all_same = 0; - } - - ker_size = k; - a_data = a->data.ptr + a->step*anchor.y + CV_ELEM_SIZE(a->type)*anchor.x; - b_data = b->data.ptr; - - for( i = 0; i < b->rows; i++, a_data += a->step, b_data += b->step ) - { - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - int val; - for( k = 0; k < ker_size; k++ ) - s += ((uchar*)a_data)[j+offset[k]]*k_data[k]; - val = cvRound(s); - ((uchar*)b_data)[j] = CV_CAST_8U(val); - } - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - int val; - for( k = 0; k < ker_size; k++ ) - s += ((schar*)a_data)[j+offset[k]]*k_data[k]; - val = cvRound(s); - ((schar*)b_data)[j] = CV_CAST_8S(val); - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - int val; - for( k = 0; k < ker_size; k++ ) - s += ((ushort*)a_data)[j+offset[k]]*k_data[k]; - val = cvRound(s); - ((ushort*)b_data)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - int val; - for( k = 0; k < ker_size; k++ ) - s += ((short*)a_data)[j+offset[k]]*k_data[k]; - val = cvRound(s); - ((short*)b_data)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - for( k = 0; k < ker_size; k++ ) - s += ((int*)a_data)[j+offset[k]]*k_data[k]; - ((int*)b_data)[j] = cvRound(s); - } - break; - case CV_32F: - if( !all_same ) - { - for( j = 0; j < ncols; j++ ) - { - double s = 0; - for( k = 0; k < ker_size; k++ ) - s += (double)((float*)a_data)[j+offset[k]]*k_data[k]; - ((float*)b_data)[j] = (float)s; - } - } - else - { - // special branch to speedup feature selection and blur tests - for( j = 0; j < ncols; j++ ) - { - double s = 0; - for( k = 0; k < ker_size; k++ ) - s += (double)((float*)a_data)[j+offset[k]]; - ((float*)b_data)[j] = (float)(s*first); - } - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double s = 0; - for( k = 0; k < ker_size; k++ ) - s += ((double*)a_data)[j+offset[k]]*k_data[k]; - ((double*)b_data)[j] = (double)s; - } - break; - default: - assert(0); - } - } - - free( offset ); - free( k_data ); -} - - -void cvTsMinMaxFilter( const CvMat* a, CvMat* b, const IplConvKernel* kernel, int op_type ) -{ - int i, j, k; - int cn, ncols, a_step; - int ker_size = kernel->nRows*kernel->nCols; - int* offset = (int*)malloc( ker_size*sizeof(offset[0])); - int calc_max = op_type != 0; - uchar *a_data, *b_data; - - cn = CV_MAT_CN(a->type); - ncols = b->cols*cn; - a_step = a->step / CV_ELEM_SIZE(a->type & ~CV_MAT_CN_MASK); - - assert( a->cols == b->cols + kernel->nCols - 1 && - a->rows == b->rows + kernel->nRows - 1 && CV_ARE_TYPES_EQ( a, b ) ); - assert( 0 <= kernel->anchorX && kernel->anchorX < kernel->nCols && - 0 <= kernel->anchorY && kernel->anchorY < kernel->nRows ); - - for( i = 0, k = 0; i < kernel->nRows; i++ ) - for( j = 0; j < kernel->nCols; j++ ) - { - if( !kernel->values || kernel->values[i*kernel->nCols + j] ) - offset[k++] = (i - kernel->anchorY)*a_step + (j - kernel->anchorX)*cn; - } - - if( k == 0 ) - offset[k++] = 0; - - ker_size = k; - - a_data = a->data.ptr + kernel->anchorY*a->step + kernel->anchorX*CV_ELEM_SIZE(a->type); - b_data = b->data.ptr; - - for( i = 0; i < b->rows; i++, a_data += a->step, b_data += b->step ) - { - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - { - int m = ((uchar*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - int v = ((uchar*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((uchar*)b_data)[j] = (uchar)m; - } - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - { - int m = ((ushort*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - int v = ((ushort*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((ushort*)b_data)[j] = (ushort)m; - } - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - { - int m = ((short*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - int v = ((short*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((short*)b_data)[j] = (short)m; - } - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - { - int m = ((int*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - int v = ((int*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((int*)b_data)[j] = m; - } - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - { - float m = ((float*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - float v = ((float*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((float*)b_data)[j] = (float)m; - } - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - { - double m = ((double*)a_data)[j+offset[0]]; - for( k = 1; k < ker_size; k++ ) - { - double v = ((double*)a_data)[j+offset[k]]; - if( calc_max ) - { - if( m < v ) - m = v; - } - else if( m > v ) - m = v; - } - ((double*)b_data)[j] = (double)m; - } - break; - default: - assert(0); - } - } - - free( offset ); -} - - -double cvTsCrossCorr( const CvMat* a, const CvMat* b ) -{ - int i, j; - int cn, ncols; - double s = 0; - - cn = CV_MAT_CN(a->type); - ncols = a->cols*cn; - - assert( CV_ARE_SIZES_EQ( a, b ) && CV_ARE_TYPES_EQ( a, b ) ); - for( i = 0; i < a->rows; i++ ) - { - uchar* a_data = a->data.ptr + a->step*i; - uchar* b_data = b->data.ptr + b->step*i; - - switch( CV_MAT_DEPTH(a->type) ) - { - case CV_8U: - for( j = 0; j < ncols; j++ ) - s += ((uchar*)a_data)[j]*((uchar*)b_data)[j]; - break; - case CV_8S: - for( j = 0; j < ncols; j++ ) - s += ((schar*)a_data)[j]*((schar*)b_data)[j]; - break; - case CV_16U: - for( j = 0; j < ncols; j++ ) - s += (double)((ushort*)a_data)[j]*((ushort*)b_data)[j]; - break; - case CV_16S: - for( j = 0; j < ncols; j++ ) - s += ((short*)a_data)[j]*((short*)b_data)[j]; - break; - case CV_32S: - for( j = 0; j < ncols; j++ ) - s += ((double)((int*)a_data)[j])*((int*)b_data)[j]; - break; - case CV_32F: - for( j = 0; j < ncols; j++ ) - s += ((double)((float*)a_data)[j])*((float*)b_data)[j]; - break; - case CV_64F: - for( j = 0; j < ncols; j++ ) - s += ((double*)a_data)[j]*((double*)b_data)[j]; - break; - default: - assert(0); - return log(-1.); - } - } - - return s; -} - - -void cvTsTransform( const CvMat* a, CvMat* b, const CvMat* transmat, const CvMat* shift ) -{ - int i, j, k, cols, dst_cols; - int cn, dst_cn, depth, mat_depth, shiftstep; - double mat[20], *buf, *dst_buf; - - cn = CV_MAT_CN(a->type); - dst_cn = CV_MAT_CN(b->type); - depth = CV_MAT_DEPTH(a->type); - mat_depth = CV_MAT_DEPTH(transmat->type); - cols = transmat->cols; - - // prepare cn x (cn + 1) transform matrix - if( mat_depth == CV_32F ) - { - shiftstep = shift && shift->rows > 1 ? shift->step/sizeof(float) : 1; - for( i = 0; i < transmat->rows; i++ ) - { - mat[i*(cn+1) + cn] = 0.; - for( j = 0; j < cols; j++ ) - mat[i*(cn+1) + j] = ((float*)(transmat->data.ptr + transmat->step*i))[j]; - if( shift ) - mat[i*(cn+1) + cn] = shift->data.fl[i*shiftstep]; - } - } - else - { - assert( mat_depth == CV_64F ); - - shiftstep = shift && shift->rows > 1 ? shift->step/sizeof(double) : 1; - for( i = 0; i < transmat->rows; i++ ) - { - mat[i*(cn+1) + cn] = 0.; - for( j = 0; j < cols; j++ ) - mat[i*(cn+1) + j] = ((double*)(transmat->data.ptr + transmat->step*i))[j]; - if( shift ) - mat[i*(cn+1) + cn] = shift->data.db[i*shiftstep]; - } - } - - // transform data - cols = a->cols * cn; - dst_cols = a->cols * dst_cn; - buf = (double*)cvStackAlloc( cols * sizeof(double) ); - dst_buf = (double*)cvStackAlloc( dst_cols * sizeof(double) ); - - for( i = 0; i < a->rows; i++ ) - { - uchar* src = a->data.ptr + i*a->step; - uchar* dst = b->data.ptr + i*b->step; - double* _dst = dst_buf; - - switch( depth ) - { - case CV_8U: - for( j = 0; j < cols; j++ ) - buf[j] = ((uchar*)src)[j]; - break; - case CV_16U: - for( j = 0; j < cols; j++ ) - buf[j] = ((ushort*)src)[j]; - break; - case CV_16S: - for( j = 0; j < cols; j++ ) - buf[j] = ((short*)src)[j]; - break; - case CV_32S: - for( j = 0; j < cols; j++ ) - buf[j] = ((int*)src)[j]; - break; - case CV_32F: - for( j = 0; j < cols; j++ ) - buf[j] = ((float*)src)[j]; - break; - case CV_64F: - for( j = 0; j < cols; j++ ) - buf[j] = ((double*)src)[j]; - break; - default: - assert(0); - } - - switch( cn ) - { - case 1: - for( j = 0; j < cols; j++, _dst += dst_cn ) - for( k = 0; k < dst_cn; k++ ) - _dst[k] = buf[j]*mat[2*k] + mat[2*k+1]; - break; - case 2: - for( j = 0; j < cols; j += 2, _dst += dst_cn ) - for( k = 0; k < dst_cn; k++ ) - _dst[k] = buf[j]*mat[3*k] + buf[j+1]*mat[3*k+1] + mat[3*k+2]; - break; - case 3: - for( j = 0; j < cols; j += 3, _dst += dst_cn ) - for( k = 0; k < dst_cn; k++ ) - _dst[k] = buf[j]*mat[4*k] + buf[j+1]*mat[4*k+1] + - buf[j+2]*mat[4*k+2] + mat[4*k+3]; - break; - case 4: - for( j = 0; j < cols; j += 4, _dst += dst_cn ) - for( k = 0; k < dst_cn; k++ ) - _dst[k] = buf[j]*mat[5*k] + buf[j+1]*mat[5*k+1] + - buf[j+2]*mat[5*k+2] + buf[j+3]*mat[5*k+3] + mat[5*k+4]; - break; - default: - assert(0); - } - - switch( depth ) - { - case CV_8U: - for( j = 0; j < dst_cols; j++ ) - { - int val = cvRound(dst_buf[j]); - ((uchar*)dst)[j] = CV_CAST_8U(val); - } - break; - case CV_16U: - for( j = 0; j < dst_cols; j++ ) - { - int val = cvRound(dst_buf[j]); - ((ushort*)dst)[j] = CV_CAST_16U(val); - } - break; - case CV_16S: - for( j = 0; j < dst_cols; j++ ) - { - int val = cvRound(dst_buf[j]); - ((short*)dst)[j] = CV_CAST_16S(val); - } - break; - case CV_32S: - for( j = 0; j < dst_cols; j++ ) - ((int*)dst)[j] = cvRound(dst_buf[j]); - break; - case CV_32F: - for( j = 0; j < dst_cols; j++ ) - ((float*)dst)[j] = (float)dst_buf[j]; - break; - case CV_64F: - for( j = 0; j < dst_cols; j++ ) - ((double*)dst)[j] = dst_buf[j]; - break; - default: - assert(0); - } - } -} - - -CvMat* cvTsTranspose( const CvMat* a, CvMat* b ) -{ - int i, j, k, rows, cols, elem_size; - uchar *a_data, *b_data; - int a_step, b_step; - - elem_size = CV_ELEM_SIZE(a->type); - rows = a->rows; - cols = a->cols; - - assert( a->rows == b->cols && a->cols == b->rows && CV_ARE_TYPES_EQ(a,b) ); - a_data = a->data.ptr; - a_step = a->step; - b_data = b->data.ptr; - b_step = b->step; - - if( rows == cols ) - { - for( i = 0; i < rows; i++ ) - { - for( j = 0; j <= i; j++ ) - { - uchar* a_ij = a_data + a_step*i + elem_size*j; - uchar* a_ji = a_data + a_step*j + elem_size*i; - uchar* b_ij = b_data + b_step*i + elem_size*j; - uchar* b_ji = b_data + b_step*j + elem_size*i; - for( k = 0; k < elem_size; k++ ) - { - uchar t0 = a_ij[k]; - uchar t1 = a_ji[k]; - b_ji[k] = t0; - b_ij[k] = t1; - } - } - } - } - else - { - for( i = 0; i < cols; i++ ) - { - for( j = 0; j < rows; j++ ) - { - uchar* a_ji = a_data + a_step*j + elem_size*i; - uchar* b_ij = b_data + b_step*i + elem_size*j; - for( k = 0; k < elem_size; k++ ) - b_ij[k] = a_ji[k]; - } - } - } - - return b; -} - - -void cvTsFlip( const CvMat* a, CvMat* b, int flip_type ) -{ - int i, j, k, rows, cols, elem_size; - uchar *a_data, *b_data; - int a_step, b_step; - - elem_size = CV_ELEM_SIZE(a->type); - rows = a->rows; - cols = a->cols*elem_size; - - assert( CV_ARE_SIZES_EQ(a,b) && CV_ARE_TYPES_EQ(a,b) && a->data.ptr != b->data.ptr ); - a_data = a->data.ptr; - a_step = a->step; - b_data = b->data.ptr; - b_step = b->step; - - if( flip_type <= 0 ) - { - a_data += a_step*(rows-1); - a_step = -a_step; - } - - for( i = 0; i < rows; i++ ) - { - if( flip_type == 0 ) - memcpy( b_data, a_data, cols ); - else - { - for( j = 0; j < cols; j += elem_size ) - for( k = 0; k < elem_size; k++ ) - b_data[j+k] = a_data[cols - elem_size - j + k]; - } - a_data += a_step; - b_data += b_step; - } -} - - -void cvTsPatchZeros( CvMat* mat, double level ) -{ - int i, j, ncols = mat->cols * CV_MAT_CN(mat->type); - - for( i = 0; i < mat->rows; i++ ) - { - switch( CV_MAT_DEPTH(mat->type) ) - { - case CV_32F: - { - float* data = (float*)(mat->data.ptr + i*mat->step); - for( j = 0; j < ncols; j++ ) - if( fabs(data[j]) < level ) - data[j] += 1; - } - break; - case CV_64F: - { - double* data = (double*)(mat->data.ptr + i*mat->step); - for( j = 0; j < ncols; j++ ) - if( fabs(data[j]) < level ) - data[j] += 1; - } - break; - default: - assert(0); - return; - } - } -} - - -/* End of file. */ diff --git a/tests/cxts/precomp.cpp b/tests/cxts/precomp.cpp deleted file mode 100644 index 5c5265a..0000000 --- a/tests/cxts/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "_cxts.h" - -/* End of file. */ diff --git a/tests/ml/CMakeLists.txt b/tests/ml/CMakeLists.txt deleted file mode 100644 index b14215a..0000000 --- a/tests/ml/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -# ---------------------------------------------------------------------------- -# CMake file for cxcoretest. See root CMakeLists.txt -# -# ---------------------------------------------------------------------------- -project(opencv_test_ml) - -file(GLOB test_srcs "src/*.cpp") -source_group("Src" FILES ${test_srcs}) -file(GLOB test_hdrs "src/*.h*") -source_group("Include" FILES ${test_hdrs}) - -if(WIN32 AND MSVC) - set(pch_header "mltest.h") - set(pch_src "precomp.cpp") - list(REMOVE_ITEM test_srcs ${CMAKE_CURRENT_SOURCE_DIR}/src/${pch_src}) - set(test_srcs ${CMAKE_CURRENT_SOURCE_DIR}/src/${pch_src} ${test_srcs}) - foreach(src_file ${test_srcs}) - if(${src_file} MATCHES ${pch_src}) - set_source_files_properties( - ${src_file} - PROPERTIES - COMPILE_FLAGS "/Yc${pch_header}" - ) - else() - set_source_files_properties( - ${src_file} - PROPERTIES - COMPILE_FLAGS "/Yu${pch_header}" - ) - endif() - endforeach() -endif() - -include_directories(../cxts - "${CMAKE_SOURCE_DIR}/include/opencv" - "${CMAKE_SOURCE_DIR}/modules/core/include" - "${CMAKE_SOURCE_DIR}/modules/ml/include" - ) - -set(the_target "opencv_test_ml") - -add_executable(${the_target} ${test_srcs} ${test_hdrs}) - -# Additional target properties -set_target_properties(${the_target} PROPERTIES - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/" - ) - - -add_dependencies(${the_target} opencv_ts opencv_core opencv_ml) - -# Add the required libraries for linking: -target_link_libraries(${the_target} ${OPENCV_LINKER_LIBS} opencv_ts opencv_core opencv_ml) - -enable_testing() -get_target_property(LOC ${the_target} LOCATION) -add_test(${the_target} "${LOC}") - -if(WIN32) -install(TARGETS ${the_target} RUNTIME DESTINATION bin COMPONENT main) -endif() diff --git a/tests/ml/src/aemknearestkmeans.cpp b/tests/ml/src/aemknearestkmeans.cpp deleted file mode 100644 index 12c782f..0000000 --- a/tests/ml/src/aemknearestkmeans.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" - -using namespace std; -using namespace cv; - -void defaultDistribs( vector& means, vector& covs ) -{ - float mp0[] = {0.0f, 0.0f}, cp0[] = {0.67f, 0.0f, 0.0f, 0.67f}; - float mp1[] = {5.0f, 0.0f}, cp1[] = {1.0f, 0.0f, 0.0f, 1.0f}; - float mp2[] = {1.0f, 5.0f}, cp2[] = {1.0f, 0.0f, 0.0f, 1.0f}; - Mat m0( 1, 2, CV_32FC1, mp0 ), c0( 2, 2, CV_32FC1, cp0 ); - Mat m1( 1, 2, CV_32FC1, mp1 ), c1( 2, 2, CV_32FC1, cp1 ); - Mat m2( 1, 2, CV_32FC1, mp2 ), c2( 2, 2, CV_32FC1, cp2 ); - means.resize(3), covs.resize(3); - m0.copyTo(means[0]), c0.copyTo(covs[0]); - m1.copyTo(means[1]), c1.copyTo(covs[1]); - m2.copyTo(means[2]), c2.copyTo(covs[2]); -} - -// generate points sets by normal distributions -void generateData( Mat& data, Mat& labels, const vector& sizes, const vector& means, const vector& covs, int labelType ) -{ - vector::const_iterator sit = sizes.begin(); - int total = 0; - for( ; sit != sizes.end(); ++sit ) - total += *sit; - assert( means.size() == sizes.size() && covs.size() == sizes.size() ); - assert( !data.empty() && data.rows == total ); - assert( data.type() == CV_32FC1 ); - - labels.create( data.rows, 1, labelType ); - - randn( data, Scalar::all(0.0), Scalar::all(1.0) ); - vector::const_iterator mit = means.begin(), cit = covs.begin(); - int bi, ei = 0; - sit = sizes.begin(); - for( int p = 0, l = 0; sit != sizes.end(); ++sit, ++mit, ++cit, l++ ) - { - bi = ei; - ei = bi + *sit; - assert( mit->rows == 1 && mit->cols == data.cols ); - assert( cit->rows == data.cols && cit->cols == data.cols ); - for( int i = bi; i < ei; i++, p++ ) - { - Mat r(1, data.cols, CV_32FC1, data.ptr(i)); - r = r * (*cit) + *mit; - if( labelType == CV_32FC1 ) - labels.at(p, 0) = (float)l; - else - labels.at(p, 0) = l; - } - } -} - -int maxIdx( const vector& count ) -{ - int idx = -1; - int maxVal = -1; - vector::const_iterator it = count.begin(); - for( int i = 0; it != count.end(); ++it, i++ ) - { - if( *it > maxVal) - { - maxVal = *it; - idx = i; - } - } - assert( idx >= 0); - return idx; -} - -bool getLabelsMap( const Mat& labels, const vector& sizes, vector& labelsMap ) -{ - int total = 0, setCount = (int)sizes.size(); - vector::const_iterator sit = sizes.begin(); - for( ; sit != sizes.end(); ++sit ) - total += *sit; - assert( !labels.empty() ); - assert( labels.rows == total && labels.cols == 1 ); - assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 ); - - bool isFlt = labels.type() == CV_32FC1; - labelsMap.resize(setCount); - vector::iterator lmit = labelsMap.begin(); - vector buzy(setCount, false); - int bi, ei = 0; - for( sit = sizes.begin(); sit != sizes.end(); ++sit, ++lmit ) - { - vector count( setCount, 0 ); - bi = ei; - ei = bi + *sit; - if( isFlt ) - { - for( int i = bi; i < ei; i++ ) - count[(int)labels.at(i, 0)]++; - } - else - { - for( int i = bi; i < ei; i++ ) - count[labels.at(i, 0)]++; - } - - *lmit = maxIdx( count ); - if( buzy[*lmit] ) - return false; - buzy[*lmit] = true; - } - return true; -} - -float calcErr( const Mat& labels, const Mat& origLabels, const vector& sizes, bool labelsEquivalent = true ) -{ - int err = 0; - assert( !labels.empty() && !origLabels.empty() ); - assert( labels.cols == 1 && origLabels.cols == 1 ); - assert( labels.rows == origLabels.rows ); - assert( labels.type() == origLabels.type() ); - assert( labels.type() == CV_32SC1 || labels.type() == CV_32FC1 ); - - vector labelsMap; - bool isFlt = labels.type() == CV_32FC1; - if( !labelsEquivalent ) - { - getLabelsMap( labels, sizes, labelsMap ); - for( int i = 0; i < labels.rows; i++ ) - if( isFlt ) - err += labels.at(i, 0) != labelsMap[(int)origLabels.at(i, 0)]; - else - err += labels.at(i, 0) != labelsMap[origLabels.at(i, 0)]; - } - else - { - for( int i = 0; i < labels.rows; i++ ) - if( isFlt ) - err += labels.at(i, 0) != origLabels.at(i, 0); - else - err += labels.at(i, 0) != origLabels.at(i, 0); - } - return (float)err / (float)labels.rows; -} - -//-------------------------------------------------------------------------------------------- -class CV_KMeansTest : public CvTest { -public: - CV_KMeansTest() : CvTest( "kmeans", "kmeans" ) {} -protected: - virtual void run( int start_from ); -}; - -void CV_KMeansTest::run( int /*start_from*/ ) -{ - const int iters = 100; - int sizesArr[] = { 5000, 7000, 8000 }; - int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2]; - - Mat data( pointsCount, 2, CV_32FC1 ), labels; - vector sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) ); - vector means, covs; - defaultDistribs( means, covs ); - generateData( data, labels, sizes, means, covs, CV_32SC1 ); - - int code = CvTS::OK; - Mat bestLabels; - // 1. flag==KMEANS_PP_CENTERS - kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_PP_CENTERS, 0 ); - if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) - { - ts->printf( CvTS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // 2. flag==KMEANS_RANDOM_CENTERS - kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_RANDOM_CENTERS, 0 ); - if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) - { - ts->printf( CvTS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // 3. flag==KMEANS_USE_INITIAL_LABELS - labels.copyTo( bestLabels ); - RNG rng; - for( int i = 0; i < 0.5f * pointsCount; i++ ) - bestLabels.at( rng.next() % pointsCount, 0 ) = rng.next() % 3; - kmeans( data, 3, bestLabels, TermCriteria( TermCriteria::COUNT, iters, 0.0), 0, KMEANS_USE_INITIAL_LABELS, 0 ); - if( calcErr( bestLabels, labels, sizes, false ) > 0.01f ) - { - ts->printf( CvTS::LOG, "bad accuracy if flag==KMEANS_PP_CENTERS" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - ts->set_failed_test_info( code ); -} - -//-------------------------------------------------------------------------------------------- -class CV_KNearestTest : public CvTest { -public: - CV_KNearestTest() : CvTest( "knearest", "CvKNearest funcs" ) {} -protected: - virtual void run( int start_from ); -}; - -void CV_KNearestTest::run( int /*start_from*/ ) -{ - int sizesArr[] = { 500, 700, 800 }; - int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2]; - - // train data - Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels; - vector sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) ); - vector means, covs; - defaultDistribs( means, covs ); - generateData( trainData, trainLabels, sizes, means, covs, CV_32FC1 ); - - // test data - Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels; - generateData( testData, testLabels, sizes, means, covs, CV_32FC1 ); - - int code = CvTS::OK; - KNearest knearest; - knearest.train( trainData, trainLabels ); - knearest.find_nearest( testData, 4, &bestLabels ); - if( calcErr( bestLabels, testLabels, sizes, true ) > 0.01f ) - { - ts->printf( CvTS::LOG, "bad accuracy on test data" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - ts->set_failed_test_info( code ); -} - -//-------------------------------------------------------------------------------------------- -class CV_EMTest : public CvTest { -public: - CV_EMTest() : CvTest( "em", "CvEM funcs" ) {} -protected: - virtual void run( int start_from ); -}; - -void CV_EMTest::run( int /*start_from*/ ) -{ - int sizesArr[] = { 5000, 7000, 8000 }; - int pointsCount = sizesArr[0]+ sizesArr[1] + sizesArr[2]; - - // train data - Mat trainData( pointsCount, 2, CV_32FC1 ), trainLabels; - vector sizes( sizesArr, sizesArr + sizeof(sizesArr) / sizeof(sizesArr[0]) ); - vector means, covs; - defaultDistribs( means, covs ); - generateData( trainData, trainLabels, sizes, means, covs, CV_32SC1 ); - - // test data - Mat testData( pointsCount, 2, CV_32FC1 ), testLabels, bestLabels; - generateData( testData, testLabels, sizes, means, covs, CV_32SC1 ); - - int code = CvTS::OK; - ExpectationMaximization em; - CvEMParams params; - params.nclusters = 3; - em.train( trainData, Mat(), params, &bestLabels ); - - // check train error - if( calcErr( bestLabels, trainLabels, sizes, true ) > 0.002f ) - { - ts->printf( CvTS::LOG, "bad accuracy on train data" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - // check test error - bestLabels.create( testData.rows, 1, CV_32SC1 ); - for( int i = 0; i < testData.rows; i++ ) - { - Mat sample( 1, testData.cols, CV_32FC1, testData.ptr(i)); - bestLabels.at(i,0) = (int)em.predict( sample, 0 ); - } - if( calcErr( bestLabels, testLabels, sizes, true ) > 0.005f ) - { - ts->printf( CvTS::LOG, "bad accuracy on test data" ); - code = CvTS::FAIL_BAD_ACCURACY; - } - - ts->set_failed_test_info( code ); -} - -CV_KMeansTest kmeans_test; -CV_KNearestTest knearest_test; -CV_EMTest em_test; diff --git a/tests/ml/src/amltests.cpp b/tests/ml/src/amltests.cpp deleted file mode 100644 index 0cf5c74..0000000 --- a/tests/ml/src/amltests.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" - -CV_AMLTest::CV_AMLTest( const char* _modelName, const char* _testName ) : - CV_MLBaseTest( _modelName, _testName, "train-predict" ) -{ - validationFN = "avalidation.xml"; -} - -int CV_AMLTest::run_test_case( int testCaseIdx ) -{ - int code = CvTS::OK; - code = prepare_test_case( testCaseIdx ); - - if (code == CvTS::OK) - { - //#define GET_STAT -#ifdef GET_STAT - const char* data_name = ((CvFileNode*)cvGetSeqElem( dataSetNames, testCaseIdx ))->data.str.ptr; - printf("%s, %s ", name, data_name); - const int icount = 100; - float res[icount]; - for (int k = 0; k < icount; k++) - { -#endif - data.mix_train_and_test_idx(); - code = train( testCaseIdx ); -#ifdef GET_STAT - float case_result = get_error(); - - res[k] = case_result; - } - float mean = 0, sigma = 0; - for (int k = 0; k < icount; k++) - { - mean += res[k]; - } - mean = mean /icount; - for (int k = 0; k < icount; k++) - { - sigma += (res[k] - mean)*(res[k] - mean); - } - sigma = sqrt(sigma/icount); - printf("%f, %f\n", mean, sigma); -#endif - } - return code; -} - -int CV_AMLTest::validate_test_results( int testCaseIdx ) -{ - int iters; - float mean, sigma; - // read validation params - FileNode resultNode = - validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["result"]; - resultNode["iter_count"] >> iters; - if ( iters > 0) - { - resultNode["mean"] >> mean; - resultNode["sigma"] >> sigma; - float curErr = get_error( testCaseIdx, CV_TEST_ERROR ); - const int coeff = 4; - ts->printf( CvTS::LOG, "Test case = %d; test error = %f; mean error = %f (diff=%f), %d*sigma = %f", - testCaseIdx, curErr, mean, abs( curErr - mean), coeff, coeff*sigma ); - if ( abs( curErr - mean) > coeff*sigma ) - { - ts->printf( CvTS::LOG, "abs(%f - %f) > %f - OUT OF RANGE!\n", curErr, mean, coeff*sigma, coeff ); - return CvTS::FAIL_BAD_ACCURACY; - } - else - ts->printf( CvTS::LOG, ".\n" ); - - } - else - { - ts->printf( CvTS::LOG, "validation info is not suitable" ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - return CvTS::OK; -} - -CV_AMLTest amldtree( CV_DTREE, "adtree" ); -CV_AMLTest amlboost( CV_BOOST, "aboost" ); -CV_AMLTest amlrtrees( CV_RTREES, "artrees" ); -CV_AMLTest amlertrees( CV_ERTREES, "aertrees" ); - -/* End of file. */ diff --git a/tests/ml/src/gbttest.cpp b/tests/ml/src/gbttest.cpp deleted file mode 100644 index 12a242e..0000000 --- a/tests/ml/src/gbttest.cpp +++ /dev/null @@ -1,276 +0,0 @@ - -#include "mltest.h" -#include -#include -#include - -using namespace std; - - -class CV_GBTreesTest : public CvTest -{ -public: - CV_GBTreesTest(); - ~CV_GBTreesTest(); - -protected: - void run(int); - - int TestTrainPredict(int test_num); - int TestSaveLoad(); - - int checkPredictError(int test_num); - int checkLoadSave(); - - //string model_file_name1; - //string model_file_name2; - char model_file_name1[50]; - char model_file_name2[50]; - string* datasets; - string data_path; - - CvMLData* data; - CvGBTrees* gtb; - - vector test_resps1; - vector test_resps2; -}; - - -int _get_len(const CvMat* mat) -{ - return (mat->cols > mat->rows) ? mat->cols : mat->rows; -} - - -CV_GBTreesTest::CV_GBTreesTest() : - CvTest( "gbtrees", - "all public methods (train, predict, save, load)" ) -{ - datasets = 0; - data = 0; - gtb = 0; -} - -CV_GBTreesTest::~CV_GBTreesTest() -{ - if (data) - delete data; - delete[] datasets; -} - - -int CV_GBTreesTest::TestTrainPredict(int test_num) -{ - int code = CvTS::OK; - - int weak_count = 200; - float shrinkage = 0.1f; - float subsample_portion = 0.5f; - int max_depth = 5; - bool use_surrogates = true; - int loss_function_type = 0; - switch (test_num) - { - case (1) : loss_function_type = CvGBTrees::SQUARED_LOSS; break; - case (2) : loss_function_type = CvGBTrees::ABSOLUTE_LOSS; break; - case (3) : loss_function_type = CvGBTrees::HUBER_LOSS; break; - case (0) : loss_function_type = CvGBTrees::DEVIANCE_LOSS; break; - default : - { - ts->printf( CvTS::LOG, "Bad test_num value in CV_GBTreesTest::TestTrainPredict(..) function." ); - return CvTS::FAIL_BAD_ARG_CHECK; - } - } - - int dataset_num = test_num == 0 ? 0 : 1; - if (!data) - { - data = new CvMLData(); - data->set_delimiter(','); - - if (data->read_csv(datasets[dataset_num].c_str())) - { - ts->printf( CvTS::LOG, "File reading error." ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - - if (test_num == 0) - { - data->set_response_idx(57); - data->set_var_types("ord[0-56],cat[57]"); - } - else - { - data->set_response_idx(13); - data->set_var_types("ord[0-2,4-13],cat[3]"); - subsample_portion = 0.7f; - } - - int train_sample_count = cvFloor(_get_len(data->get_responses())*0.5f); - CvTrainTestSplit spl( train_sample_count ); - data->set_train_test_split( &spl ); - } - - data->mix_train_and_test_idx(); - - - if (gtb) delete gtb; - gtb = new CvGBTrees(); - bool tmp_code = true; - tmp_code = gtb->train(data, CvGBTreesParams(loss_function_type, weak_count, - shrinkage, subsample_portion, - max_depth, use_surrogates)); - - if (!tmp_code) - { - ts->printf( CvTS::LOG, "Model training was failed."); - return CvTS::FAIL_INVALID_OUTPUT; - } - - code = checkPredictError(test_num); - - return code; - -} - - -int CV_GBTreesTest::checkPredictError(int test_num) -{ - if (!gtb) - return CvTS::FAIL_GENERIC; - - float mean[] = {5.430247f, 13.5654f, 12.6569f, 13.1661f}; - float sigma[] = {0.4162694f, 3.21161f, 3.43297f, 3.00624f}; - - float current_error = gtb->calc_error(data, CV_TEST_ERROR); - - if ( abs( current_error - mean[test_num]) > 6*sigma[test_num] ) - { - ts->printf( CvTS::LOG, "Test error is out of range:\n" - "abs(%f/*curEr*/ - %f/*mean*/ > %f/*6*sigma*/", - current_error, mean[test_num], 6*sigma[test_num] ); - return CvTS::FAIL_BAD_ACCURACY; - } - - return CvTS::OK; - -} - - -int CV_GBTreesTest::TestSaveLoad() -{ - if (!gtb) - return CvTS::FAIL_GENERIC; - - tmpnam(model_file_name1); - tmpnam(model_file_name2); - - if(model_file_name1[0] == '\\') - model_file_name1[0] = '_'; - if(model_file_name2[0] == '\\') - model_file_name2[0] = '_'; - - gtb->save(model_file_name1); - gtb->calc_error(data, CV_TEST_ERROR, &test_resps1); - gtb->load(model_file_name1); - gtb->calc_error(data, CV_TEST_ERROR, &test_resps2); - gtb->save(model_file_name2); - - return checkLoadSave(); - -} - - - -int CV_GBTreesTest::checkLoadSave() -{ - int code = CvTS::OK; - - // 1. compare files - ifstream f1( model_file_name1 ), f2( model_file_name2 ); - string s1, s2; - int lineIdx = 0; - CV_Assert( f1.is_open() && f2.is_open() ); - for( ; !f1.eof() && !f2.eof(); lineIdx++ ) - { - getline( f1, s1 ); - getline( f2, s2 ); - if( s1.compare(s2) ) - { - ts->printf( CvTS::LOG, "first and second saved files differ in %n-line; first %n line: %s; second %n-line: %s", - lineIdx, lineIdx, s1.c_str(), lineIdx, s2.c_str() ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - } - if( !f1.eof() || !f2.eof() ) - { - ts->printf( CvTS::LOG, "First and second saved files differ in %n-line; first %n line: %s; second %n-line: %s", - lineIdx, lineIdx, s1.c_str(), lineIdx, s2.c_str() ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - f1.close(); - f2.close(); - // delete temporary files - remove( model_file_name1 ); - remove( model_file_name2 ); - - // 2. compare responses - CV_Assert( test_resps1.size() == test_resps2.size() ); - vector::const_iterator it1 = test_resps1.begin(), it2 = test_resps2.begin(); - for( ; it1 != test_resps1.end(); ++it1, ++it2 ) - { - if( fabs(*it1 - *it2) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "Responses predicted before saving and after loading are different" ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - } - return code; -} - - - -void CV_GBTreesTest::run(int) -{ - - string data_path = string(ts->get_data_path()); - datasets = new string[2]; - datasets[0] = data_path + string("spambase.data"); /*string("dataset_classification.csv");*/ - datasets[1] = data_path + string("housing_.data"); /*string("dataset_regression.csv");*/ - - int code = CvTS::OK; - - for (int i = 0; i < 4; i++) - { - - int temp_code = TestTrainPredict(i); - if (temp_code != CvTS::OK) - { - code = temp_code; - break; - } - - else if (i==0) - { - temp_code = TestSaveLoad(); - if (temp_code != CvTS::OK) - code = temp_code; - delete data; - data = 0; - } - - delete gtb; - gtb = 0; - } - delete data; - data = 0; - - ts->set_failed_test_info( code ); -} - -///////////////////////////////////////////////////////////////////////////// -//////////////////// test registration ///////////////////////////////////// -///////////////////////////////////////////////////////////////////////////// - -CV_GBTreesTest gbtrees_test; diff --git a/tests/ml/src/mltest.h b/tests/ml/src/mltest.h deleted file mode 100644 index c7ed83d..0000000 --- a/tests/ml/src/mltest.h +++ /dev/null @@ -1,133 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef _OPENCV_MLTEST_H_ -#define _OPENCV_MLTEST_H_ - -#if defined _MSC_VER && _MSC_VER >= 1200 -#pragma warning( disable: 4710 4711 4514 4996 ) -#endif - -#include "cxcore.h" -#include "cxmisc.h" -#include "cxts.h" -#include "ml.h" -#include -#include -#include - -using namespace cv; - -#define CV_NBAYES "nbayes" -#define CV_KNEAREST "knearest" -#define CV_SVM "svm" -#define CV_EM "em" -#define CV_ANN "ann" -#define CV_DTREE "dtree" -#define CV_BOOST "boost" -#define CV_RTREES "rtrees" -#define CV_ERTREES "ertrees" - -class CV_MLBaseTest : public CvTest -{ -public: - CV_MLBaseTest( const char* _modelName, const char* _testName, const char* _testFuncs ); - virtual ~CV_MLBaseTest(); - virtual int init( CvTS* system ); -protected: - virtual int read_params( CvFileStorage* fs ); - virtual void run( int startFrom ); - virtual int prepare_test_case( int testCaseIdx ); - virtual string& get_validation_filename(); - virtual int run_test_case( int testCaseIdx ) = 0; - virtual int validate_test_results( int testCaseIdx ) = 0; - - int train( int testCaseIdx ); - float get_error( int testCaseIdx, int type, std::vector *resp = 0 ); - void save( const char* filename ); - void load( const char* filename ); - - CvMLData data; - string modelName, validationFN; - std::vector dataSetNames; - FileStorage validationFS; - - // MLL models - CvNormalBayesClassifier* nbayes; - CvKNearest* knearest; - CvSVM* svm; - CvEM* em; - CvANN_MLP* ann; - CvDTree* dtree; - CvBoost* boost; - CvRTrees* rtrees; - CvERTrees* ertrees; - - std::map cls_map; - - int64 initSeed; -}; - -class CV_AMLTest : public CV_MLBaseTest -{ -public: - CV_AMLTest( const char* _modelName, const char* _testName ); -protected: - virtual int run_test_case( int testCaseIdx ); - virtual int validate_test_results( int testCaseIdx ); -}; - -class CV_SLMLTest : public CV_MLBaseTest -{ -public: - CV_SLMLTest( const char* _modelName, const char* _testName ); -protected: - virtual int run_test_case( int testCaseIdx ); - virtual int validate_test_results( int testCaseIdx ); - - std::vector test_resps1, test_resps2; // predicted responses for test data - char fname1[50], fname2[50]; -}; - -/* End of file. */ - -#endif diff --git a/tests/ml/src/mltest_main.cpp b/tests/ml/src/mltest_main.cpp deleted file mode 100644 index 97b7c7e..0000000 --- a/tests/ml/src/mltest_main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" - -CvTS test_system("ml"); - -const char* blacklist[] = -{ - "em", //ticket 754 - 0 -}; - -int main( int argc, char** argv ) -{ - return test_system.run( argc, argv, blacklist ); -} - -/* End of file. */ diff --git a/tests/ml/src/mltests.cpp b/tests/ml/src/mltests.cpp deleted file mode 100644 index 1cacab3..0000000 --- a/tests/ml/src/mltests.cpp +++ /dev/null @@ -1,800 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" - -// auxiliary functions -// 1. nbayes -void nbayes_check_data( CvMLData* _data ) -{ - if( _data->get_missing() ) - CV_Error( CV_StsBadArg, "missing values are not supported" ); - const CvMat* var_types = _data->get_var_types(); - bool is_classifier = var_types->data.ptr[var_types->cols-1] == CV_VAR_CATEGORICAL; - if( ( fabs( cvNorm( var_types, 0, CV_L1 ) - - (var_types->rows + var_types->cols - 2)*CV_VAR_ORDERED - CV_VAR_CATEGORICAL ) > FLT_EPSILON ) || - !is_classifier ) - CV_Error( CV_StsBadArg, "incorrect types of predictors or responses" ); -} -bool nbayes_train( CvNormalBayesClassifier* nbayes, CvMLData* _data ) -{ - nbayes_check_data( _data ); - const CvMat* values = _data->get_values(); - const CvMat* responses = _data->get_responses(); - const CvMat* train_sidx = _data->get_train_sample_idx(); - const CvMat* var_idx = _data->get_var_idx(); - return nbayes->train( values, responses, var_idx, train_sidx ); -} -float nbayes_calc_error( CvNormalBayesClassifier* nbayes, CvMLData* _data, int type, vector *resp ) -{ - float err = 0; - nbayes_check_data( _data ); - const CvMat* values = _data->get_values(); - const CvMat* response = _data->get_responses(); - const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx(); - int* sidx = sample_idx ? sample_idx->data.i : 0; - int r_step = CV_IS_MAT_CONT(response->type) ? - 1 : response->step / CV_ELEM_SIZE(response->type); - int sample_count = sample_idx ? sample_idx->cols : 0; - sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? values->rows : sample_count; - float* pred_resp = 0; - if( resp && (sample_count > 0) ) - { - resp->resize( sample_count ); - pred_resp = &((*resp)[0]); - } - - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( values, &sample, si ); - float r = (float)nbayes->predict( &sample, 0 ); - if( pred_resp ) - pred_resp[i] = r; - int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1; - err += d; - } - err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX; - return err; -} - -// 2. knearest -void knearest_check_data_and_get_predictors( CvMLData* _data, CvMat* _predictors ) -{ - const CvMat* values = _data->get_values(); - const CvMat* var_idx = _data->get_var_idx(); - if( var_idx->cols + var_idx->rows != values->cols ) - CV_Error( CV_StsBadArg, "var_idx is not supported" ); - if( _data->get_missing() ) - CV_Error( CV_StsBadArg, "missing values are not supported" ); - int resp_idx = _data->get_response_idx(); - if( resp_idx == 0) - cvGetCols( values, _predictors, 1, values->cols ); - else if( resp_idx == values->cols - 1 ) - cvGetCols( values, _predictors, 0, values->cols - 1 ); - else - CV_Error( CV_StsBadArg, "responses must be in the first or last column; other cases are not supported" ); -} -bool knearest_train( CvKNearest* knearest, CvMLData* _data ) -{ - const CvMat* responses = _data->get_responses(); - const CvMat* train_sidx = _data->get_train_sample_idx(); - bool is_regression = _data->get_var_type( _data->get_response_idx() ) == CV_VAR_ORDERED; - CvMat predictors; - knearest_check_data_and_get_predictors( _data, &predictors ); - return knearest->train( &predictors, responses, train_sidx, is_regression ); -} -float knearest_calc_error( CvKNearest* knearest, CvMLData* _data, int k, int type, vector *resp ) -{ - float err = 0; - const CvMat* response = _data->get_responses(); - const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx(); - int* sidx = sample_idx ? sample_idx->data.i : 0; - int r_step = CV_IS_MAT_CONT(response->type) ? - 1 : response->step / CV_ELEM_SIZE(response->type); - bool is_regression = _data->get_var_type( _data->get_response_idx() ) == CV_VAR_ORDERED; - CvMat predictors; - knearest_check_data_and_get_predictors( _data, &predictors ); - int sample_count = sample_idx ? sample_idx->cols : 0; - sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? predictors.rows : sample_count; - float* pred_resp = 0; - if( resp && (sample_count > 0) ) - { - resp->resize( sample_count ); - pred_resp = &((*resp)[0]); - } - if ( !is_regression ) - { - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( &predictors, &sample, si ); - float r = knearest->find_nearest( &sample, k ); - if( pred_resp ) - pred_resp[i] = r; - int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1; - err += d; - } - err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX; - } - else - { - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( &predictors, &sample, si ); - float r = knearest->find_nearest( &sample, k ); - if( pred_resp ) - pred_resp[i] = r; - float d = r - response->data.fl[si*r_step]; - err += d*d; - } - err = sample_count ? err / (float)sample_count : -FLT_MAX; - } - return err; -} - -// 3. svm -int str_to_svm_type(string& str) -{ - if( !str.compare("C_SVC") ) - return CvSVM::C_SVC; - if( !str.compare("NU_SVC") ) - return CvSVM::NU_SVC; - if( !str.compare("ONE_CLASS") ) - return CvSVM::ONE_CLASS; - if( !str.compare("EPS_SVR") ) - return CvSVM::EPS_SVR; - if( !str.compare("NU_SVR") ) - return CvSVM::NU_SVR; - CV_Error( CV_StsBadArg, "incorrect svm type string" ); - return -1; -} -int str_to_svm_kernel_type( string& str ) -{ - if( !str.compare("LINEAR") ) - return CvSVM::LINEAR; - if( !str.compare("POLY") ) - return CvSVM::POLY; - if( !str.compare("RBF") ) - return CvSVM::RBF; - if( !str.compare("SIGMOID") ) - return CvSVM::SIGMOID; - CV_Error( CV_StsBadArg, "incorrect svm type string" ); - return -1; -} -void svm_check_data( CvMLData* _data ) -{ - if( _data->get_missing() ) - CV_Error( CV_StsBadArg, "missing values are not supported" ); - const CvMat* var_types = _data->get_var_types(); - for( int i = 0; i < var_types->cols-1; i++ ) - if (var_types->data.ptr[i] == CV_VAR_CATEGORICAL) - { - char msg[50]; - sprintf( msg, "incorrect type of %d-predictor", i ); - CV_Error( CV_StsBadArg, msg ); - } -} -bool svm_train( CvSVM* svm, CvMLData* _data, CvSVMParams _params ) -{ - svm_check_data(_data); - const CvMat* _train_data = _data->get_values(); - const CvMat* _responses = _data->get_responses(); - const CvMat* _var_idx = _data->get_var_idx(); - const CvMat* _sample_idx = _data->get_train_sample_idx(); - return svm->train( _train_data, _responses, _var_idx, _sample_idx, _params ); -} -bool svm_train_auto( CvSVM* svm, CvMLData* _data, CvSVMParams _params, - int k_fold, CvParamGrid C_grid, CvParamGrid gamma_grid, - CvParamGrid p_grid, CvParamGrid nu_grid, CvParamGrid coef_grid, - CvParamGrid degree_grid ) -{ - svm_check_data(_data); - const CvMat* _train_data = _data->get_values(); - const CvMat* _responses = _data->get_responses(); - const CvMat* _var_idx = _data->get_var_idx(); - const CvMat* _sample_idx = _data->get_train_sample_idx(); - return svm->train_auto( _train_data, _responses, _var_idx, - _sample_idx, _params, k_fold, C_grid, gamma_grid, p_grid, nu_grid, coef_grid, degree_grid ); -} -float svm_calc_error( CvSVM* svm, CvMLData* _data, int type, vector *resp ) -{ - svm_check_data(_data); - float err = 0; - const CvMat* values = _data->get_values(); - const CvMat* response = _data->get_responses(); - const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx(); - const CvMat* var_types = _data->get_var_types(); - int* sidx = sample_idx ? sample_idx->data.i : 0; - int r_step = CV_IS_MAT_CONT(response->type) ? - 1 : response->step / CV_ELEM_SIZE(response->type); - bool is_classifier = var_types->data.ptr[var_types->cols-1] == CV_VAR_CATEGORICAL; - int sample_count = sample_idx ? sample_idx->cols : 0; - sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? values->rows : sample_count; - float* pred_resp = 0; - if( resp && (sample_count > 0) ) - { - resp->resize( sample_count ); - pred_resp = &((*resp)[0]); - } - if ( is_classifier ) - { - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( values, &sample, si ); - float r = svm->predict( &sample ); - if( pred_resp ) - pred_resp[i] = r; - int d = fabs((double)r - response->data.fl[si*r_step]) <= FLT_EPSILON ? 0 : 1; - err += d; - } - err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX; - } - else - { - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( values, &sample, si ); - float r = svm->predict( &sample ); - if( pred_resp ) - pred_resp[i] = r; - float d = r - response->data.fl[si*r_step]; - err += d*d; - } - err = sample_count ? err / (float)sample_count : -FLT_MAX; - } - return err; -} - -// 4. em -// 5. ann -int str_to_ann_train_method( string& str ) -{ - if( !str.compare("BACKPROP") ) - return CvANN_MLP_TrainParams::BACKPROP; - if( !str.compare("RPROP") ) - return CvANN_MLP_TrainParams::RPROP; - CV_Error( CV_StsBadArg, "incorrect ann train method string" ); - return -1; -} -void ann_check_data_and_get_predictors( CvMLData* _data, CvMat* _inputs ) -{ - const CvMat* values = _data->get_values(); - const CvMat* var_idx = _data->get_var_idx(); - if( var_idx->cols + var_idx->rows != values->cols ) - CV_Error( CV_StsBadArg, "var_idx is not supported" ); - if( _data->get_missing() ) - CV_Error( CV_StsBadArg, "missing values are not supported" ); - int resp_idx = _data->get_response_idx(); - if( resp_idx == 0) - cvGetCols( values, _inputs, 1, values->cols ); - else if( resp_idx == values->cols - 1 ) - cvGetCols( values, _inputs, 0, values->cols - 1 ); - else - CV_Error( CV_StsBadArg, "outputs must be in the first or last column; other cases are not supported" ); -} -void ann_get_new_responses( CvMLData* _data, Mat& new_responses, map& cls_map ) -{ - const CvMat* train_sidx = _data->get_train_sample_idx(); - int* train_sidx_ptr = train_sidx->data.i; - const CvMat* responses = _data->get_responses(); - float* responses_ptr = responses->data.fl; - int r_step = CV_IS_MAT_CONT(responses->type) ? - 1 : responses->step / CV_ELEM_SIZE(responses->type); - int cls_count = 0; - // construct cls_map - cls_map.clear(); - for( int si = 0; si < train_sidx->cols; si++ ) - { - int sidx = train_sidx_ptr[si]; - int r = cvRound(responses_ptr[sidx*r_step]); - CV_DbgAssert( fabs(responses_ptr[sidx*r_step]-r) < FLT_EPSILON ); - int cls_map_size = (int)cls_map.size(); - cls_map[r]; - if ( (int)cls_map.size() > cls_map_size ) - cls_map[r] = cls_count++; - } - new_responses.create( responses->rows, cls_count, CV_32F ); - new_responses.setTo( 0 ); - for( int si = 0; si < train_sidx->cols; si++ ) - { - int sidx = train_sidx_ptr[si]; - int r = cvRound(responses_ptr[sidx*r_step]); - int cidx = cls_map[r]; - new_responses.ptr(sidx)[cidx] = 1; - } -} -int ann_train( CvANN_MLP* ann, CvMLData* _data, Mat& new_responses, CvANN_MLP_TrainParams _params, int flags = 0 ) -{ - const CvMat* train_sidx = _data->get_train_sample_idx(); - CvMat predictors; - ann_check_data_and_get_predictors( _data, &predictors ); - CvMat _new_responses = CvMat( new_responses ); - return ann->train( &predictors, &_new_responses, 0, train_sidx, _params, flags ); -} -float ann_calc_error( CvANN_MLP* ann, CvMLData* _data, map& cls_map, int type , vector *resp_labels ) -{ - float err = 0; - const CvMat* responses = _data->get_responses(); - const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx(); - int* sidx = sample_idx ? sample_idx->data.i : 0; - int r_step = CV_IS_MAT_CONT(responses->type) ? - 1 : responses->step / CV_ELEM_SIZE(responses->type); - CvMat predictors; - ann_check_data_and_get_predictors( _data, &predictors ); - int sample_count = sample_idx ? sample_idx->cols : 0; - sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? predictors.rows : sample_count; - float* pred_resp = 0; - vector innresp; - if( sample_count > 0 ) - { - if( resp_labels ) - { - resp_labels->resize( sample_count ); - pred_resp = &((*resp_labels)[0]); - } - else - { - innresp.resize( sample_count ); - pred_resp = &(innresp[0]); - } - } - int cls_count = (int)cls_map.size(); - Mat output( 1, cls_count, CV_32FC1 ); - CvMat _output = CvMat(output); - map::iterator b_it = cls_map.begin(); - for( int i = 0; i < sample_count; i++ ) - { - CvMat sample; - int si = sidx ? sidx[i] : i; - cvGetRow( &predictors, &sample, si ); - ann->predict( &sample, &_output ); - CvPoint best_cls = {0,0}; - cvMinMaxLoc( &_output, 0, 0, 0, &best_cls, 0 ); - int r = cvRound(responses->data.fl[si*r_step]); - CV_DbgAssert( fabs(responses->data.fl[si*r_step]-r) < FLT_EPSILON ); - r = cls_map[r]; - int d = best_cls.x == r ? 0 : 1; - err += d; - pred_resp[i] = (float)best_cls.x; - } - err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX; - return err; -} - -// 6. dtree -// 7. boost -int str_to_boost_type( string& str ) -{ - if ( !str.compare("DISCRETE") ) - return CvBoost::DISCRETE; - if ( !str.compare("REAL") ) - return CvBoost::REAL; - if ( !str.compare("LOGIT") ) - return CvBoost::LOGIT; - if ( !str.compare("GENTLE") ) - return CvBoost::GENTLE; - CV_Error( CV_StsBadArg, "incorrect boost type string" ); - return -1; -} - -// 8. rtrees -// 9. ertrees - -// ---------------------------------- MLBaseTest --------------------------------------------------- - -CV_MLBaseTest::CV_MLBaseTest( const char* _modelName, const char* _testName, const char* _testFuncs ) : -CvTest( _testName, _testFuncs ) -{ - int64 seeds[] = { CV_BIG_INT(0x00009fff4f9c8d52), - CV_BIG_INT(0x0000a17166072c7c), - CV_BIG_INT(0x0201b32115cd1f9a), - CV_BIG_INT(0x0513cb37abcd1234), - CV_BIG_INT(0x0001a2b3c4d5f678) - }; - - int seedCount = sizeof(seeds)/sizeof(seeds[0]); - RNG& rng = theRNG(); - - initSeed = rng.state; - - rng.state = seeds[rng(seedCount)]; - - modelName = _modelName; - nbayes = 0; - knearest = 0; - svm = 0; - em = 0; - ann = 0; - dtree = 0; - boost = 0; - rtrees = 0; - ertrees = 0; - if( !modelName.compare(CV_NBAYES) ) - nbayes = new CvNormalBayesClassifier; - else if( !modelName.compare(CV_KNEAREST) ) - knearest = new CvKNearest; - else if( !modelName.compare(CV_SVM) ) - svm = new CvSVM; - else if( !modelName.compare(CV_EM) ) - em = new CvEM; - else if( !modelName.compare(CV_ANN) ) - ann = new CvANN_MLP; - else if( !modelName.compare(CV_DTREE) ) - dtree = new CvDTree; - else if( !modelName.compare(CV_BOOST) ) - boost = new CvBoost; - else if( !modelName.compare(CV_RTREES) ) - rtrees = new CvRTrees; - else if( !modelName.compare(CV_ERTREES) ) - ertrees = new CvERTrees; -} - -int CV_MLBaseTest::init( CvTS* system ) -{ - clear(); - ts = system; - - string filename = ts->get_data_path(); - filename += get_validation_filename(); - validationFS.open( filename, FileStorage::READ ); - return read_params( *validationFS ); -} - -CV_MLBaseTest::~CV_MLBaseTest() -{ - if( validationFS.isOpened() ) - validationFS.release(); - if( nbayes ) - delete nbayes; - if( knearest ) - delete knearest; - if( svm ) - delete svm; - if( em ) - delete em; - if( ann ) - delete ann; - if( dtree ) - delete dtree; - if( boost ) - delete boost; - if( rtrees ) - delete rtrees; - if( ertrees ) - delete ertrees; - theRNG().state = initSeed; -} - -int CV_MLBaseTest::read_params( CvFileStorage* _fs ) -{ - if( !_fs ) - test_case_count = -1; - else - { - CvFileNode* fn = cvGetRootFileNode( _fs, 0 ); - fn = (CvFileNode*)cvGetSeqElem( fn->data.seq, 0 ); - fn = cvGetFileNodeByName( _fs, fn, "run_params" ); - CvSeq* dataSetNamesSeq = cvGetFileNodeByName( _fs, fn, modelName.c_str() )->data.seq; - test_case_count = dataSetNamesSeq ? dataSetNamesSeq->total : -1; - if( test_case_count > 0 ) - { - dataSetNames.resize( test_case_count ); - vector::iterator it = dataSetNames.begin(); - for( int i = 0; i < test_case_count; i++, it++ ) - *it = ((CvFileNode*)cvGetSeqElem( dataSetNamesSeq, i ))->data.str.ptr; - } - } - return CvTS::OK;; -} - -void CV_MLBaseTest::run( int start_from ) -{ - int code = CvTS::OK; - start_from = 0; - for (int i = 0; i < test_case_count; i++) - { - int temp_code = run_test_case( i ); - if (temp_code == CvTS::OK) - temp_code = validate_test_results( i ); - if (temp_code != CvTS::OK) - code = temp_code; - } - if ( test_case_count <= 0) - { - ts->printf( CvTS::LOG, "validation file is not determined or not correct" ); - code = CvTS::FAIL_INVALID_TEST_DATA; - } - ts->set_failed_test_info( code ); -} - -int CV_MLBaseTest::prepare_test_case( int test_case_idx ) -{ - int trainSampleCount, respIdx; - string varTypes; - clear(); - - string dataPath = ts->get_data_path(); - if ( dataPath.empty() ) - { - ts->printf( CvTS::LOG, "data path is empty" ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - - string dataName = dataSetNames[test_case_idx], - filename = dataPath + dataName + ".data"; - if ( data.read_csv( filename.c_str() ) != 0) - { - char msg[100]; - sprintf( msg, "file %s can not be read", filename.c_str() ); - ts->printf( CvTS::LOG, msg ); - return CvTS::FAIL_INVALID_TEST_DATA; - } - - FileNode dataParamsNode = validationFS.getFirstTopLevelNode()["validation"][modelName][dataName]["data_params"]; - CV_DbgAssert( !dataParamsNode.empty() ); - - CV_DbgAssert( !dataParamsNode["LS"].empty() ); - dataParamsNode["LS"] >> trainSampleCount; - CvTrainTestSplit spl( trainSampleCount ); - data.set_train_test_split( &spl ); - - CV_DbgAssert( !dataParamsNode["resp_idx"].empty() ); - dataParamsNode["resp_idx"] >> respIdx; - data.set_response_idx( respIdx ); - - CV_DbgAssert( !dataParamsNode["types"].empty() ); - dataParamsNode["types"] >> varTypes; - data.set_var_types( varTypes.c_str() ); - - return CvTS::OK; -} - -string& CV_MLBaseTest::get_validation_filename() -{ - return validationFN; -} - -int CV_MLBaseTest::train( int testCaseIdx ) -{ - bool is_trained = false; - FileNode modelParamsNode = - validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["model_params"]; - - if( !modelName.compare(CV_NBAYES) ) - is_trained = nbayes_train( nbayes, &data ); - else if( !modelName.compare(CV_KNEAREST) ) - { - assert( 0 ); - //is_trained = knearest->train( &data ); - } - else if( !modelName.compare(CV_SVM) ) - { - string svm_type_str, kernel_type_str; - modelParamsNode["svm_type"] >> svm_type_str; - modelParamsNode["kernel_type"] >> kernel_type_str; - CvSVMParams params; - params.svm_type = str_to_svm_type( svm_type_str ); - params.kernel_type = str_to_svm_kernel_type( kernel_type_str ); - modelParamsNode["degree"] >> params.degree; - modelParamsNode["gamma"] >> params.gamma; - modelParamsNode["coef0"] >> params.coef0; - modelParamsNode["C"] >> params.C; - modelParamsNode["nu"] >> params.nu; - modelParamsNode["p"] >> params.p; - is_trained = svm_train( svm, &data, params ); - } - else if( !modelName.compare(CV_EM) ) - { - assert( 0 ); - } - else if( !modelName.compare(CV_ANN) ) - { - string train_method_str; - double param1, param2; - modelParamsNode["train_method"] >> train_method_str; - modelParamsNode["param1"] >> param1; - modelParamsNode["param2"] >> param2; - Mat new_responses; - ann_get_new_responses( &data, new_responses, cls_map ); - int layer_sz[] = { data.get_values()->cols - 1, 100, 100, (int)cls_map.size() }; - CvMat layer_sizes = - cvMat( 1, (int)(sizeof(layer_sz)/sizeof(layer_sz[0])), CV_32S, layer_sz ); - ann->create( &layer_sizes ); - is_trained = ann_train( ann, &data, new_responses, CvANN_MLP_TrainParams(cvTermCriteria(CV_TERMCRIT_ITER,300,0.01), - str_to_ann_train_method(train_method_str), param1, param2) ) >= 0; - } - else if( !modelName.compare(CV_DTREE) ) - { - int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS; - float REG_ACCURACY = 0; - bool USE_SURROGATE, IS_PRUNED; - modelParamsNode["max_depth"] >> MAX_DEPTH; - modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT; - modelParamsNode["use_surrogate"] >> USE_SURROGATE; - modelParamsNode["max_categories"] >> MAX_CATEGORIES; - modelParamsNode["cv_folds"] >> CV_FOLDS; - modelParamsNode["is_pruned"] >> IS_PRUNED; - is_trained = dtree->train( &data, - CvDTreeParams(MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY, USE_SURROGATE, - MAX_CATEGORIES, CV_FOLDS, false, IS_PRUNED, 0 )) != 0; - } - else if( !modelName.compare(CV_BOOST) ) - { - int BOOST_TYPE, WEAK_COUNT, MAX_DEPTH; - float WEIGHT_TRIM_RATE; - bool USE_SURROGATE; - string typeStr; - modelParamsNode["type"] >> typeStr; - BOOST_TYPE = str_to_boost_type( typeStr ); - modelParamsNode["weak_count"] >> WEAK_COUNT; - modelParamsNode["weight_trim_rate"] >> WEIGHT_TRIM_RATE; - modelParamsNode["max_depth"] >> MAX_DEPTH; - modelParamsNode["use_surrogate"] >> USE_SURROGATE; - is_trained = boost->train( &data, - CvBoostParams(BOOST_TYPE, WEAK_COUNT, WEIGHT_TRIM_RATE, MAX_DEPTH, USE_SURROGATE, 0) ) != 0; - } - else if( !modelName.compare(CV_RTREES) ) - { - int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS, NACTIVE_VARS, MAX_TREES_NUM; - float REG_ACCURACY = 0, OOB_EPS = 0.0; - bool USE_SURROGATE, IS_PRUNED; - modelParamsNode["max_depth"] >> MAX_DEPTH; - modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT; - modelParamsNode["use_surrogate"] >> USE_SURROGATE; - modelParamsNode["max_categories"] >> MAX_CATEGORIES; - modelParamsNode["cv_folds"] >> CV_FOLDS; - modelParamsNode["is_pruned"] >> IS_PRUNED; - modelParamsNode["nactive_vars"] >> NACTIVE_VARS; - modelParamsNode["max_trees_num"] >> MAX_TREES_NUM; - is_trained = rtrees->train( &data, CvRTParams( MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY, - USE_SURROGATE, MAX_CATEGORIES, 0, true, // (calc_var_importance == true) <=> RF processes variable importance - NACTIVE_VARS, MAX_TREES_NUM, OOB_EPS, CV_TERMCRIT_ITER)) != 0; - } - else if( !modelName.compare(CV_ERTREES) ) - { - int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS, NACTIVE_VARS, MAX_TREES_NUM; - float REG_ACCURACY = 0, OOB_EPS = 0.0; - bool USE_SURROGATE, IS_PRUNED; - modelParamsNode["max_depth"] >> MAX_DEPTH; - modelParamsNode["min_sample_count"] >> MIN_SAMPLE_COUNT; - modelParamsNode["use_surrogate"] >> USE_SURROGATE; - modelParamsNode["max_categories"] >> MAX_CATEGORIES; - modelParamsNode["cv_folds"] >> CV_FOLDS; - modelParamsNode["is_pruned"] >> IS_PRUNED; - modelParamsNode["nactive_vars"] >> NACTIVE_VARS; - modelParamsNode["max_trees_num"] >> MAX_TREES_NUM; - is_trained = ertrees->train( &data, CvRTParams( MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY, - USE_SURROGATE, MAX_CATEGORIES, 0, false, // (calc_var_importance == true) <=> RF processes variable importance - NACTIVE_VARS, MAX_TREES_NUM, OOB_EPS, CV_TERMCRIT_ITER)) != 0; - } - - if( !is_trained ) - { - ts->printf( CvTS::LOG, "in test case %d model training was failed", testCaseIdx ); - return CvTS::FAIL_INVALID_OUTPUT; - } - return CvTS::OK; -} - -float CV_MLBaseTest::get_error( int testCaseIdx, int type, vector *resp ) -{ - float err = 0; - if( !modelName.compare(CV_NBAYES) ) - err = nbayes_calc_error( nbayes, &data, type, resp ); - else if( !modelName.compare(CV_KNEAREST) ) - { - assert( 0 ); - testCaseIdx = 0; - /*int k = 2; - validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["model_params"]["k"] >> k; - err = knearest->calc_error( &data, k, type, resp );*/ - } - else if( !modelName.compare(CV_SVM) ) - err = svm_calc_error( svm, &data, type, resp ); - else if( !modelName.compare(CV_EM) ) - assert( 0 ); - else if( !modelName.compare(CV_ANN) ) - err = ann_calc_error( ann, &data, cls_map, type, resp ); - else if( !modelName.compare(CV_DTREE) ) - err = dtree->calc_error( &data, type, resp ); - else if( !modelName.compare(CV_BOOST) ) - err = boost->calc_error( &data, type, resp ); - else if( !modelName.compare(CV_RTREES) ) - err = rtrees->calc_error( &data, type, resp ); - else if( !modelName.compare(CV_ERTREES) ) - err = ertrees->calc_error( &data, type, resp ); - return err; -} - -void CV_MLBaseTest::save( const char* filename ) -{ - if( !modelName.compare(CV_NBAYES) ) - nbayes->save( filename ); - else if( !modelName.compare(CV_KNEAREST) ) - knearest->save( filename ); - else if( !modelName.compare(CV_SVM) ) - svm->save( filename ); - else if( !modelName.compare(CV_EM) ) - em->save( filename ); - else if( !modelName.compare(CV_ANN) ) - ann->save( filename ); - else if( !modelName.compare(CV_DTREE) ) - dtree->save( filename ); - else if( !modelName.compare(CV_BOOST) ) - boost->save( filename ); - else if( !modelName.compare(CV_RTREES) ) - rtrees->save( filename ); - else if( !modelName.compare(CV_ERTREES) ) - ertrees->save( filename ); -} - -void CV_MLBaseTest::load( const char* filename ) -{ - if( !modelName.compare(CV_NBAYES) ) - nbayes->load( filename ); - else if( !modelName.compare(CV_KNEAREST) ) - knearest->load( filename ); - else if( !modelName.compare(CV_SVM) ) - svm->load( filename ); - else if( !modelName.compare(CV_EM) ) - em->load( filename ); - else if( !modelName.compare(CV_ANN) ) - ann->load( filename ); - else if( !modelName.compare(CV_DTREE) ) - dtree->load( filename ); - else if( !modelName.compare(CV_BOOST) ) - boost->load( filename ); - else if( !modelName.compare(CV_RTREES) ) - rtrees->load( filename ); - else if( !modelName.compare(CV_ERTREES) ) - ertrees->load( filename ); -} - -/* End of file. */ diff --git a/tests/ml/src/precomp.cpp b/tests/ml/src/precomp.cpp deleted file mode 100644 index 5b95855..0000000 --- a/tests/ml/src/precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" -/* End of file. */ diff --git a/tests/ml/src/slmltests.cpp b/tests/ml/src/slmltests.cpp deleted file mode 100644 index 29fbcd3..0000000 --- a/tests/ml/src/slmltests.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "mltest.h" -#include -#include - -CV_SLMLTest::CV_SLMLTest( const char* _modelName, const char* _testName ) : - CV_MLBaseTest( _modelName, _testName, "load-save" ) -{ - validationFN = "slvalidation.xml"; -} - -int CV_SLMLTest::run_test_case( int testCaseIdx ) -{ - int code = CvTS::OK; - code = prepare_test_case( testCaseIdx ); - - if( code == CvTS::OK ) - { - data.mix_train_and_test_idx(); - code = train( testCaseIdx ); - if( code == CvTS::OK ) - { - get_error( testCaseIdx, CV_TEST_ERROR, &test_resps1 ); - tmpnam(fname1); - if(fname1[0] == '\\') fname1[0] = '_'; - save( fname1 ); - load( fname1); - get_error( testCaseIdx, CV_TEST_ERROR, &test_resps2 ); - tmpnam(fname2); - if(fname2[0] == '\\') fname2[0] = '_'; - save( fname2 ); - } - else - ts->printf( CvTS::LOG, "model can not be trained" ); - } - return code; -} - -int CV_SLMLTest::validate_test_results( int testCaseIdx ) -{ - int code = CvTS::OK; - - // 1. compare files - ifstream f1( fname1 ), f2( fname2 ); - string s1, s2; - int lineIdx = 0; - CV_Assert( f1.is_open() && f2.is_open() ); - for( ; !f1.eof() && !f2.eof(); lineIdx++ ) - { - getline( f1, s1 ); - getline( f2, s2 ); - if( s1.compare(s2) ) - { - ts->printf( CvTS::LOG, "first and second saved files differ in %n-line; first %n line: %s; second %n-line: %s", - lineIdx, lineIdx, s1.c_str(), lineIdx, s2.c_str() ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - } - if( !f1.eof() || !f2.eof() ) - { - ts->printf( CvTS::LOG, "in test case %d first and second saved files differ in %n-line; first %n line: %s; second %n-line: %s", - testCaseIdx, lineIdx, lineIdx, s1.c_str(), lineIdx, s2.c_str() ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - f1.close(); - f2.close(); - // delete temporary files - remove( fname1 ); - remove( fname2 ); - - // 2. compare responses - CV_Assert( test_resps1.size() == test_resps2.size() ); - vector::const_iterator it1 = test_resps1.begin(), it2 = test_resps2.begin(); - for( ; it1 != test_resps1.end(); ++it1, ++it2 ) - { - if( fabs(*it1 - *it2) > FLT_EPSILON ) - { - ts->printf( CvTS::LOG, "in test case %d responses predicted before saving and after loading is different", testCaseIdx ); - code = CvTS::FAIL_INVALID_OUTPUT; - } - } - return code; -} - -CV_SLMLTest lsmlnbayes( CV_NBAYES, "slnbayes" ); -//CV_SLMLTest lsmlknearest( CV_KNEAREST, "slknearest" ); // does not support save! -CV_SLMLTest lsmlsvm( CV_SVM, "slsvm" ); -//CV_SLMLTest lsmlem( CV_EM, "slem" ); // does not support save! -CV_SLMLTest lsmlann( CV_ANN, "slann" ); -CV_SLMLTest slmldtree( CV_DTREE, "sldtree" ); -CV_SLMLTest slmlboost( CV_BOOST, "slboost" ); -CV_SLMLTest slmlrtrees( CV_RTREES, "slrtrees" ); -CV_SLMLTest slmlertrees( CV_ERTREES, "slertrees" ); - -/* End of file. */ diff --git a/tests/octave/frame.jpg b/tests/octave/frame.jpg deleted file mode 100644 index 4cc25664605031baa06f495799d6b04064b0e106..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19985 zcmX7v1yEbh_x6Lkwz#BNY0;v^1LccDDeltZq_}H}yB8>$QrwHXySKO%3sOA68X$z1 z-~Zh^xpOnw?B3Zs+4G#|eDb*bxCJ0rRa8*~U|;|M7*7Y_aSb33z{L1p``;P!e+?V! ze`g$QY%FYC99-Q0d*Kn_s@6BT`fCwM3fC0k5pa47$ z0)S70-*IdFPqHo2-CFK88P*hS@ zQPt7a(>E|QGPbg|v9+^zaP;u>^7ird^A8J;h>VJkiA_!Wnx2vQEi3y+VNr2OX<2zi zeM4hYb4zPmd;h@T(D2CU*!b++{KDeW^2+M=4s3UC|KRW85#r+V>iXs%^7ig=6@dT0 zWdi{&J388^Ch-0-$QdO7fnc&HLIaQSkzAek;475ob?U6;G<`I_bB?eo1j=&nB zJl7UC=gvaL*f3_qvL?Qp4Dh-$pz*Qv>=IV-fpBHeDPv3@m2byYj@9Hin%aQ`IRRwV zUTEf7)W<4|tj0sT2sXBiZy}q%0t{-9N<*s$QNk^e$3~ZQLigX$&aUEBf0SUPl_cjY znR}NqPJaurgB+)Gs=)cI>H7UUMy|cBi3;j&zjkAD%#m(8U20DAe^YwJZG-gxV4!wq zG#z_$`n)gIZp=ilJJE_eTS;Yo4`6P6cujdpODcbukXu`AAHFj=OxY6486z4*Y? z0*fBM#eF zz`L%IH~Q6BP3sq|Um&#+YRZaO!rls!N&nW(Gs_FTm)KA%=QO7mu@pdFm6rs4Xj$b{ zSBg&$_>OTiW#=d(@ase`p*zaf*3H{<+Qq4Sb=oJM(KO^ptkl;<@8_H|dYCol zzp2&^F(2u=)4A)~4{^P#T)ywklr`MwzxIV<6Ebji;G&y!`c^X%w!uc6iv@{iJW$r5 zn&lUdfB(`3}^t_DDj? z_BhaK$?APyE6TU*1+u{XlZW(``Rz_s<bb6Hc^PM1!9H(RdhU;6NresSHz!F~`c zH<4dcD}fC}lFwDEkQnq5H>cXyL~owl%%Qz{p&?OT?qc^r6n0hS`M@@K^E;&yJiDGt z%%1$Z_aN*de$gP#E9l+u@}Fk9uX}i3zcHf-4-OD#9pw%r)Fr9-vXc6*LLUJvro?Ez zdnOpZdSd*tKo|i_wM@FOVzM4J}SK6rIJ%aa3Q=3U1=HC%II#yd8 zQ$&yGCK-2dKh+MU;wQaA7@v&jl7|XvnWSgnw#B6DTMz$PT zXtnqJmKkr8@i?Zy`Ix^cs!~HVXt21r#UwNOqtJ;AVDT-$DtrGLNPk%Cyhv@#(Lat$ zyhL&yzvWrU3|yeCSxX?}ZM16IQo`-NLEq3to4@v|V z7Cm&BBNXaKkH1x0ehC#?-pU6jAvDAJMaIkzG!dAq|H)2Fv3yP}#eh`1PXWV)84%zy zN6NZKKt|>dpa>Fulrbc;-Oc=GGDk|YY=R}ITQ}oK^Zk1~K#+%##QYLHpUv;{amrwQ z6ZaDsyuWBNH>dJ4Qn*pH~rgnY2_&}kT4W3Kw(v8i{lXz*i zcEqqFC5!%65ba-y=7d)b^YL|gEC1E2i4$Oxt zQ33FbmLj>5zi37<*uIa0Ba=7e2s{Y6Q14xF&j$vHv!6cYtkuC%6^txlc`_+%O`gjf35c)M_Wq<RW+GC%5RI2a+}>$5;paL0UHOXK(& zskgSiD~8sa?v5)%`efWbL_EfjSFm|}Mj<6qfpdJE5k63=W2B?#zRN8TIWFGzO1 zy!|M8G4|>p^*m-*yd;87|Gej=so3|SiDm%FGVCWz%&w(R&b|B#~c2O zpr(eAQiUy5>8f1#W&UesNxDP~TE1m;Q`5^@k*^GjrHs~z_}WwF@oq@lg18}}=+4bX z#j{{UDo+|(!Qn6Dxzm+jeD?0oMteC6L6&$l6L-ZNn#-QPdS;F1g!)Kxn_>uBLgu)n z8EZV0>#n--{1f92D5W`RD4Ht42cc=u(0;F2Xyf91`D`!hzfoX{NJCNJf4@*YjT^^K z!Y6{%k}kZ@@4VR2x@pMmvoAtp#99~HN-ccrm;KG4vGVPuDvi=Lr>2+bx+MMo5u}|| z&RtfykOvyI`;v5i5=+5dpcwVZ_xCrT3#c|ZrZEpL=;nD#!FKK=gRJOT^-piEs+a#P z^?hJGq}A#?WZLfmTpTvY%-(5#x;ku-OqR;t>|?d8_j?N%y_!t_1^%!Vb2sJ2Ff8!b zcgi428Ckidmbn0{YtXal%|86|OzdP*{1CasQN0#ui%hE>kcrsl{^RZQnO%Y@yan)V z?(Fr*Bfz*_lL|fl2xtt>*&eOE*8CFuLWN`aW8AwATdjwEeoBnHrMx4V=ZJ$S{!G<* zDe)kx(V!m$JRG!EiF>kF=f;`&n27X*cE=5YOtpptCF)Fx(|Xe$rUHFC;5+U-#Oqiv z3sY?r@6Jc)21Dwk94sW>&5+lsa#gYZ*4bd5w5Ry9y+p)Ab~N>C0^0+?<*k8(6U?H% zxB0aL{kSa2e2Z#6Y>cz1Wi z{xQSw=#Id3@Pol~tiYGCk``YecvlbnCr8*4rO~G5=J^u2A2IH%_1`9Tvm^iQSP~(~ zhW#Up-dfB4!(r7da+IZ-adfqRyV$qi+?IxiQIMho2#D#csl9QA&kSrnM`_hP-Clz5 z#KftfX;q!{4E7g5pAlW%P>{#He((VFXGBY{0)i~6n@Gi}JjeUxp_kehkC17hbBnl^ zdo&RBVLmGSTCMWc);zni9y?Ab?hBGh0x5$!q|QwTa;9)a$*MR|e~H3ZPoa%N^Rrdy zp?Ti+W;C+|B0uwH^Vv~LW`&}fsY#{fJyX^Lc&M8v&;*$WKOU<4%ZHsc*^MbY;X)+7J1G;DSjg zaW~^}yHXYu`3Ru+s)H04yEB+d9{FyfAzXjNn|Bb=n1q)flC;=fjrHH$x#t+4XPH+_ zOMY|o8=AC?pm4J3pN*Qt_7})V035KgXB;bx z#cqD!4HGCPG2p63LYh!^CN?8SR?<6LYpTW3#`#MFSt8XLeZx z%-*#@bf$>0i&S?>?~35pNN&Wz2ZFL=G)?_n`qxNNbEb~=5n%t+b2VsxgA*F>h{Trp z_+HKo{o$WE(8TQw6PQzbQRPA#$bj&PIytRD_f@ki>SNkQd{h)Wc_VaH;}s|X8x~Ni zSUDoHSEM##u>wl_6Wgt}GjZQ|Ae3SkbQIyuB^y>}1_77}T$leopfpe`v_2fk)VE= z zoc-f>Qu;Tmwnc^-J?T_+7^;uVtNyd1654!R@sRgCASn00--Ylav#!=j zhqAqfu)qC1f{y?P7m}lFXmrdhJ)h|pHjbVY={nQRFH&z|4%g3rJHL!wpp94U3z33} zjdTTM`{GXY=Tnn;`0-BlX=Q%BAiFOLk~GN5d7h+`Z&#n8PpnKC@j?8AQiSue1~!0} zLYVr0LIyQTgHC3h6ltEB)u$w##VkNn*Wjh$!jftQ6=T~Pn2KLhcb+yQG{$<;jL2a- z4m!uKG>i8NO2SPnzOo&l4@gok)rxHc@8oHZuUr!e*uS)Bb8Y{RYhVe;hbxmlj!fD) z7|IkhSr3$J!#8E6J#qT|%O95@WwohsCLToVIm%LBhfFJD=S}#1>$V4%%(X^)@h5;B z&R1RjBVV%zF`|_0NFM>$)Crg`{%wm_#NErG0v1p*E&d0?WE5sIbq&%(NUM=|&tG6s zg=|6NfaD@`uB$CcBE0W*USkz4r4~2~%#43`i`@@?@$`spig*5|J_3f?(|;MEwZs(( zrRzKW=K>XA5N6X=ld52;`4laNDS?fYIjLP&vL=82lfA9Y1P~=J$$41gCb@-d)?5F& z4$qbtN#RT%lHEb+uhhL;p0%Inx-pS>iYd<5YaL0{M<;TgvwTdJ(bofxG{q%>9_V5# zoz->?vhDq(?VJ@6GvNE*C?TFwp_Zs>qw|+i&<*qHDIu?uAiwHI0JgEOwv(&5xjo!M zwFb~SZ!n#P;LX00gi;xstTj@*t(hddYQI`g1YwveC7`68c4#*q0UFI8JxRCO9c~$S zssc$LYC9ott3d&K?r^$K9tG`6gt#a7&$Z(4^~%EyEWsw zi*wHh>~{wvd3VR#d|eBIXAVK0fe8^ua}FN1USgs|tsci6 zv3E0DpR<{UqiuS?&)s7;OdP!h;$hH~O;E^w<_?wv`BAririri9AYRWL$z8u zeb@U`V%+^ z&IqF&bh>Ne27=^(&prYS>k+_&3~8I{HPLpb*(&ckQI8C{f5;Q?-$wwWZ|XRcD7Q%r z>%B;)$>*yz!$JM#BZOx@G&Idbqk;+zIkQ6lWfuvAJOYA5bP)%qYxjIe?S8+Uo5)`r9m->gGa7kk zS~;P}yloZ=mY=BfxqS#M_jnyu&>n|9-bL87zPdfmtvgKLevB5Rs+T<`bz)#>Fu8&B!wvIMXq%hCHW- zyAqvDx?YX3;`)04qleza-h_~VOx`P^j`#!VzwAzoH)TaY5ECd}IMH&w=|w3MnOH?L{dg9kgTZX{WhCndNDlo4D6w6+t&>u?>iy-|Bj9B#kiendM5-fs zOS#MGhxAB=!7{V~oyp!VW3@0Je5%H7@tO9MG)tI0YG$z*neHGR`P~{koO?bV|HtF{ z@&klxI>Sj(jl8A)>OQFv*w#NEC}TBHF;XA z9gPpQhkM!WB1!auf!$2A!9A;qevg2jcR!%Uh)K}vUyUIt9eE0frB#q|o`@#BavQyK z%v|Z}KIbDqVP0Mr(S1UsfrAT6+gBaAT+=%rNob-K5|R402o* zrlCQw=Po<^9-U&jdp*Wz(C)jb^U%}H^_Sej7pOju0?{Uk-o%s+5cNnoUuI6u1n#t& zKvpEtglhLDq?y&ou@mz;>3`mRt#@0CBauB@DG-|LX8NdM%~dr`Tlq}% zZ0#(nk0aKU=zt&I*@0fAyIwSup@aY10Wghsx>!0^ae1urN^uK9_+2V z`qLl79+Li-RQ6z;>M!05$#8%dPt3V3h)txYzPcwWWd-?CzBKo{_>l~E+{-*A0ELaL zbdv{SBE7ace6fhsDoH3@Ty*V1ZSuUit$>1x64nMRu$h=m%I?>uM71%&GV|Aq`cG~# z5db<6!7lRD$(MF0zWFJ(dw)|B19z2pu=j~Ow+zcC5ma%NJ)ZV0*{wh8<7{@QN_85e zz3M9~*2AOgJrbDawopsRU`pkxwEl?GhOXhBlo2}2)DUy9mBsk`h5!{)^K2l4jPdeP z&@wE=Pi$t3f$F-n*YG7&5#O$z{l8Ybu*uVv;tqAR9^Nqi*L7+Es0`EESOG7ME|Lgdw9f&L&Zj<81B%tRZba zo>B%izF;Aw`=8Dq2IGLA@7%JpHyDx{U8w5?5x+I5{CGs@0J?R#@j<_zK_c|#8>gIX zW^QzmBl2{W5SxzXM*Xfj`}wkISyXoq%&@(9=ue|!K!Et9UBsvFc+AV<4_ulAN59t1 z@s@-Ix*ya2G2&vwPvp3)X^8&Z41BEiR z5V`bHch^;-lXRtvF6nZ%&&<% z;h{fz32QECx-L-VNq~gF`RcrQlTJ?WMUb$edYp%i0uO7RYBP@|M}iW7$G_hgBU+*~=p(}Wd?V%dtuo;V%o}+oPdYGjY zeA6t3nqQr(le2IlKPBP!WIEn2z5AVoA^?|x^Vt@zV^BZkkM43aS=_}}Yn09Z;3zPT z$3(Xht`oa0#?;V#J)0It1r`5CTQ_o5u)7w|Jm^)Crb?|*P&Xp-OjX>n4d7FjHQy{d z0*lvGhxw>RYO#p(hWy1*+NT<@ezr-)!p`|?*ZR7|MJI18-t&c5(dF~qcss^qhkS=I z5>ByyW%{nCb-AQupZD9%1i7i9R)=5mU|(GEcGJfK4eI7TeZeRhB!$Gp9A9I0maxxK z?zpr3R2&tf{?&5S-<|vb4IXkLd zQz!fNkj;TQp1Hntx_Wqhx+PFYarxqDd8i(^_a6b#d?HNddwhG-&-SpowBhF8?;z3D zs9{4G-KapJ&p)bbyhte%nWTb&n$@-OvFCxpjwx+-RN|*b=E4t!!EccLE1n57x)~$y z!^s4kohgW3NyT^AU9i@BxzHhx2fbgHA_Mx`PcOEON}K9CeB-dfBIT!poBlGBATwdd zB#aJs=K~fr&V=8nyJ@?=Sq60MGzr%xWe>&II`$BuoY&U8mjfx-fbXl^))t#Tqs5RF z|8Uo~9sz@2s+8H0a?joV63w}w0$`HI1t8RGXmpLY6GtbneWw?iv;16!3#DS1Zi!@o zeTx3>wmm_79{{BoLr(g{0BD=MMzimkvsjA*uZ`x4{t0JPmp{GE-}8JU9>HR6(sm8$>>Wu<(Q?tJ+f2#d zFZ3e~fJ6wa_+XA;mEV+^tuZvCzxEFSF=R)#n9~{l)ZIp(y?GsoR-`2}4Hgz&r*xGT zKh_dY2o0BRm|M(Y)E;}uqIlbmm~t^X+8;L+S#6no8*a@G)y(vA-K3IIqnb~kS=rMz z;hGeHx()fcEnFv^5?D3UhfG>UpRr?o5xX^5?aqA2zOFXEe;3MP<2}s+i22z0t$d^` zL*&8HCH^jbR<+-kP7_c(NTH}C1yP&St2XNgg1LxD?fJ5N6bgM6XZ##xjDN3NQ{!@W6WW#R*O zWh=52k@>z+O`02K5L@$SiR4Dw*1pi9;1X{y_P9|qWK(1*sx?3RsFzW7`*C8#M zXG!gjrINZ^1aacMzcc(#+a33Vxo`6x6r}K#P`R5s(At|~glebkOiIPm<8~_BW@gYL zj)sS|v%cenr(aV?=FG#jh(2_<=UIuZoD=KI-zg83dG^rde@KzPpeWkGeMHL5sM^aORh@JLQ9oV^@fKxohNq=Z7ST(-&ZRMU7 zrMECXL&n;t41VLD_LD5XU*0p_g=JSujZaJv+of!L=PRNl4M_4=@-h{5OBqt&*^c}r zc_l)djJrC5y3;YY-#p9j?y4vs$gmWjCcHx|=FxiI#=5QT9jdXV^hp8DuZH3&0q0>M z2A}3x=9b)t>F&IawahoxCadcYbXxJm@7XE2uCD!_dmL-|x?gUIr1wI1d_tP0^rHTR zGN`=V@H;Ddb-qxcNrloy5;&C3l=>3ge2h|eqnKJO# zsk6QCg;Zxj{@!w^(vMfbtQvzpNIlLjnmbc(si{NxQzqKb*pP)sD3@}jRFq5l0l56Ouu@QWoK>eQp@ViP*~4XQ;=z*(nqhW{v``5e`2rV(-MOhb z!P&O+{!Mvoo6(aqAgfpE&M#u~p7v7yaKT=y)By!?pwGR8GX$|3g{CXqn%1*;Kl^5- zKS5M0Y^LH~`v}ya*>@i#VGyT2TVF>>CA>JJ`44<4geJt8C70_oI~P_cA1xcsI;=zm26}%zg;GHJmHnj_G}p9|dUJj;`qet# zrxw(azxpaV)jUswnQ5NKYUw0jeE#h!jP0phOkO+BA7$WXih9{>;|}?4C3ZSnVMmB> zDL1Vk`VJP(Zq+Pa@|Gl>%^SiMKgA%R0o!ClAwIOl)2Ig)c@4?8Myw^~^<8}zoBm}8 zYsTfGChoKg8SOn(PhoQ%HVg}WBj+yZGbB)y$b%gZ5QtzZr~D5)BOV~TpR#Y~^qtt7 zx$B7a9(_2Yj-}~9{Tzq=uj>dCiB?yu%}QOE7Y{z#OX#SwJi-L~R=n3P-^cV{KUdOX z17CqWo5*kI?k9Dy3o#z8)V}^V=>35(@;XS}P}8x&QFQ$09wlCSAM+k-gwhrn%nWjZ z@F+K}kTT9F>uKM8F>m+r4KL0GTei0nn+<5vQ z5jL}NJg1oS5w``!yOvLqt{&@=!_pN2j{tg8#Ss1ZvBs21BtY*GfPd_IY#dLWagwTj z2}r@aADLs{GWf+zhtxxSx>St~fDj(mM7URov`$7HRgiMOCkyMLUPqy^dT0LY(4U!0 zIbE$*g3Irm40r;`ils=6UB3s5gT|{N10a+>MFw<$yx$`pj}Mf+5C9Ec*2S>{Od)x!DG63dO2mt9oXKVW4YD0p#^4s?rtKyg|6}<9WrHNZkmD~66 zDQ&XhTR_d(%GE#$WQ^BKhJg`mw|_B@fMdOtU;^LqSMeI#e*4b-VsE_<7kfaEtqN#^ z0y@D_O1|vS$%b90TvI$*i2Ds*!pgb1-@QyA8DcV<%fhj_Ij)3_fCcv)`V}kJNn{t= zoUqZjI^X>JM}lPTEtl*D;D+kruyvMXFiO8OPxm^J_73gY{<38o?DT1&T3C_yrf5LZ zCpU25CuWZp`k94%06c$Ii=Hb-d3u2s=v{cZD0G49%?*9cyf=pNftc7%x`Oh&b=NgW zgLo)2-j0^hyF}b$cv?CLLKxjZv)Ph+A*A7LYe}<*^=n?cK0ec`l@!1@ZzpKI7geHZ zoS=BK1)HCfe{D+X3!^RkL+-U7=^1`*e*riUk=L3Z*61XqYC&yzgv~JTcL8s}59u|DninjKXLg$%E^T$Tq@8ZQ4; zC(dVTjb-;}esxm4&4X^O4u3iZeu}0Ml=$ou_c->{v2l#HB#N{ttJZ0 zWm=h2+#8}N+A~KqNKL90PkH_`Oq($bPmGd|vzl#%5(SU7M}-D*cvK%l8AUpd%_P|K z`-e5;SVBMGs-DPQ`jct|X5E8P4s%V>=bqr8=c~Q(IBj6tF{Wv^8UNd!?b4GK#3k$+ z1`LPbO3Cdg_`If@^;{B2`j?9;q?J~#1tXoF^15FSmBJsQ%%5r^UcQ^A3lY7qJpy)2 z0=S>kZQVNdB}%Uo-dm|6HJ%LS2s9vaVuvjJ({DcGbu0D6Th0ry`<#?zx4CK$xh2VO zh^4=HBq6n!?Q>I1&T%dYe)Q)a(733CPx zv5bESdZXY^c5;0$a|C2Y8Br&dBO4t=Uk#l4jK`|h_~Dl(EYGm#yAAoDpL)P+Zx|ku zyXiDNwxk)f5v8$|bKC(tc^akhDv6cYGN!&Wb+u1GTd3`mrT8Djk)M`f2H=PmYM6U5 zXRgV|#HJiOPj&RY$`XL58R+h?YSEuVYismzmOW|zeuhsO1>xHKiS+u^svk|wc+m#R zvqC+i0o3_@|P94UsR8bTK}$vF#1|O@R-) zF}r|5M-!6WqINnq# z5?mI-dA}l7cJ|T=y1_C!Gd`vD2(Ue(sf=EE2CzYuSfR?|29|zJ?3*5?j{9wY<$5Xu zRq#3qGsG#?E$|Ch*AyGoT+>bq%{`%Jv)#N8)hKa& zJTA%^uWF;wtSF*~2DC6T#^rhw-%*QTohMTwvVmBQ{va*vrK|W~NrR`leceA4E3_Uu z00xnoga5TheoubYO7GR6EY&Z5yZeePIOzEIHUAp*Ua%9ta@UJz(5CeY;MiNT#m<8f zC{V;Ans_nIA>&s(%q=f3$@Cgvz`jJN$%BazItUY1lA?U6d&Rh4>_ARVz?)yB!)&Kf z^BtR!awPGZeg-h}%^jbPxrDBF8->C?E@H~K1-{nIsCb+xmi7p!HWtli z%>B->jwxe0wscjgvR#>rs*>dl+ketXTp1t|^$;J)WRql*%}2n3el-f@JK~5p>}nLf zU!6y|_grfB?8H?_na7xi!g(rWnbgrfVdtmqoHZXuF+iOX7yZIS#6fr>FY;s2cp=(f<%=M0K=wZBBf?@^Y2dH1CR3mW z{3eI>x(TYKBXEP?W`!i&aqjtC8~))>P@EEcCf;kOvJFx%CH$8m|IJ*ZY*_wx5li2= zn_lEnrR3q0LV41nGq?`U1)6KYT&Vv-2f5M``Wf7KqL_31Z)!nLJj){>>GDWP8JTw< z;A=PVp*e6(GdvhO`-V1i^~N(&38VltPSS$^8>lu>Pcm411h}}wN+5{Z3R>r|-@SK> zmxjH$vov7hkLd>9P8ARBfM`wo>nYlq;E_VtUJu0RG*Y? zu9fbQxT?iP_gggcC&E1;D-(k^aDfkeA|}37b0q7H7yQhfwof!G2(IwtUp)CW^-)Vw z8e9CNy@NK+UJPCDc1d>?oB*1i{nC%~pCIT^;=@-zETSQe1~KP`t+sIk-DHu|f|3dU zc!h!`a20&DP`^~-UMZ@-D}$Zy_wwyT<_3}g!mYEbGQ-DyKQ zJjEx}uj>R=ku{f_7?xz`(|t`JZYm3Hs-z}w3*ulpWM-d?bHP(=ihKkRp=dr&buY=n z6Lb0bJbw8#j6GMzr`^_yVge674O(nLZhX+^ad>Bz%;n@dl%*AXpe_3s@B67m7?kQv z#7W1fC*zEOTD0}!v!c%ibkd{}!I+%}7Vzr5>&gDem3~7 z-tu;n4bBKGF*G7aQ-1HE43ms)k`WC&C^n2eqsB;BtxuHI$(@_seM|H_$75t7w!z7L z(mVWxT|QUeN-C)$*}K<7Yp+0}bGfeKPof^7$SN>&kL)e0Y| z7aNE(DI`pp(bpr@gqe$%t^1-GB3qk&XAfH%jtRSI2v=!Z)gXWHgZcF>DY2$Cxce?T4^=Uzx#;bLP;h%K1X&5QH zl&THy)nE0c3Wd#QgU3_H@uh$}BCNLzgKqV8Sd6iWM=z!>A^5a1KZ+xRj#J%ENbHb5 z-erpnhWz@8$JAOYiFAVq`Nqm#rV_c5+jetussYsz0gZtW}GUq zM;E8?x)ozt>y(_3FXb6WLEM|cq>w&g$diPL=O>wl!fSxUhN=^ffM-cm>)(EsCiLSN zq}MGmD1r|+BY^OCL0lldbJ)l*l+ri*osUe`_9>%-_dvYUrERLBbHJ&&z)%o3JPb_$ zzNZO%ohsRdcVqiA;OnZ!ep9)~deuPNx*=&0PC#v>3?nk2pT#LqXe$U$EkqH}*gQct zrr-W*hl1={Eq{-k>{yd$pvW4{T1etMf-CmR|D5;E5+Y&2k|d})crS`$Fc0ezEp~Fo zb`CzKnwCC}atZrKzfr)kSX*9Iw{`nTS&k)oMCvl>*j(pc13lmoXafJ!Z}>I}_O*B1 z9Hx=|PPay&Q57ecC-@H#uAv#zgV$7<110gz^lIfu$g40LA={$&#yYehL#Az)4hIB` z%yKMR$8vaF6c5IY-l*FTgK7M(QRT-;ar!F@t_yg0@?&e8K442b{TdLWtpitm_{$L5#!jF3LEr!AQHO^g_iePBX9?V;GD4`0y?YXfeG%wdUtNwu=L_I#!HRB@u>%<7yTPj!T; zAR~C?jm<+A8helxsQ|YakO6YFUV5H#2`4A{48xGwXNtu(bgPMB%WfKJCJk~>X^2Fm z#j`^MvB>y?$A^{#VQV_@E>K6^h1oaABkw(5XW#-JibopIP5M2I`Kok>EQ;-eiEcEc zw_RHU!8Sk*7rt;ziO|Z}udhPCKBQmRA9dD!b$oe6RY?{v+{`x7_CX-A$r9P3YW-rp z9NTlsZ)w;f5<-OLa7Z1fw)bujs-2t+%SH;_#6N`y`#|x9Yo&RV_z&X(2cafbCW0E( zC5t(LSXSQ*vqqa3=*!5lPJ+3^8nymgQYF+C*Oy0tL=RYMPk#N!ASCXAt#p^`BQa&D z!Uee>NC0vi+h*h7(&$H1$J~ntfXxK;wn&OCh*#+q8w|6~-#uEF82)W#*#?kl*@WE&YI>)nYWqq7+3R=0j+p>en@z zdPtFNl20_0Go<^|1n8!{O$vyWSd;yR8Qbu0ld#|VZ;(5!J$S(bZz+-4L>A<}S8|pY zNsSs#wt>Ug7ed(&?;pahESB$Ybl{(bka*jUo5$R=ZzcAoiZo^X;b&_6!Rc2KOQ&xU z&xQpGkbYZ(YPK4e7UrA(QPKPycyn-BeU1~Ty3o|BKcc&2+1j~ktmX8A#qThEr#;T^ zWvk4`lyA)6KnJMUybxXNhqGOM{c2Auobb}aTmz;ZUPs?dcXdB0o66`#DR2;WvBJcu z#Z4vd{f^9!@B6n%(1tX(FzSQ-x7+si8lm`!#04OV*NB}%u^j3m>@KOt^puk=e=&Xp z*pss#N6k=y`+F!{oT{^THyC>W`^`Pu;LRFLb1}ANN5gJDN4a3|5+^b^IGt%^==i`a z!FvSjyNl!Sf(+aGOypba2TkMKY!a|)BA+Eb{_d^ONRv^VRvnkgzwhLtP&Ru|9?+#( z_YZv?$$av6vQlB_>W5+Z5#pko+XbZ~N18>a%hsaAksp3_X~@gi7YOQ~Bhz6Do6|5+-&Sx53cq@ePq<+U%?i6Oa1 zkHc58QAqB>8iY*dyN@Bbxh8-+FWleNv7~&vmU?9XU9hLMfk%>pq#w*6IHj%LD~gpH zqYOh;R2J~yrPD~0u0y9Q|A3MK)E&#-*m@o!Q+=2wIIEEMTlBl+)jEzJ(S@XK&cU5Q zTm)3__bIGHT?^Arjp(at>ObEL)=Ed%DyP<%8RmKc2qVF_=5&l_iIuRcct!&9BOi;K{U)Q zeHW#+0JGON+d_13s|D1)3$vOO%5R!F?tT>_&#Ees`|PR)YlxX6rj7D7BLZ6O*OSm` zLRH)_p6Xu6hT9#4Xc^Kl-nmg$EaocT`XryYFrk6KJ;5wF%n_e9ye?bX;n?N$H*J04 z?V)=Oid+4+`X)OqLV?k?xiKke<3)Xoa#0?mrR&PU(%s@|<|&n1Bf;s?+#cs_V>QHH zlGCZaPmC5OR*{`~iosnY{Fm@R+#%uv72|2(PnDqWn8sfR}o& zbSYkOy0h%Ok3Tm;E0wCt_yklrnoMQTw`qe85}MtR`CLTz39Nw$O6K{pN({St!0(61 zg=#(*f>E?yb`-3lQWQc7R)3k|bic{X96kyfPVpiE2FpxdJWD3^aYGWS#dtDBk=5%= zQ{BLhM@y^d-}@9-3Xx(-kAaf$?sRILZR|U{QXvE!XgU1WJhxPd2##>J^{3Bx0ke%(u zTzr0BZ&Anw=bi4`e7Z#z`Mnjt-)RZIp4h@gwY4Ma>A=x!p?nN&(1YhnH9!5EIzCeI z)y)UTq79mPKHN+4X^+eiEYQJa$;38yoNr4E@5KO~*prln9_Z<8cQ-*;?0KCJ`Xn_v zc?PbY-^x(<4jBZt3;%uvdmFA4_6Wcl((XWdiB!Jn?3^uhCbjsGwD$<;RuReDadH_j zCz~ZHJX&lKQuaPcq_(!G6vJw=MOqDMt+UO1WE4ZTMS<-^oAb70|uq(KuB!Pj=0BbY0H91Y8{ z2ZRpGozDbwgGMZvovw4dTk0s?H75tjj?Go7k=ZK64n=9HlKPDKFSw9)TlZHtWov^& zN@QoGVCE;5mY8p)v)_Gr`h=8A525@0$JtT9P34UYYf9oazjOEjRRK*bJKH(2PEt%> zr0UIgWU5>SFZAYQ2KAhet?5*$tdj>%vrUznTr`kVO zpX+<3_b`%;7v>Y$M`aPJ;-BZvv)Wti2~kN;5CbQ5>jz3FD*}g7qTB^FHFbtKY6>bG zG<(##@&%P9n&m^Fjtw-?opQ-uueMsvdXo{(R#&^k4`A)3LG$MVl}EwEb}r`(|FrTU z;ZA5T?xS|E(LX;{9lSY`fZ*B5Esuvori!llo@cDuo)CHmLOhnw)jKhDe=$Q0SDSla zQYQ;d)$g@SGX?Vs4_Dj%Sm;H84kapS#BMpUY8RW)&p>?>GnDKQYUgXQt6s&M-vvfY zk$z*RQvpwwRv!?_u{5NHf0aiBTi6c^)Ev$38r3I3|KcjVuJITK!qvG+@RViPkP3(y z*(E2vw|*c;jngD`0jjMh4ve8EM1o^IpEc%1fVFcXzSztQG}RLe<`O)I=0vU_sLy_T zIY2dAveKn<~)8$gKaV#W~){0?NPm}$?hLlI32X;h5NOlck%`*4t4vM`DR*@N^fTYas^UG61 zpS$tGR!UFjSpNm99UP+YG)DhLk?F?sS2#cE?wQl2Yic&!%O3$^)sjwj?3f2^r7{cd zye^z>YG}CG zCopQrL-7x!&{W#eszhGv(-j*9WVe6a)N@QDweE-bq-DkbUjRuBw(_O7@m2M)+XdCg z1MZ^4hPCq{*4kCu$ym&7>DOr$f5Q5{k7*wL8{!7DqxAm(M=sJK_8gz- zUpM~%!9@N%-srv#lSQ%dyI+<lr|fU>>r(Lc zqaK5(UN|wf7jy8-Uvp_5GK*NSOSP4-{SW0$ztuxXGbRpt=BZ1mMu~v=Abvu!PN=4E z8M!3jX06-mvMI@YWOVeaQR`s1DCA&Z=e=8tUEBih{4-V~)lR@;2OT*zELw|TmN_G* z74;3ivuh~b7%z^5npm{}N!oybayNFVP5%IxFzTdZrtDM`-A9eFqNYXbLp86GGw$?MA z3n&~^V&Yia_i>;&{w4#1OK~_v^DZxK(XrFc>A>zQ&ps{R+dY)OXTFA4^7_Pc&3H@e zR}kG8*@+>rbK14-yj2`989~VdB$Hnae%+ompTr&@7Ogv-(-YUVct?cvGpJsylde%) zJoGizYTC3~YzEfbBLf_Eu5#m8y_Rp17WU@mz`Pfh@nUbDoFKRqyk78&T7;e#Hg9y$84W^vbz4oBhBa3SJ!D3xm;}H&>VA15ZHD_4mmva z;++FXsxt^YmOi#e#pywIE^n|S$K&{M=L&4-sc=mT?#c+;&4 zmY(R091*lsQ`p-qXUV)(PYHw$k*IJc))W$3DE%yf5HC75qrozQv`v@|sVX$01bn z_}8=ed*K)C`QR-=4L`@e0-s#InbfSe*RrC&R9z6JYf8ZO^BAm-=PGgwyk7J7DwTNbrG=fJM&)sq>)&Brx zpB~F$cD4^bWwvp#n2o@Fe+v4?L-^)W~!kMKG|mzo}JFpYdb~#rMv~H->t{RAAmY!>Ki4kW_xeaGlTyCeAiw) zb^8-|(f3>En%9QpWAlrBYjEed6Dp2AwPXGjSHS&XdEOKF?|BA6+Pa>QvmxWA=nj7q zO<&p5#G0B0@RyH#EvvC0d1F=<@87D(GCq|4-9Fs`H^Zmn?86`XcbT6{{YsmPV`yD zE37vJf%i-Nryk=xQ(?G>b!fU|usPzUH*iQsZWXiHO);CvZ{6KTgV3-Urd;1+=KDw( z$2sPpT}EI&Ny9Iudj2%{bt{kv*o}kE(lQ1;Iixy;#{U2@?%;(-UGk6qxit;nimffb zcP5~(x9+NE4fF$?Q-9$gy1I`xwokR0`FM4n;&~-)CBzisgq36?Z)M`^9u}SM<*2H4ZFqi z#HpTyE-_Hcr$vzKb1?6>aO?D?4ID!SiNVLtPc<;Pj{zCM9)KE-YnWjKg(H*G>qxh| zesnu|>@ijKi6Xw!W=D~CZOZO7^S{J>ZhsBy*)0^&Ir-LHFR>i^R$TW#4*W@?T>ZY| z`#N7NmS#MD7#!Eaf3+r`qebKBE%a@6Jwi4tcSjp8%rM~Rui;!)q#RjCZ*Lhc>;}~w zo(2VbXYA{&S$saZwzj{ui3<^jZLD{YIXu_aH~#>#*N6TqXjc9(y77LKVE$hAkL@w; zeB_MR`|={sZ{cd_6JoZkF&$s6(S3 zL9d*=Nuy7t-`r`_C(M!&h98wx_mXE-!nv=n{vY^_HC+xSEuE?B?Ohk! zBVm(|V6~kigDy*CW|nt{cFxO-3MCGZd%Ub&SIgk zrFkEvV_a(=V<*qQjsO58J^}jk{uK-!KhcQ=FWP1&Ai)uT$bpZ-ryeW3zbE@Q!uo`T zhUIxsAU@e_RBU`_cKhJ6v$q5ceX4elk5RP%AFWRYldn!c(!4@c6Cd~1?9_w9 z7ApIsNv2|d<*mauPt$?=Rogoodtg@D(m46xs*KgFNeBTP436#oJXEW2?!#$L2OzZu zP{VOk&r&IT^nmmOu2hbi&35iem`ehBmj3|j(*cwn(-MAetMsL5m&-fgB=%xC zt_$L4!s~w*TFEuL5i1O@HQ_!p_&apG-BBv{efIPFFQ z?dJz0j=k%>wTr_)4|JB(6Ifl4C>!K)lj+7!R;+NHd5vBBizbBeVVs}m+$cmDui z6!p|$BN6V;e4nK!_LZ}-!V}I8K9wwYwyZ-U9(v&Psg`SZ7-R(Yue6g|xE99n0!jmb zT>k({zu|u!c;@Q~qj-Q>l5nihnF#*?$Axzgd^H{|fJx(z9BcZExz5OMg{(?OItY|8 z9Q0;kSz7nO{{RB`a!)f&(m`O`gHFanoDOo?=BYp+v|l3H*%3NzQIF+P7x^;4oF3+u zNj$XkHs_ErNgVPp-^V?GspBP(kT5~*QLM*)%zX}eQp+(UWk)1)k9u{X6K--bx3E2F zW1GxnUAP<*gHTCw0}x^aV>rz!Y-iYG7zeNCO`butgh04F3(uB0Y<2dhnaL{Q za7h{FtKD2kHiE~l2R$=UiCnQ##DlowKIBw;ka7^`vEA=Yn&v?fa_o5B*Zf6SZBd{` zoWvLf$yRQ^;at~={9UGN5KE_DcxfDMBXOVlZLfyEY;T5M92d{6>Cv^jmL#CT9R5|| zUK8-ykHi-D>3Rc2oukVC0PEM)zXd#1uU%S&EP0JLE^WvzSSl2 z-e3p|$nD2GS6F@?_*>!RaNcQl^T{qST1ognhAYlKIa=x3n#Xi(LOF5?4W9o1O8NKV z4YUy0+(ME4*#-&i^H-beejQ7IB^Nt)91-Q``qy>)KF4#XNMrj^brKu`xb5|?ar^Ox zJ;rhVew9jOEh)p0c4swa-g!RE2|Wk@0A7W-kmLh`JNneIm*6w!CppF`W4MqL&qIou O8`*XiIOVwZum9N%!T