Merge pull request #25075 from mshabunin:cleanup-imgproc-1

C-API cleanup: apps, imgproc_c and some constants #25075

Merge with https://github.com/opencv/opencv_contrib/pull/3642

* Removed obsolete apps - traincascade and createsamples (please use older OpenCV versions if you need them). These apps relied heavily on C-API
* removed all mentions of imgproc C-API headers (imgproc_c.h, types_c.h) - they were empty, included core C-API headers
* replaced usage of several C constants with C++ ones (error codes, norm modes, RNG modes, PCA modes, ...) - most part of this PR (split into two parts - all modules and calib+3d - for easier backporting)
* removed imgproc C-API headers (as separate commit, so that other changes could be backported to 4.x)

Most of these changes can be backported to 4.x.
pull/25216/head
Maksim Shabunin 9 months ago committed by GitHub
parent 1d1faaabef
commit 8cbdd0c833
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 2
      apps/CMakeLists.txt
  2. 4
      apps/createsamples/CMakeLists.txt
  3. 258
      apps/createsamples/createsamples.cpp
  4. 1464
      apps/createsamples/utility.cpp
  5. 124
      apps/createsamples/utility.hpp
  6. 5
      apps/traincascade/CMakeLists.txt
  7. 250
      apps/traincascade/HOGfeatures.cpp
  8. 78
      apps/traincascade/HOGfeatures.h
  9. 1718
      apps/traincascade/boost.cpp
  10. 86
      apps/traincascade/boost.h
  11. 570
      apps/traincascade/cascadeclassifier.cpp
  12. 125
      apps/traincascade/cascadeclassifier.h
  13. 93
      apps/traincascade/features.cpp
  14. 312
      apps/traincascade/haarfeatures.cpp
  15. 89
      apps/traincascade/haarfeatures.h
  16. 186
      apps/traincascade/imagestorage.cpp
  17. 50
      apps/traincascade/imagestorage.h
  18. 67
      apps/traincascade/lbpfeatures.cpp
  19. 57
      apps/traincascade/lbpfeatures.h
  20. 2041
      apps/traincascade/old_ml.hpp
  21. 2160
      apps/traincascade/old_ml_boost.cpp
  22. 792
      apps/traincascade/old_ml_data.cpp
  23. 1684
      apps/traincascade/old_ml_inner_functions.cpp
  24. 376
      apps/traincascade/old_ml_precomp.hpp
  25. 4153
      apps/traincascade/old_ml_tree.cpp
  26. 129
      apps/traincascade/traincascade.cpp
  27. 101
      apps/traincascade/traincascade_features.h
  28. 2
      doc/tutorials/others/barcode_detect_and_decode.markdown
  29. 6
      doc/tutorials/others/cascade_classifier.markdown
  30. 1
      doc/tutorials/others/table_of_content_other.markdown
  31. 224
      doc/tutorials/others/traincascade.markdown
  32. 13
      modules/3d/src/calibration_base.cpp
  33. 20
      modules/3d/src/levmarq.cpp
  34. 2
      modules/3d/src/rgbd/pose_graph.cpp
  35. 2
      modules/3d/src/solvepnp.cpp
  36. 4
      modules/3d/src/triangulate.cpp
  37. 8
      modules/3d/test/test_fundam.cpp
  38. 2
      modules/3d/test/test_undistort.cpp
  39. 16
      modules/3d/test/test_undistort_badarg.cpp
  40. 1
      modules/calib/src/calibinit.cpp
  41. 48
      modules/calib/src/calibration.cpp
  42. 4
      modules/calib/test/test_cameracalibration.cpp
  43. 48
      modules/calib/test/test_cameracalibration_badarg.cpp
  44. 1
      modules/calib/test/test_cornerssubpix.cpp
  45. 7
      modules/core/include/opencv2/core/private.hpp
  46. 11
      modules/core/perf/opencl/perf_arithm.cpp
  47. 2
      modules/core/src/alloc.cpp
  48. 16
      modules/core/src/arithm.cpp
  49. 258
      modules/core/src/array.cpp
  50. 2
      modules/core/src/batch_distance.cpp
  51. 6
      modules/core/src/command_line_parser.cpp
  52. 4
      modules/core/src/copy.cpp
  53. 214
      modules/core/src/datastructs.cpp
  54. 4
      modules/core/src/dxt.cpp
  55. 2
      modules/core/src/glob.cpp
  56. 4
      modules/core/src/lapack.cpp
  57. 2
      modules/core/src/mathfuncs.cpp
  58. 4
      modules/core/src/matmul.dispatch.cpp
  59. 20
      modules/core/src/matrix.cpp
  60. 12
      modules/core/src/matrix_c.cpp
  61. 8
      modules/core/src/matrix_expressions.cpp
  62. 2
      modules/core/src/matrix_operations.cpp
  63. 8
      modules/core/src/matrix_sparse.cpp
  64. 8
      modules/core/src/matrix_wrap.cpp
  65. 6
      modules/core/src/norm.cpp
  66. 16
      modules/core/src/pca.cpp
  67. 4
      modules/core/src/rand.cpp
  68. 110
      modules/core/src/system.cpp
  69. 2
      modules/core/src/types.cpp
  70. 16
      modules/core/src/umatrix.cpp
  71. 2
      modules/core/test/ocl/test_arithm.cpp
  72. 8
      modules/core/test/test_arithm.cpp
  73. 5
      modules/core/test/test_ds.cpp
  74. 5
      modules/core/test/test_dxt.cpp
  75. 14
      modules/core/test/test_io.cpp
  76. 55
      modules/core/test/test_mat.cpp
  77. 7
      modules/core/test/test_math.cpp
  78. 23
      modules/core/test/test_operations.cpp
  79. 22
      modules/core/test/test_rand.cpp
  80. 1
      modules/core/test/test_umat.cpp
  81. 2
      modules/dnn/src/dnn_utils.cpp
  82. 2
      modules/dnn/src/int8layers/convolution_layer.cpp
  83. 2
      modules/dnn/src/layers/cpu_kernels/convolution.cpp
  84. 10
      modules/dnn/src/vkcom/src/context.cpp
  85. 2
      modules/dnn/src/vkcom/src/op_conv.cpp
  86. 2
      modules/dnn/src/vkcom/src/op_naryEltwise.cpp
  87. 4
      modules/dnn/src/vkcom/src/pipeline.cpp
  88. 2
      modules/features2d/misc/java/test/FlannBasedDescriptorMatcherTest.java
  89. 2
      modules/features2d/src/mser.cpp
  90. 1
      modules/gapi/src/backends/fluid/gfluidimgproc.cpp
  91. 2
      modules/highgui/src/precomp.hpp
  92. 26
      modules/highgui/src/window.cpp
  93. 66
      modules/highgui/src/window_QT.cpp
  94. 102
      modules/highgui/src/window_cocoa.mm
  95. 26
      modules/highgui/src/window_gtk.cpp
  96. 28
      modules/highgui/src/window_winrt.cpp
  97. 1
      modules/imgcodecs/test/test_precomp.hpp
  98. 48
      modules/imgproc/include/opencv2/imgproc/imgproc_c.h
  99. 48
      modules/imgproc/include/opencv2/imgproc/types_c.h
  100. 1
      modules/imgproc/perf/perf_houghcircles.cpp
  101. Some files were not shown because too many files have changed in this diff Show More

@ -53,8 +53,6 @@ macro(ocv_add_app directory)
endif()
endmacro()
#ocv_add_app(traincascade)
#ocv_add_app(createsamples)
ocv_add_app(annotation)
ocv_add_app(visualisation)
ocv_add_app(interactive-calibration)

@ -1,4 +0,0 @@
file(GLOB SRCS *.cpp)
ocv_add_application(opencv_createsamples
MODULES opencv_core opencv_imgproc opencv_objdetect opencv_imgcodecs opencv_highgui opencv_3d opencv_features2d opencv_videoio
SRCS ${SRCS})

@ -1,258 +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*/
/*
* createsamples.cpp
*
* Create test/training samples
*/
#include "opencv2/core.hpp"
#include "utility.hpp"
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int main( int argc, char* argv[] )
{
int i = 0;
char* nullname = (char*)"(NULL)";
char* vecname = NULL; /* .vec file name */
char* infoname = NULL; /* file name with marked up image descriptions */
char* imagename = NULL; /* single sample image */
char* bgfilename = NULL; /* background */
int num = 1000;
int bgcolor = 0;
int bgthreshold = 80;
int invert = 0;
int maxintensitydev = 40;
double maxxangle = 1.1;
double maxyangle = 1.1;
double maxzangle = 0.5;
int showsamples = 0;
/* the samples are adjusted to this scale in the sample preview window */
double scale = 4.0;
int width = 24;
int height = 24;
double maxscale = -1.0;
int rngseed = 12345;
if( argc == 1 )
{
printf( "Usage: %s\n [-info <collection_file_name>]\n"
" [-img <image_file_name>]\n"
" [-vec <vec_file_name>]\n"
" [-bg <background_file_name>]\n [-num <number_of_samples = %d>]\n"
" [-bgcolor <background_color = %d>]\n"
" [-inv] [-randinv] [-bgthresh <background_color_threshold = %d>]\n"
" [-maxidev <max_intensity_deviation = %d>]\n"
" [-maxxangle <max_x_rotation_angle = %f>]\n"
" [-maxyangle <max_y_rotation_angle = %f>]\n"
" [-maxzangle <max_z_rotation_angle = %f>]\n"
" [-show [<scale = %f>]]\n"
" [-w <sample_width = %d>]\n [-h <sample_height = %d>]\n"
" [-maxscale <max sample scale = %f>]\n"
" [-rngseed <rng seed = %d>]\n",
argv[0], num, bgcolor, bgthreshold, maxintensitydev,
maxxangle, maxyangle, maxzangle, scale, width, height, maxscale, rngseed );
return 0;
}
for( i = 1; i < argc; ++i )
{
if( !strcmp( argv[i], "-info" ) )
{
infoname = argv[++i];
}
else if( !strcmp( argv[i], "-img" ) )
{
imagename = argv[++i];
}
else if( !strcmp( argv[i], "-vec" ) )
{
vecname = argv[++i];
}
else if( !strcmp( argv[i], "-bg" ) )
{
bgfilename = argv[++i];
}
else if( !strcmp( argv[i], "-num" ) )
{
num = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-bgcolor" ) )
{
bgcolor = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-bgthresh" ) )
{
bgthreshold = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-inv" ) )
{
invert = 1;
}
else if( !strcmp( argv[i], "-randinv" ) )
{
invert = CV_RANDOM_INVERT;
}
else if( !strcmp( argv[i], "-maxidev" ) )
{
maxintensitydev = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-maxxangle" ) )
{
maxxangle = atof( argv[++i] );
}
else if( !strcmp( argv[i], "-maxyangle" ) )
{
maxyangle = atof( argv[++i] );
}
else if( !strcmp( argv[i], "-maxzangle" ) )
{
maxzangle = atof( argv[++i] );
}
else if( !strcmp( argv[i], "-show" ) )
{
showsamples = 1;
if( i+1 < argc && strlen( argv[i+1] ) > 0 && argv[i+1][0] != '-' )
{
double d;
d = strtod( argv[i+1], 0 );
if( d != -HUGE_VAL && d != HUGE_VAL && d > 0 ) scale = d;
++i;
}
}
else if( !strcmp( argv[i], "-w" ) )
{
width = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-h" ) )
{
height = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-maxscale" ) )
{
maxscale = atof( argv[++i] );
}
else if (!strcmp(argv[i], "-rngseed"))
{
rngseed = atoi(argv[++i]);
}
}
cv::setRNGSeed( rngseed );
printf( "Info file name: %s\n", ((infoname == NULL) ? nullname : infoname ) );
printf( "Img file name: %s\n", ((imagename == NULL) ? nullname : imagename ) );
printf( "Vec file name: %s\n", ((vecname == NULL) ? nullname : vecname ) );
printf( "BG file name: %s\n", ((bgfilename == NULL) ? nullname : bgfilename ) );
printf( "Num: %d\n", num );
printf( "BG color: %d\n", bgcolor );
printf( "BG threshold: %d\n", bgthreshold );
printf( "Invert: %s\n", (invert == CV_RANDOM_INVERT) ? "RANDOM"
: ( (invert) ? "TRUE" : "FALSE" ) );
printf( "Max intensity deviation: %d\n", maxintensitydev );
printf( "Max x angle: %g\n", maxxangle );
printf( "Max y angle: %g\n", maxyangle );
printf( "Max z angle: %g\n", maxzangle );
printf( "Show samples: %s\n", (showsamples) ? "TRUE" : "FALSE" );
if( showsamples )
{
printf( "Scale: %g\n", scale );
}
printf( "Width: %d\n", width );
printf( "Height: %d\n", height );
printf( "Max Scale: %g\n", maxscale );
printf( "RNG Seed: %d\n", rngseed );
/* determine action */
if( imagename && vecname )
{
printf( "Create training samples from single image applying distortions...\n" );
cvCreateTrainingSamples( vecname, imagename, bgcolor, bgthreshold, bgfilename,
num, invert, maxintensitydev,
maxxangle, maxyangle, maxzangle,
showsamples, width, height );
printf( "Done\n" );
}
else if( imagename && bgfilename && infoname )
{
printf( "Create test samples from single image applying distortions...\n" );
cvCreateTestSamples( infoname, imagename, bgcolor, bgthreshold, bgfilename, num,
invert, maxintensitydev,
maxxangle, maxyangle, maxzangle, showsamples, width, height, maxscale);
printf( "Done\n" );
}
else if( infoname && vecname )
{
int total;
printf( "Create training samples from images collection...\n" );
total = cvCreateTrainingSamplesFromInfo( infoname, vecname, num, showsamples,
width, height );
printf( "Done. Created %d samples\n", total );
}
else if( vecname )
{
printf( "View samples from vec file (press ESC to exit)...\n" );
cvShowVecSamples( vecname, width, height, scale );
printf( "Done\n" );
}
else
{
printf( "Nothing to do\n" );
}
return 0;
}

File diff suppressed because it is too large Load Diff

@ -1,124 +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 __CREATESAMPLES_UTILITY_HPP__
#define __CREATESAMPLES_UTILITY_HPP__
#define CV_VERBOSE 1
/*
* cvCreateTrainingSamples
*
* Create training samples applying random distortions to sample image and
* store them in .vec file
*
* filename - .vec file name
* imgfilename - sample image file name
* bgcolor - background color for sample image
* bgthreshold - background color threshold. Pixels those colors are in range
* [bgcolor-bgthreshold, bgcolor+bgthreshold] are considered as transparent
* bgfilename - background description file name. If not NULL samples
* will be put on arbitrary background
* count - desired number of samples
* invert - if not 0 sample foreground pixels will be inverted
* if invert == CV_RANDOM_INVERT then samples will be inverted randomly
* maxintensitydev - desired max intensity deviation of foreground samples pixels
* maxxangle - max rotation angles
* maxyangle
* maxzangle
* showsamples - if not 0 samples will be shown
* winwidth - desired samples width
* winheight - desired samples height
*/
#define CV_RANDOM_INVERT 0x7FFFFFFF
void cvCreateTrainingSamples( const char* filename,
const char* imgfilename, int bgcolor, int bgthreshold,
const char* bgfilename, int count,
int invert = 0, int maxintensitydev = 40,
double maxxangle = 1.1,
double maxyangle = 1.1,
double maxzangle = 0.5,
int showsamples = 0,
int winwidth = 24, int winheight = 24 );
void cvCreateTestSamples( const char* infoname,
const char* imgfilename, int bgcolor, int bgthreshold,
const char* bgfilename, int count,
int invert, int maxintensitydev,
double maxxangle, double maxyangle, double maxzangle,
int showsamples,
int winwidth, int winheight, double maxscale );
/*
* cvCreateTrainingSamplesFromInfo
*
* Create training samples from a set of marked up images and store them into .vec file
* infoname - file in which marked up image descriptions are stored
* num - desired number of samples
* showsamples - if not 0 samples will be shown
* winwidth - sample width
* winheight - sample height
*
* Return number of successfully created samples
*/
int cvCreateTrainingSamplesFromInfo( const char* infoname, const char* vecfilename,
int num,
int showsamples,
int winwidth, int winheight );
/*
* cvShowVecSamples
*
* Shows samples stored in .vec file
*
* filename
* .vec file name
* winwidth
* sample width
* winheight
* sample height
* scale
* the scale each sample is adjusted to
*/
void cvShowVecSamples( const char* filename, int winwidth, int winheight, double scale );
#endif //__CREATESAMPLES_UTILITY_HPP__

@ -1,5 +0,0 @@
ocv_warnings_disable(CMAKE_CXX_FLAGS -Woverloaded-virtual -Winconsistent-missing-override -Wsuggest-override)
file(GLOB SRCS *.cpp)
ocv_add_application(opencv_traincascade
MODULES opencv_core opencv_imgproc opencv_objdetect opencv_imgcodecs opencv_highgui opencv_3d opencv_features2d
SRCS ${SRCS})

@ -1,250 +0,0 @@
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "HOGfeatures.h"
#include "cascadeclassifier.h"
using namespace std;
using namespace cv;
CvHOGFeatureParams::CvHOGFeatureParams()
{
maxCatCount = 0;
name = HOGF_NAME;
featSize = N_BINS * N_CELLS;
}
void CvHOGEvaluator::init(const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize)
{
CV_Assert( _maxSampleCount > 0);
int cols = (_winSize.width + 1) * (_winSize.height + 1);
for (int bin = 0; bin < N_BINS; bin++)
{
hist.push_back(Mat(_maxSampleCount, cols, CV_32FC1));
}
normSum.create( (int)_maxSampleCount, cols, CV_32FC1 );
CvFeatureEvaluator::init( _featureParams, _maxSampleCount, _winSize );
}
void CvHOGEvaluator::setImage(const Mat &img, uchar clsLabel, int idx)
{
CV_DbgAssert( !hist.empty());
CvFeatureEvaluator::setImage( img, clsLabel, idx );
vector<Mat> integralHist;
for (int bin = 0; bin < N_BINS; bin++)
{
integralHist.push_back( Mat(winSize.height + 1, winSize.width + 1, hist[bin].type(), hist[bin].ptr<float>((int)idx)) );
}
Mat integralNorm(winSize.height + 1, winSize.width + 1, normSum.type(), normSum.ptr<float>((int)idx));
integralHistogram(img, integralHist, integralNorm, (int)N_BINS);
}
//void CvHOGEvaluator::writeFeatures( FileStorage &fs, const Mat& featureMap ) const
//{
// _writeFeatures( features, fs, featureMap );
//}
void CvHOGEvaluator::writeFeatures( FileStorage &fs, const Mat& featureMap ) const
{
int featIdx;
int componentIdx;
const Mat_<int>& featureMap_ = (const Mat_<int>&)featureMap;
fs << FEATURES << "[";
for ( int fi = 0; fi < featureMap.cols; fi++ )
if ( featureMap_(0, fi) >= 0 )
{
fs << "{";
featIdx = fi / getFeatureSize();
componentIdx = fi % getFeatureSize();
features[featIdx].write( fs, componentIdx );
fs << "}";
}
fs << "]";
}
void CvHOGEvaluator::generateFeatures()
{
int offset = winSize.width + 1;
Size blockStep;
int x, y, t, w, h;
for (t = 8; t <= winSize.width/2; t+=8) //t = size of a cell. blocksize = 4*cellSize
{
blockStep = Size(4,4);
w = 2*t; //width of a block
h = 2*t; //height of a block
for (x = 0; x <= winSize.width - w; x += blockStep.width)
{
for (y = 0; y <= winSize.height - h; y += blockStep.height)
{
features.push_back(Feature(offset, x, y, t, t));
}
}
w = 2*t;
h = 4*t;
for (x = 0; x <= winSize.width - w; x += blockStep.width)
{
for (y = 0; y <= winSize.height - h; y += blockStep.height)
{
features.push_back(Feature(offset, x, y, t, 2*t));
}
}
w = 4*t;
h = 2*t;
for (x = 0; x <= winSize.width - w; x += blockStep.width)
{
for (y = 0; y <= winSize.height - h; y += blockStep.height)
{
features.push_back(Feature(offset, x, y, 2*t, t));
}
}
}
numFeatures = (int)features.size();
}
CvHOGEvaluator::Feature::Feature()
{
for (int i = 0; i < N_CELLS; i++)
{
rect[i] = Rect(0, 0, 0, 0);
}
}
CvHOGEvaluator::Feature::Feature( int offset, int x, int y, int cellW, int cellH )
{
rect[0] = Rect(x, y, cellW, cellH); //cell0
rect[1] = Rect(x+cellW, y, cellW, cellH); //cell1
rect[2] = Rect(x, y+cellH, cellW, cellH); //cell2
rect[3] = Rect(x+cellW, y+cellH, cellW, cellH); //cell3
for (int i = 0; i < N_CELLS; i++)
{
CV_SUM_OFFSETS(fastRect[i].p0, fastRect[i].p1, fastRect[i].p2, fastRect[i].p3, rect[i], offset);
}
}
void CvHOGEvaluator::Feature::write(FileStorage &fs) const
{
fs << CC_RECTS << "[";
for( int i = 0; i < N_CELLS; i++ )
{
fs << "[:" << rect[i].x << rect[i].y << rect[i].width << rect[i].height << "]";
}
fs << "]";
}
//cell and bin idx writing
//void CvHOGEvaluator::Feature::write(FileStorage &fs, int varIdx) const
//{
// int featComponent = varIdx % (N_CELLS * N_BINS);
// int cellIdx = featComponent / N_BINS;
// int binIdx = featComponent % N_BINS;
//
// fs << CC_RECTS << "[:" << rect[cellIdx].x << rect[cellIdx].y <<
// rect[cellIdx].width << rect[cellIdx].height << binIdx << "]";
//}
//cell[0] and featComponent idx writing. By cell[0] it's possible to recover all block
//All block is necessary for block normalization
void CvHOGEvaluator::Feature::write(FileStorage &fs, int featComponentIdx) const
{
fs << CC_RECT << "[:" << rect[0].x << rect[0].y <<
rect[0].width << rect[0].height << featComponentIdx << "]";
}
void CvHOGEvaluator::integralHistogram(const Mat &img, vector<Mat> &histogram, Mat &norm, int nbins) const
{
CV_Assert( img.type() == CV_8U || img.type() == CV_8UC3 );
int x, y, binIdx;
Size gradSize(img.size());
Size histSize(histogram[0].size());
Mat grad(gradSize, CV_32F);
Mat qangle(gradSize, CV_8U);
AutoBuffer<int> mapbuf(gradSize.width + gradSize.height + 4);
int* xmap = mapbuf.data() + 1;
int* ymap = xmap + gradSize.width + 2;
const int borderType = (int)BORDER_REPLICATE;
for( x = -1; x < gradSize.width + 1; x++ )
xmap[x] = borderInterpolate(x, gradSize.width, borderType);
for( y = -1; y < gradSize.height + 1; y++ )
ymap[y] = borderInterpolate(y, gradSize.height, borderType);
int width = gradSize.width;
AutoBuffer<float> _dbuf(width*4);
float* dbuf = _dbuf.data();
Mat Dx(1, width, CV_32F, dbuf);
Mat Dy(1, width, CV_32F, dbuf + width);
Mat Mag(1, width, CV_32F, dbuf + width*2);
Mat Angle(1, width, CV_32F, dbuf + width*3);
float angleScale = (float)(nbins/CV_PI);
for( y = 0; y < gradSize.height; y++ )
{
const uchar* currPtr = img.ptr(ymap[y]);
const uchar* prevPtr = img.ptr(ymap[y-1]);
const uchar* nextPtr = img.ptr(ymap[y+1]);
float* gradPtr = grad.ptr<float>(y);
uchar* qanglePtr = qangle.ptr(y);
for( x = 0; x < width; x++ )
{
dbuf[x] = (float)(currPtr[xmap[x+1]] - currPtr[xmap[x-1]]);
dbuf[width + x] = (float)(nextPtr[xmap[x]] - prevPtr[xmap[x]]);
}
cartToPolar( Dx, Dy, Mag, Angle, false );
for( x = 0; x < width; x++ )
{
float mag = dbuf[x+width*2];
float angle = dbuf[x+width*3];
angle = angle*angleScale - 0.5f;
int bidx = cvFloor(angle);
angle -= bidx;
if( bidx < 0 )
bidx += nbins;
else if( bidx >= nbins )
bidx -= nbins;
qanglePtr[x] = (uchar)bidx;
gradPtr[x] = mag;
}
}
integral(grad, norm, grad.depth());
float* histBuf;
const float* magBuf;
const uchar* binsBuf;
int binsStep = (int)( qangle.step / sizeof(uchar) );
int histStep = (int)( histogram[0].step / sizeof(float) );
int magStep = (int)( grad.step / sizeof(float) );
for( binIdx = 0; binIdx < nbins; binIdx++ )
{
histBuf = histogram[binIdx].ptr<float>();
magBuf = grad.ptr<float>();
binsBuf = qangle.ptr();
memset( histBuf, 0, histSize.width * sizeof(histBuf[0]) );
histBuf += histStep + 1;
for( y = 0; y < qangle.rows; y++ )
{
histBuf[-1] = 0.f;
float strSum = 0.f;
for( x = 0; x < qangle.cols; x++ )
{
if( binsBuf[x] == binIdx )
strSum += magBuf[x];
histBuf[x] = histBuf[-histStep + x] + strSum;
}
histBuf += histStep;
binsBuf += binsStep;
magBuf += magStep;
}
}
}

@ -1,78 +0,0 @@
#ifndef _OPENCV_HOGFEATURES_H_
#define _OPENCV_HOGFEATURES_H_
#include "traincascade_features.h"
//#define TEST_INTHIST_BUILD
//#define TEST_FEAT_CALC
#define N_BINS 9
#define N_CELLS 4
#define HOGF_NAME "HOGFeatureParams"
struct CvHOGFeatureParams : public CvFeatureParams
{
CvHOGFeatureParams();
};
class CvHOGEvaluator : public CvFeatureEvaluator
{
public:
virtual ~CvHOGEvaluator() {}
virtual void init(const CvFeatureParams *_featureParams,
int _maxSampleCount, cv::Size _winSize );
virtual void setImage(const cv::Mat& img, uchar clsLabel, int idx);
virtual float operator()(int varIdx, int sampleIdx) const;
virtual void writeFeatures( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
protected:
virtual void generateFeatures();
virtual void integralHistogram(const cv::Mat &img, std::vector<cv::Mat> &histogram, cv::Mat &norm, int nbins) const;
class Feature
{
public:
Feature();
Feature( int offset, int x, int y, int cellW, int cellH );
float calc( const std::vector<cv::Mat> &_hists, const cv::Mat &_normSum, size_t y, int featComponent ) const;
void write( cv::FileStorage &fs ) const;
void write( cv::FileStorage &fs, int varIdx ) const;
cv::Rect rect[N_CELLS]; //cells
struct
{
int p0, p1, p2, p3;
} fastRect[N_CELLS];
};
std::vector<Feature> features;
cv::Mat normSum; //for normalization calculation (L1 or L2)
std::vector<cv::Mat> hist;
};
inline float CvHOGEvaluator::operator()(int varIdx, int sampleIdx) const
{
int featureIdx = varIdx / (N_BINS * N_CELLS);
int componentIdx = varIdx % (N_BINS * N_CELLS);
//return features[featureIdx].calc( hist, sampleIdx, componentIdx);
return features[featureIdx].calc( hist, normSum, sampleIdx, componentIdx);
}
inline float CvHOGEvaluator::Feature::calc( const std::vector<cv::Mat>& _hists, const cv::Mat& _normSum, size_t y, int featComponent ) const
{
float normFactor;
float res;
int binIdx = featComponent % N_BINS;
int cellIdx = featComponent / N_BINS;
const float *phist = _hists[binIdx].ptr<float>((int)y);
res = phist[fastRect[cellIdx].p0] - phist[fastRect[cellIdx].p1] - phist[fastRect[cellIdx].p2] + phist[fastRect[cellIdx].p3];
const float *pnormSum = _normSum.ptr<float>((int)y);
normFactor = (float)(pnormSum[fastRect[0].p0] - pnormSum[fastRect[1].p1] - pnormSum[fastRect[2].p2] + pnormSum[fastRect[3].p3]);
res = (res > 0.001f) ? ( res / (normFactor + 0.001f) ) : 0.f; //for cutting negative values, which appear due to floating precision
return res;
}
#endif // _OPENCV_HOGFEATURES_H_

File diff suppressed because it is too large Load Diff

@ -1,86 +0,0 @@
#ifndef _OPENCV_BOOST_H_
#define _OPENCV_BOOST_H_
#include "traincascade_features.h"
#include "old_ml.hpp"
struct CvCascadeBoostParams : CvBoostParams
{
float minHitRate;
float maxFalseAlarm;
CvCascadeBoostParams();
CvCascadeBoostParams( int _boostType, float _minHitRate, float _maxFalseAlarm,
double _weightTrimRate, int _maxDepth, int _maxWeakCount );
virtual ~CvCascadeBoostParams() {}
void write( cv::FileStorage &fs ) const;
bool read( const cv::FileNode &node );
virtual void printDefaults() const;
virtual void printAttrs() const;
virtual bool scanAttr( const std::string prmName, const std::string val);
};
struct CvCascadeBoostTrainData : CvDTreeTrainData
{
CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator,
const CvDTreeParams& _params );
CvCascadeBoostTrainData( const CvFeatureEvaluator* _featureEvaluator,
int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize,
const CvDTreeParams& _params = CvDTreeParams() );
virtual void setData( const CvFeatureEvaluator* _featureEvaluator,
int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize,
const CvDTreeParams& _params=CvDTreeParams() );
void precalculate();
virtual CvDTreeNode* subsample_data( const CvMat* _subsample_idx );
virtual const int* get_class_labels( CvDTreeNode* n, int* labelsBuf );
virtual const int* get_cv_labels( CvDTreeNode* n, int* labelsBuf);
virtual const int* get_sample_indices( CvDTreeNode* n, int* indicesBuf );
virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ordValuesBuf, int* sortedIndicesBuf,
const float** ordValues, const int** sortedIndices, int* sampleIndicesBuf );
virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* catValuesBuf );
virtual float getVarValue( int vi, int si );
virtual void free_train_data();
const CvFeatureEvaluator* featureEvaluator;
cv::Mat valCache; // precalculated feature values (CV_32FC1)
CvMat _resp; // for casting
int numPrecalcVal, numPrecalcIdx;
};
class CvCascadeBoostTree : public CvBoostTree
{
public:
virtual CvDTreeNode* predict( int sampleIdx ) const;
void write( cv::FileStorage &fs, const cv::Mat& featureMap );
void read( const cv::FileNode &node, CvBoost* _ensemble, CvDTreeTrainData* _data );
void markFeaturesInMap( cv::Mat& featureMap );
protected:
virtual void split_node_data( CvDTreeNode* n );
};
class CvCascadeBoost : public CvBoost
{
public:
virtual bool train( const CvFeatureEvaluator* _featureEvaluator,
int _numSamples, int _precalcValBufSize, int _precalcIdxBufSize,
const CvCascadeBoostParams& _params=CvCascadeBoostParams() );
virtual float predict( int sampleIdx, bool returnSum = false ) const;
float getThreshold() const { return threshold; }
void write( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
bool read( const cv::FileNode &node, const CvFeatureEvaluator* _featureEvaluator,
const CvCascadeBoostParams& _params );
void markUsedFeaturesInMap( cv::Mat& featureMap );
protected:
virtual bool set_params( const CvBoostParams& _params );
virtual void update_weights( CvBoostTree* tree );
virtual bool isErrDesired();
float threshold;
float minHitRate, maxFalseAlarm;
};
#endif

@ -1,570 +0,0 @@
#include "opencv2/core.hpp"
#include "cascadeclassifier.h"
#include <queue>
using namespace std;
using namespace cv;
static const char* stageTypes[] = { CC_BOOST };
static const char* featureTypes[] = { CC_HAAR, CC_LBP, CC_HOG };
CvCascadeParams::CvCascadeParams() : stageType( defaultStageType ),
featureType( defaultFeatureType ), winSize( cvSize(24, 24) )
{
name = CC_CASCADE_PARAMS;
}
CvCascadeParams::CvCascadeParams( int _stageType, int _featureType ) : stageType( _stageType ),
featureType( _featureType ), winSize( cvSize(24, 24) )
{
name = CC_CASCADE_PARAMS;
}
//---------------------------- CascadeParams --------------------------------------
void CvCascadeParams::write( FileStorage &fs ) const
{
string stageTypeStr = stageType == BOOST ? CC_BOOST : string();
CV_Assert( !stageTypeStr.empty() );
fs << CC_STAGE_TYPE << stageTypeStr;
string featureTypeStr = featureType == CvFeatureParams::HAAR ? CC_HAAR :
featureType == CvFeatureParams::LBP ? CC_LBP :
featureType == CvFeatureParams::HOG ? CC_HOG :
0;
CV_Assert( !stageTypeStr.empty() );
fs << CC_FEATURE_TYPE << featureTypeStr;
fs << CC_HEIGHT << winSize.height;
fs << CC_WIDTH << winSize.width;
}
bool CvCascadeParams::read( const FileNode &node )
{
if ( node.empty() )
return false;
string stageTypeStr, featureTypeStr;
FileNode rnode = node[CC_STAGE_TYPE];
if ( !rnode.isString() )
return false;
rnode >> stageTypeStr;
stageType = !stageTypeStr.compare( CC_BOOST ) ? BOOST : -1;
if (stageType == -1)
return false;
rnode = node[CC_FEATURE_TYPE];
if ( !rnode.isString() )
return false;
rnode >> featureTypeStr;
featureType = !featureTypeStr.compare( CC_HAAR ) ? CvFeatureParams::HAAR :
!featureTypeStr.compare( CC_LBP ) ? CvFeatureParams::LBP :
!featureTypeStr.compare( CC_HOG ) ? CvFeatureParams::HOG :
-1;
if (featureType == -1)
return false;
node[CC_HEIGHT] >> winSize.height;
node[CC_WIDTH] >> winSize.width;
return winSize.height > 0 && winSize.width > 0;
}
void CvCascadeParams::printDefaults() const
{
CvParams::printDefaults();
cout << " [-stageType <";
for( int i = 0; i < (int)(sizeof(stageTypes)/sizeof(stageTypes[0])); i++ )
{
cout << (i ? " | " : "") << stageTypes[i];
if ( i == defaultStageType )
cout << "(default)";
}
cout << ">]" << endl;
cout << " [-featureType <{";
for( int i = 0; i < (int)(sizeof(featureTypes)/sizeof(featureTypes[0])); i++ )
{
cout << (i ? ", " : "") << featureTypes[i];
if ( i == defaultStageType )
cout << "(default)";
}
cout << "}>]" << endl;
cout << " [-w <sampleWidth = " << winSize.width << ">]" << endl;
cout << " [-h <sampleHeight = " << winSize.height << ">]" << endl;
}
void CvCascadeParams::printAttrs() const
{
cout << "stageType: " << stageTypes[stageType] << endl;
cout << "featureType: " << featureTypes[featureType] << endl;
cout << "sampleWidth: " << winSize.width << endl;
cout << "sampleHeight: " << winSize.height << endl;
}
bool CvCascadeParams::scanAttr( const string prmName, const string val )
{
bool res = true;
if( !prmName.compare( "-stageType" ) )
{
for( int i = 0; i < (int)(sizeof(stageTypes)/sizeof(stageTypes[0])); i++ )
if( !val.compare( stageTypes[i] ) )
stageType = i;
}
else if( !prmName.compare( "-featureType" ) )
{
for( int i = 0; i < (int)(sizeof(featureTypes)/sizeof(featureTypes[0])); i++ )
if( !val.compare( featureTypes[i] ) )
featureType = i;
}
else if( !prmName.compare( "-w" ) )
{
winSize.width = atoi( val.c_str() );
}
else if( !prmName.compare( "-h" ) )
{
winSize.height = atoi( val.c_str() );
}
else
res = false;
return res;
}
//---------------------------- CascadeClassifier --------------------------------------
bool CvCascadeClassifier::train( const string _cascadeDirName,
const string _posFilename,
const string _negFilename,
int _numPos, int _numNeg,
int _precalcValBufSize, int _precalcIdxBufSize,
int _numStages,
const CvCascadeParams& _cascadeParams,
const CvFeatureParams& _featureParams,
const CvCascadeBoostParams& _stageParams,
bool baseFormatSave,
double acceptanceRatioBreakValue )
{
// Start recording clock ticks for training time output
double time = (double)getTickCount();
if( _cascadeDirName.empty() || _posFilename.empty() || _negFilename.empty() )
CV_Error( CV_StsBadArg, "_cascadeDirName or _bgfileName or _vecFileName is NULL" );
string dirName;
if (_cascadeDirName.find_last_of("/\\") == (_cascadeDirName.length() - 1) )
dirName = _cascadeDirName;
else
dirName = _cascadeDirName + '/';
numPos = _numPos;
numNeg = _numNeg;
numStages = _numStages;
if ( !imgReader.create( _posFilename, _negFilename, _cascadeParams.winSize ) )
{
cout << "Image reader can not be created from -vec " << _posFilename
<< " and -bg " << _negFilename << "." << endl;
return false;
}
if ( !load( dirName ) )
{
cascadeParams = _cascadeParams;
featureParams = CvFeatureParams::create(cascadeParams.featureType);
featureParams->init(_featureParams);
stageParams = makePtr<CvCascadeBoostParams>();
*stageParams = _stageParams;
featureEvaluator = CvFeatureEvaluator::create(cascadeParams.featureType);
featureEvaluator->init( featureParams, numPos + numNeg, cascadeParams.winSize );
stageClassifiers.reserve( numStages );
}else{
// Make sure that if model parameters are preloaded, that people are aware of this,
// even when passing other parameters to the training command
cout << "---------------------------------------------------------------------------------" << endl;
cout << "Training parameters are pre-loaded from the parameter file in data folder!" << endl;
cout << "Please empty this folder if you want to use a NEW set of training parameters." << endl;
cout << "---------------------------------------------------------------------------------" << endl;
}
cout << "PARAMETERS:" << endl;
cout << "cascadeDirName: " << _cascadeDirName << endl;
cout << "vecFileName: " << _posFilename << endl;
cout << "bgFileName: " << _negFilename << endl;
cout << "numPos: " << _numPos << endl;
cout << "numNeg: " << _numNeg << endl;
cout << "numStages: " << numStages << endl;
cout << "precalcValBufSize[Mb] : " << _precalcValBufSize << endl;
cout << "precalcIdxBufSize[Mb] : " << _precalcIdxBufSize << endl;
cout << "acceptanceRatioBreakValue : " << acceptanceRatioBreakValue << endl;
cascadeParams.printAttrs();
stageParams->printAttrs();
featureParams->printAttrs();
cout << "Number of unique features given windowSize [" << _cascadeParams.winSize.width << "," << _cascadeParams.winSize.height << "] : " << featureEvaluator->getNumFeatures() << "" << endl;
int startNumStages = (int)stageClassifiers.size();
if ( startNumStages > 1 )
cout << endl << "Stages 0-" << startNumStages-1 << " are loaded" << endl;
else if ( startNumStages == 1)
cout << endl << "Stage 0 is loaded" << endl;
double requiredLeafFARate = pow( (double) stageParams->maxFalseAlarm, (double) numStages ) /
(double)stageParams->max_depth;
double tempLeafFARate;
for( int i = startNumStages; i < numStages; i++ )
{
cout << endl << "===== TRAINING " << i << "-stage =====" << endl;
cout << "<BEGIN" << endl;
if ( !updateTrainingSet( requiredLeafFARate, tempLeafFARate ) )
{
cout << "Train dataset for temp stage can not be filled. "
"Branch training terminated." << endl;
break;
}
if( tempLeafFARate <= requiredLeafFARate )
{
cout << "Required leaf false alarm rate achieved. "
"Branch training terminated." << endl;
break;
}
if( (tempLeafFARate <= acceptanceRatioBreakValue) && (acceptanceRatioBreakValue >= 0) ){
cout << "The required acceptanceRatio for the model has been reached to avoid overfitting of trainingdata. "
"Branch training terminated." << endl;
break;
}
Ptr<CvCascadeBoost> tempStage = makePtr<CvCascadeBoost>();
bool isStageTrained = tempStage->train( featureEvaluator,
curNumSamples, _precalcValBufSize, _precalcIdxBufSize,
*stageParams );
cout << "END>" << endl;
if(!isStageTrained)
break;
stageClassifiers.push_back( tempStage );
// save params
if( i == 0)
{
std::string paramsFilename = dirName + CC_PARAMS_FILENAME;
FileStorage fs( paramsFilename, FileStorage::WRITE);
if ( !fs.isOpened() )
{
cout << "Parameters can not be written, because file " << paramsFilename
<< " can not be opened." << endl;
return false;
}
fs << FileStorage::getDefaultObjectName(paramsFilename) << "{";
writeParams( fs );
fs << "}";
}
// save current stage
char buf[32];
snprintf(buf, sizeof(buf), "%s%d", "stage", i );
string stageFilename = dirName + buf + ".xml";
FileStorage fs( stageFilename, FileStorage::WRITE );
if ( !fs.isOpened() )
{
cout << "Current stage can not be written, because file " << stageFilename
<< " can not be opened." << endl;
return false;
}
fs << FileStorage::getDefaultObjectName(stageFilename) << "{";
tempStage->write( fs, Mat() );
fs << "}";
// Output training time up till now
double seconds = ( (double)getTickCount() - time)/ getTickFrequency();
int days = int(seconds) / 60 / 60 / 24;
int hours = (int(seconds) / 60 / 60) % 24;
int minutes = (int(seconds) / 60) % 60;
int seconds_left = int(seconds) % 60;
cout << "Training until now has taken " << days << " days " << hours << " hours " << minutes << " minutes " << seconds_left <<" seconds." << endl;
}
if(stageClassifiers.size() == 0)
{
cout << "Cascade classifier can't be trained. Check the used training parameters." << endl;
return false;
}
save( dirName + CC_CASCADE_FILENAME, baseFormatSave );
return true;
}
int CvCascadeClassifier::predict( int sampleIdx )
{
CV_DbgAssert( sampleIdx < numPos + numNeg );
for (vector< Ptr<CvCascadeBoost> >::iterator it = stageClassifiers.begin();
it != stageClassifiers.end();++it )
{
if ( (*it)->predict( sampleIdx ) == 0.f )
return 0;
}
return 1;
}
bool CvCascadeClassifier::updateTrainingSet( double minimumAcceptanceRatio, double& acceptanceRatio)
{
int64 posConsumed = 0, negConsumed = 0;
imgReader.restart();
int posCount = fillPassedSamples( 0, numPos, true, 0, posConsumed );
if( !posCount )
return false;
cout << "POS count : consumed " << posCount << " : " << (int)posConsumed << endl;
int proNumNeg = cvRound( ( ((double)numNeg) * ((double)posCount) ) / numPos ); // apply only a fraction of negative samples. double is required since overflow is possible
int negCount = fillPassedSamples( posCount, proNumNeg, false, minimumAcceptanceRatio, negConsumed );
if ( !negCount )
if ( !(negConsumed > 0 && ((double)negCount+1)/(double)negConsumed <= minimumAcceptanceRatio) )
return false;
curNumSamples = posCount + negCount;
acceptanceRatio = negConsumed == 0 ? 0 : ( (double)negCount/(double)(int64)negConsumed );
cout << "NEG count : acceptanceRatio " << negCount << " : " << acceptanceRatio << endl;
return true;
}
int CvCascadeClassifier::fillPassedSamples( int first, int count, bool isPositive, double minimumAcceptanceRatio, int64& consumed )
{
int getcount = 0;
Mat img(cascadeParams.winSize, CV_8UC1);
for( int i = first; i < first + count; i++ )
{
for( ; ; )
{
if( consumed != 0 && ((double)getcount+1)/(double)(int64)consumed <= minimumAcceptanceRatio )
return getcount;
bool isGetImg = isPositive ? imgReader.getPos( img ) :
imgReader.getNeg( img );
if( !isGetImg )
return getcount;
consumed++;
featureEvaluator->setImage( img, isPositive ? 1 : 0, i );
if( predict( i ) == 1 )
{
getcount++;
printf("%s current samples: %d\r", isPositive ? "POS":"NEG", getcount);
fflush(stdout);
break;
}
}
}
return getcount;
}
void CvCascadeClassifier::writeParams( FileStorage &fs ) const
{
cascadeParams.write( fs );
fs << CC_STAGE_PARAMS << "{"; stageParams->write( fs ); fs << "}";
fs << CC_FEATURE_PARAMS << "{"; featureParams->write( fs ); fs << "}";
}
void CvCascadeClassifier::writeFeatures( FileStorage &fs, const Mat& featureMap ) const
{
featureEvaluator->writeFeatures( fs, featureMap );
}
void CvCascadeClassifier::writeStages( FileStorage &fs, const Mat& featureMap ) const
{
char cmnt[30];
int i = 0;
fs << CC_STAGES << "[";
for( vector< Ptr<CvCascadeBoost> >::const_iterator it = stageClassifiers.begin();
it != stageClassifiers.end();++it, ++i )
{
snprintf( cmnt, sizeof(cmnt), "stage %d", i );
fs.writeComment(cmnt);
fs << "{";
(*it)->write( fs, featureMap );
fs << "}";
}
fs << "]";
}
bool CvCascadeClassifier::readParams( const FileNode &node )
{
if ( !node.isMap() || !cascadeParams.read( node ) )
return false;
stageParams = makePtr<CvCascadeBoostParams>();
FileNode rnode = node[CC_STAGE_PARAMS];
if ( !stageParams->read( rnode ) )
return false;
featureParams = CvFeatureParams::create(cascadeParams.featureType);
rnode = node[CC_FEATURE_PARAMS];
if ( !featureParams->read( rnode ) )
return false;
return true;
}
bool CvCascadeClassifier::readStages( const FileNode &node)
{
FileNode rnode = node[CC_STAGES];
if (!rnode.empty() || !rnode.isSeq())
return false;
stageClassifiers.reserve(numStages);
FileNodeIterator it = rnode.begin();
for( int i = 0; i < min( (int)rnode.size(), numStages ); i++, it++ )
{
Ptr<CvCascadeBoost> tempStage = makePtr<CvCascadeBoost>();
if ( !tempStage->read( *it, featureEvaluator, *stageParams) )
return false;
stageClassifiers.push_back(tempStage);
}
return true;
}
// For old Haar Classifier file saving
#define ICV_HAAR_TYPE_ID "opencv-haar-classifier"
#define ICV_HAAR_SIZE_NAME "size"
#define ICV_HAAR_STAGES_NAME "stages"
#define ICV_HAAR_TREES_NAME "trees"
#define ICV_HAAR_FEATURE_NAME "feature"
#define ICV_HAAR_RECTS_NAME "rects"
#define ICV_HAAR_TILTED_NAME "tilted"
#define ICV_HAAR_THRESHOLD_NAME "threshold"
#define ICV_HAAR_LEFT_NODE_NAME "left_node"
#define ICV_HAAR_LEFT_VAL_NAME "left_val"
#define ICV_HAAR_RIGHT_NODE_NAME "right_node"
#define ICV_HAAR_RIGHT_VAL_NAME "right_val"
#define ICV_HAAR_STAGE_THRESHOLD_NAME "stage_threshold"
#define ICV_HAAR_PARENT_NAME "parent"
#define ICV_HAAR_NEXT_NAME "next"
void CvCascadeClassifier::save( const string filename, bool baseFormat )
{
FileStorage fs( filename, FileStorage::WRITE );
if ( !fs.isOpened() )
return;
fs << FileStorage::getDefaultObjectName(filename);
if ( !baseFormat )
{
Mat featureMap;
getUsedFeaturesIdxMap( featureMap );
fs << "{";
writeParams( fs );
fs << CC_STAGE_NUM << (int)stageClassifiers.size();
writeStages( fs, featureMap );
writeFeatures( fs, featureMap );
}
else
{
//char buf[256];
CvSeq* weak;
if ( cascadeParams.featureType != CvFeatureParams::HAAR )
CV_Error( CV_StsBadFunc, "old file format is used for Haar-like features only");
fs << "{:" ICV_HAAR_TYPE_ID;
fs << ICV_HAAR_SIZE_NAME << "[:" << cascadeParams.winSize.width <<
cascadeParams.winSize.height << "]";
fs << ICV_HAAR_STAGES_NAME << "[";
for( size_t si = 0; si < stageClassifiers.size(); si++ )
{
fs << "{"; //stage
/*snprintf( buf, sizeof(buf), "stage %d", si );
CV_CALL( cvWriteComment( fs, buf, 1 ) );*/
weak = stageClassifiers[si]->get_weak_predictors();
fs << ICV_HAAR_TREES_NAME << "[";
for( int wi = 0; wi < weak->total; wi++ )
{
int total_inner_node_idx = -1;
queue<const CvDTreeNode*> inner_nodes_queue;
CvCascadeBoostTree* tree = *((CvCascadeBoostTree**) cvGetSeqElem( weak, wi ));
fs << "[";
/*snprintf( buf, sizeof(buf), "tree %d", wi );
CV_CALL( cvWriteComment( fs, buf, 1 ) );*/
const CvDTreeNode* tempNode;
inner_nodes_queue.push( tree->get_root() );
total_inner_node_idx++;
while (!inner_nodes_queue.empty())
{
tempNode = inner_nodes_queue.front();
fs << "{";
fs << ICV_HAAR_FEATURE_NAME << "{";
((CvHaarEvaluator*)featureEvaluator.get())->writeFeature( fs, tempNode->split->var_idx );
fs << "}";
fs << ICV_HAAR_THRESHOLD_NAME << tempNode->split->ord.c;
if( tempNode->left->left || tempNode->left->right )
{
inner_nodes_queue.push( tempNode->left );
total_inner_node_idx++;
fs << ICV_HAAR_LEFT_NODE_NAME << total_inner_node_idx;
}
else
fs << ICV_HAAR_LEFT_VAL_NAME << tempNode->left->value;
if( tempNode->right->left || tempNode->right->right )
{
inner_nodes_queue.push( tempNode->right );
total_inner_node_idx++;
fs << ICV_HAAR_RIGHT_NODE_NAME << total_inner_node_idx;
}
else
fs << ICV_HAAR_RIGHT_VAL_NAME << tempNode->right->value;
fs << "}"; // ICV_HAAR_FEATURE_NAME
inner_nodes_queue.pop();
}
fs << "]";
}
fs << "]"; //ICV_HAAR_TREES_NAME
fs << ICV_HAAR_STAGE_THRESHOLD_NAME << stageClassifiers[si]->getThreshold();
fs << ICV_HAAR_PARENT_NAME << (int)si-1 << ICV_HAAR_NEXT_NAME << -1;
fs << "}"; //stage
} /* for each stage */
fs << "]"; //ICV_HAAR_STAGES_NAME
}
fs << "}";
}
bool CvCascadeClassifier::load( const string cascadeDirName )
{
FileStorage fs( cascadeDirName + CC_PARAMS_FILENAME, FileStorage::READ );
if ( !fs.isOpened() )
return false;
FileNode node = fs.getFirstTopLevelNode();
if ( !readParams( node ) )
return false;
featureEvaluator = CvFeatureEvaluator::create(cascadeParams.featureType);
featureEvaluator->init( featureParams, numPos + numNeg, cascadeParams.winSize );
fs.release();
char buf[5+10+1] = {0};
for ( int si = 0; si < numStages; si++ )
{
snprintf( buf, sizeof(buf), "%s%d", "stage", si);
fs.open( cascadeDirName + buf + ".xml", FileStorage::READ );
node = fs.getFirstTopLevelNode();
if ( !fs.isOpened() )
break;
Ptr<CvCascadeBoost> tempStage = makePtr<CvCascadeBoost>();
if ( !tempStage->read( node, featureEvaluator, *stageParams ))
{
fs.release();
break;
}
stageClassifiers.push_back(tempStage);
}
return true;
}
void CvCascadeClassifier::getUsedFeaturesIdxMap( Mat& featureMap )
{
int varCount = featureEvaluator->getNumFeatures() * featureEvaluator->getFeatureSize();
featureMap.create( 1, varCount, CV_32SC1 );
featureMap.setTo(Scalar(-1));
for( vector< Ptr<CvCascadeBoost> >::const_iterator it = stageClassifiers.begin();
it != stageClassifiers.end();++it )
(*it)->markUsedFeaturesInMap( featureMap );
for( int fi = 0, idx = 0; fi < varCount; fi++ )
if ( featureMap.at<int>(0, fi) >= 0 )
featureMap.ptr<int>(0)[fi] = idx++;
}

@ -1,125 +0,0 @@
#ifndef _OPENCV_CASCADECLASSIFIER_H_
#define _OPENCV_CASCADECLASSIFIER_H_
#include <ctime>
#include "traincascade_features.h"
#include "haarfeatures.h"
#include "lbpfeatures.h"
#include "HOGfeatures.h" //new
#include "boost.h"
#define CC_CASCADE_FILENAME "cascade.xml"
#define CC_PARAMS_FILENAME "params.xml"
#define CC_CASCADE_PARAMS "cascadeParams"
#define CC_STAGE_TYPE "stageType"
#define CC_FEATURE_TYPE "featureType"
#define CC_HEIGHT "height"
#define CC_WIDTH "width"
#define CC_STAGE_NUM "stageNum"
#define CC_STAGES "stages"
#define CC_STAGE_PARAMS "stageParams"
#define CC_BOOST "BOOST"
#define CC_BOOST_TYPE "boostType"
#define CC_DISCRETE_BOOST "DAB"
#define CC_REAL_BOOST "RAB"
#define CC_LOGIT_BOOST "LB"
#define CC_GENTLE_BOOST "GAB"
#define CC_MINHITRATE "minHitRate"
#define CC_MAXFALSEALARM "maxFalseAlarm"
#define CC_TRIM_RATE "weightTrimRate"
#define CC_MAX_DEPTH "maxDepth"
#define CC_WEAK_COUNT "maxWeakCount"
#define CC_STAGE_THRESHOLD "stageThreshold"
#define CC_WEAK_CLASSIFIERS "weakClassifiers"
#define CC_INTERNAL_NODES "internalNodes"
#define CC_LEAF_VALUES "leafValues"
#define CC_FEATURES FEATURES
#define CC_FEATURE_PARAMS "featureParams"
#define CC_MAX_CAT_COUNT "maxCatCount"
#define CC_FEATURE_SIZE "featSize"
#define CC_HAAR "HAAR"
#define CC_MODE "mode"
#define CC_MODE_BASIC "BASIC"
#define CC_MODE_CORE "CORE"
#define CC_MODE_ALL "ALL"
#define CC_RECTS "rects"
#define CC_TILTED "tilted"
#define CC_LBP "LBP"
#define CC_RECT "rect"
#define CC_HOG "HOG"
#ifdef _WIN32
#define TIME( arg ) (((double) clock()) / CLOCKS_PER_SEC)
#else
#define TIME( arg ) (time( arg ))
#endif
class CvCascadeParams : public CvParams
{
public:
enum { BOOST = 0 };
static const int defaultStageType = BOOST;
static const int defaultFeatureType = CvFeatureParams::HAAR;
CvCascadeParams();
CvCascadeParams( int _stageType, int _featureType );
void write( cv::FileStorage &fs ) const;
bool read( const cv::FileNode &node );
void printDefaults() const;
void printAttrs() const;
bool scanAttr( const std::string prmName, const std::string val );
int stageType;
int featureType;
cv::Size winSize;
};
class CvCascadeClassifier
{
public:
bool train( const std::string _cascadeDirName,
const std::string _posFilename,
const std::string _negFilename,
int _numPos, int _numNeg,
int _precalcValBufSize, int _precalcIdxBufSize,
int _numStages,
const CvCascadeParams& _cascadeParams,
const CvFeatureParams& _featureParams,
const CvCascadeBoostParams& _stageParams,
bool baseFormatSave = false,
double acceptanceRatioBreakValue = -1.0 );
private:
int predict( int sampleIdx );
void save( const std::string cascadeDirName, bool baseFormat = false );
bool load( const std::string cascadeDirName );
bool updateTrainingSet( double minimumAcceptanceRatio, double& acceptanceRatio );
int fillPassedSamples( int first, int count, bool isPositive, double requiredAcceptanceRatio, int64& consumed );
void writeParams( cv::FileStorage &fs ) const;
void writeStages( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
void writeFeatures( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
bool readParams( const cv::FileNode &node );
bool readStages( const cv::FileNode &node );
void getUsedFeaturesIdxMap( cv::Mat& featureMap );
CvCascadeParams cascadeParams;
cv::Ptr<CvFeatureParams> featureParams;
cv::Ptr<CvCascadeBoostParams> stageParams;
cv::Ptr<CvFeatureEvaluator> featureEvaluator;
std::vector< cv::Ptr<CvCascadeBoost> > stageClassifiers;
CvCascadeImageReader imgReader;
int numStages, curNumSamples;
int numPos, numNeg;
};
#endif

@ -1,93 +0,0 @@
#include "opencv2/core.hpp"
#include "traincascade_features.h"
#include "cascadeclassifier.h"
using namespace std;
using namespace cv;
float calcNormFactor( const Mat& sum, const Mat& sqSum )
{
CV_DbgAssert( sum.cols > 3 && sqSum.rows > 3 );
Rect normrect( 1, 1, sum.cols - 3, sum.rows - 3 );
size_t p0, p1, p2, p3;
CV_SUM_OFFSETS( p0, p1, p2, p3, normrect, sum.step1() )
double area = normrect.width * normrect.height;
const int *sp = sum.ptr<int>();
int valSum = sp[p0] - sp[p1] - sp[p2] + sp[p3];
const double *sqp = sqSum.ptr<double>();
double valSqSum = sqp[p0] - sqp[p1] - sqp[p2] + sqp[p3];
return (float) sqrt( (double) (area * valSqSum - (double)valSum * valSum) );
}
CvParams::CvParams() : name( "params" ) {}
void CvParams::printDefaults() const
{ cout << "--" << name << "--" << endl; }
void CvParams::printAttrs() const {}
bool CvParams::scanAttr( const string, const string ) { return false; }
//---------------------------- FeatureParams --------------------------------------
CvFeatureParams::CvFeatureParams() : maxCatCount( 0 ), featSize( 1 )
{
name = CC_FEATURE_PARAMS;
}
void CvFeatureParams::init( const CvFeatureParams& fp )
{
maxCatCount = fp.maxCatCount;
featSize = fp.featSize;
}
void CvFeatureParams::write( FileStorage &fs ) const
{
fs << CC_MAX_CAT_COUNT << maxCatCount;
fs << CC_FEATURE_SIZE << featSize;
}
bool CvFeatureParams::read( const FileNode &node )
{
if ( node.empty() )
return false;
maxCatCount = node[CC_MAX_CAT_COUNT];
featSize = node[CC_FEATURE_SIZE];
return ( maxCatCount >= 0 && featSize >= 1 );
}
Ptr<CvFeatureParams> CvFeatureParams::create( int featureType )
{
return featureType == HAAR ? Ptr<CvFeatureParams>(new CvHaarFeatureParams) :
featureType == LBP ? Ptr<CvFeatureParams>(new CvLBPFeatureParams) :
featureType == HOG ? Ptr<CvFeatureParams>(new CvHOGFeatureParams) :
Ptr<CvFeatureParams>();
}
//------------------------------------- FeatureEvaluator ---------------------------------------
void CvFeatureEvaluator::init(const CvFeatureParams *_featureParams,
int _maxSampleCount, Size _winSize )
{
CV_Assert(_maxSampleCount > 0);
featureParams = (CvFeatureParams *)_featureParams;
winSize = _winSize;
numFeatures = 0;
cls.create( (int)_maxSampleCount, 1, CV_32FC1 );
generateFeatures();
}
void CvFeatureEvaluator::setImage(const Mat &img, uchar clsLabel, int idx)
{
CV_Assert(img.cols == winSize.width);
CV_Assert(img.rows == winSize.height);
CV_Assert(idx < cls.rows);
cls.ptr<float>(idx)[0] = clsLabel;
}
Ptr<CvFeatureEvaluator> CvFeatureEvaluator::create(int type)
{
return type == CvFeatureParams::HAAR ? Ptr<CvFeatureEvaluator>(new CvHaarEvaluator) :
type == CvFeatureParams::LBP ? Ptr<CvFeatureEvaluator>(new CvLBPEvaluator) :
type == CvFeatureParams::HOG ? Ptr<CvFeatureEvaluator>(new CvHOGEvaluator) :
Ptr<CvFeatureEvaluator>();
}

@ -1,312 +0,0 @@
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "haarfeatures.h"
#include "cascadeclassifier.h"
using namespace std;
using namespace cv;
CvHaarFeatureParams::CvHaarFeatureParams() : mode(BASIC)
{
name = HFP_NAME;
}
CvHaarFeatureParams::CvHaarFeatureParams( int _mode ) : mode( _mode )
{
name = HFP_NAME;
}
void CvHaarFeatureParams::init( const CvFeatureParams& fp )
{
CvFeatureParams::init( fp );
mode = ((const CvHaarFeatureParams&)fp).mode;
}
void CvHaarFeatureParams::write( FileStorage &fs ) const
{
CvFeatureParams::write( fs );
string modeStr = mode == BASIC ? CC_MODE_BASIC :
mode == CORE ? CC_MODE_CORE :
mode == ALL ? CC_MODE_ALL : string();
CV_Assert( !modeStr.empty() );
fs << CC_MODE << modeStr;
}
bool CvHaarFeatureParams::read( const FileNode &node )
{
if( !CvFeatureParams::read( node ) )
return false;
FileNode rnode = node[CC_MODE];
if( !rnode.isString() )
return false;
string modeStr;
rnode >> modeStr;
mode = !modeStr.compare( CC_MODE_BASIC ) ? BASIC :
!modeStr.compare( CC_MODE_CORE ) ? CORE :
!modeStr.compare( CC_MODE_ALL ) ? ALL : -1;
return (mode >= 0);
}
void CvHaarFeatureParams::printDefaults() const
{
CvFeatureParams::printDefaults();
cout << " [-mode <" CC_MODE_BASIC << "(default) | "
<< CC_MODE_CORE <<" | " << CC_MODE_ALL << endl;
}
void CvHaarFeatureParams::printAttrs() const
{
CvFeatureParams::printAttrs();
string mode_str = mode == BASIC ? CC_MODE_BASIC :
mode == CORE ? CC_MODE_CORE :
mode == ALL ? CC_MODE_ALL : 0;
cout << "mode: " << mode_str << endl;
}
bool CvHaarFeatureParams::scanAttr( const string prmName, const string val)
{
if ( !CvFeatureParams::scanAttr( prmName, val ) )
{
if( !prmName.compare("-mode") )
{
mode = !val.compare( CC_MODE_CORE ) ? CORE :
!val.compare( CC_MODE_ALL ) ? ALL :
!val.compare( CC_MODE_BASIC ) ? BASIC : -1;
if (mode == -1)
return false;
}
return false;
}
return true;
}
//--------------------- HaarFeatureEvaluator ----------------
void CvHaarEvaluator::init(const CvFeatureParams *_featureParams,
int _maxSampleCount, Size _winSize )
{
CV_Assert(_maxSampleCount > 0);
int cols = (_winSize.width + 1) * (_winSize.height + 1);
sum.create((int)_maxSampleCount, cols, CV_32SC1);
tilted.create((int)_maxSampleCount, cols, CV_32SC1);
normfactor.create(1, (int)_maxSampleCount, CV_32FC1);
CvFeatureEvaluator::init( _featureParams, _maxSampleCount, _winSize );
}
void CvHaarEvaluator::setImage(const Mat& img, uchar clsLabel, int idx)
{
CV_DbgAssert( !sum.empty() && !tilted.empty() && !normfactor.empty() );
CvFeatureEvaluator::setImage( img, clsLabel, idx);
Mat innSum(winSize.height + 1, winSize.width + 1, sum.type(), sum.ptr<int>((int)idx));
Mat innSqSum;
if (((const CvHaarFeatureParams*)featureParams)->mode == CvHaarFeatureParams::ALL)
{
Mat innTilted(winSize.height + 1, winSize.width + 1, tilted.type(), tilted.ptr<int>((int)idx));
integral(img, innSum, innSqSum, innTilted);
}
else
integral(img, innSum, innSqSum);
normfactor.ptr<float>(0)[idx] = calcNormFactor( innSum, innSqSum );
}
void CvHaarEvaluator::writeFeatures( FileStorage &fs, const Mat& featureMap ) const
{
_writeFeatures( features, fs, featureMap );
}
void CvHaarEvaluator::writeFeature(FileStorage &fs, int fi) const
{
CV_DbgAssert( fi < (int)features.size() );
features[fi].write(fs);
}
void CvHaarEvaluator::generateFeatures()
{
int mode = ((const CvHaarFeatureParams*)((CvFeatureParams*)featureParams))->mode;
int offset = winSize.width + 1;
for( int x = 0; x < winSize.width; x++ )
{
for( int y = 0; y < winSize.height; y++ )
{
for( int dx = 1; dx <= winSize.width; dx++ )
{
for( int dy = 1; dy <= winSize.height; dy++ )
{
// haar_x2
if ( (x+dx*2 <= winSize.width) && (y+dy <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx*2, dy, -1,
x+dx, y, dx , dy, +2 ) );
}
// haar_y2
if ( (x+dx <= winSize.width) && (y+dy*2 <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx, dy*2, -1,
x, y+dy, dx, dy, +2 ) );
}
// haar_x3
if ( (x+dx*3 <= winSize.width) && (y+dy <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx*3, dy, -1,
x+dx, y, dx , dy, +2 ) );
}
// haar_y3
if ( (x+dx <= winSize.width) && (y+dy*3 <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx, dy*3, -1,
x, y+dy, dx, dy, +2 ) );
}
if( mode != CvHaarFeatureParams::BASIC )
{
// haar_x4
if ( (x+dx*4 <= winSize.width) && (y+dy <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx*4, dy, -1,
x+dx, y, dx*2, dy, +2 ) );
}
// haar_y4
if ( (x+dx <= winSize.width ) && (y+dy*4 <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx, dy*4, -1,
x, y+dy, dx, dy*2, +2 ) );
}
}
// x2_y2
if ( (x+dx*2 <= winSize.width) && (y+dy*2 <= winSize.height) )
{
features.push_back( Feature( offset, false,
x, y, dx*2, dy*2, -1,
x, y, dx, dy, +2,
x+dx, y+dy, dx, dy, +2 ) );
}
if (mode != CvHaarFeatureParams::BASIC)
{
if ( (x+dx*3 <= winSize.width) && (y+dy*3 <= winSize.height) )
{
features.push_back( Feature( offset, false,
x , y , dx*3, dy*3, -1,
x+dx, y+dy, dx , dy , +9) );
}
}
if (mode == CvHaarFeatureParams::ALL)
{
// tilted haar_x2
if ( (x+2*dx <= winSize.width) && (y+2*dx+dy <= winSize.height) && (x-dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx*2, dy, -1,
x, y, dx, dy, +2 ) );
}
// tilted haar_y2
if ( (x+dx <= winSize.width) && (y+dx+2*dy <= winSize.height) && (x-2*dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx, 2*dy, -1,
x, y, dx, dy, +2 ) );
}
// tilted haar_x3
if ( (x+3*dx <= winSize.width) && (y+3*dx+dy <= winSize.height) && (x-dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx*3, dy, -1,
x+dx, y+dx, dx, dy, +3 ) );
}
// tilted haar_y3
if ( (x+dx <= winSize.width) && (y+dx+3*dy <= winSize.height) && (x-3*dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx, 3*dy, -1,
x-dy, y+dy, dx, dy, +3 ) );
}
// tilted haar_x4
if ( (x+4*dx <= winSize.width) && (y+4*dx+dy <= winSize.height) && (x-dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx*4, dy, -1,
x+dx, y+dx, dx*2, dy, +2 ) );
}
// tilted haar_y4
if ( (x+dx <= winSize.width) && (y+dx+4*dy <= winSize.height) && (x-4*dy>= 0) )
{
features.push_back( Feature( offset, true,
x, y, dx, 4*dy, -1,
x-dy, y+dy, dx, 2*dy, +2 ) );
}
}
}
}
}
}
numFeatures = (int)features.size();
}
CvHaarEvaluator::Feature::Feature()
{
tilted = false;
rect[0].r = rect[1].r = rect[2].r = Rect(0,0,0,0);
rect[0].weight = rect[1].weight = rect[2].weight = 0;
}
CvHaarEvaluator::Feature::Feature( int offset, bool _tilted,
int x0, int y0, int w0, int h0, float wt0,
int x1, int y1, int w1, int h1, float wt1,
int x2, int y2, int w2, int h2, float wt2 )
{
tilted = _tilted;
rect[0].r.x = x0;
rect[0].r.y = y0;
rect[0].r.width = w0;
rect[0].r.height = h0;
rect[0].weight = wt0;
rect[1].r.x = x1;
rect[1].r.y = y1;
rect[1].r.width = w1;
rect[1].r.height = h1;
rect[1].weight = wt1;
rect[2].r.x = x2;
rect[2].r.y = y2;
rect[2].r.width = w2;
rect[2].r.height = h2;
rect[2].weight = wt2;
if( !tilted )
{
for( int j = 0; j < CV_HAAR_FEATURE_MAX; j++ )
{
if( rect[j].weight == 0.0F )
break;
CV_SUM_OFFSETS( fastRect[j].p0, fastRect[j].p1, fastRect[j].p2, fastRect[j].p3, rect[j].r, offset )
}
}
else
{
for( int j = 0; j < CV_HAAR_FEATURE_MAX; j++ )
{
if( rect[j].weight == 0.0F )
break;
CV_TILTED_OFFSETS( fastRect[j].p0, fastRect[j].p1, fastRect[j].p2, fastRect[j].p3, rect[j].r, offset )
}
}
}
void CvHaarEvaluator::Feature::write( FileStorage &fs ) const
{
fs << CC_RECTS << "[";
for( int ri = 0; ri < CV_HAAR_FEATURE_MAX && rect[ri].r.width != 0; ++ri )
{
fs << "[:" << rect[ri].r.x << rect[ri].r.y <<
rect[ri].r.width << rect[ri].r.height << rect[ri].weight << "]";
}
fs << "]" << CC_TILTED << tilted;
}

@ -1,89 +0,0 @@
#ifndef _OPENCV_HAARFEATURES_H_
#define _OPENCV_HAARFEATURES_H_
#include "traincascade_features.h"
#define CV_HAAR_FEATURE_MAX 3
#define HFP_NAME "haarFeatureParams"
class CvHaarFeatureParams : public CvFeatureParams
{
public:
enum { BASIC = 0, CORE = 1, ALL = 2 };
/* 0 - BASIC = Viola
* 1 - CORE = All upright
* 2 - ALL = All features */
CvHaarFeatureParams();
CvHaarFeatureParams( int _mode );
virtual void init( const CvFeatureParams& fp );
virtual void write( cv::FileStorage &fs ) const;
virtual bool read( const cv::FileNode &node );
virtual void printDefaults() const;
virtual void printAttrs() const;
virtual bool scanAttr( const std::string prm, const std::string val);
int mode;
};
class CvHaarEvaluator : public CvFeatureEvaluator
{
public:
virtual void init(const CvFeatureParams *_featureParams,
int _maxSampleCount, cv::Size _winSize );
virtual void setImage(const cv::Mat& img, uchar clsLabel, int idx);
virtual float operator()(int featureIdx, int sampleIdx) const;
virtual void writeFeatures( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
void writeFeature( cv::FileStorage &fs, int fi ) const; // for old file fornat
protected:
virtual void generateFeatures();
class Feature
{
public:
Feature();
Feature( int offset, bool _tilted,
int x0, int y0, int w0, int h0, float wt0,
int x1, int y1, int w1, int h1, float wt1,
int x2 = 0, int y2 = 0, int w2 = 0, int h2 = 0, float wt2 = 0.0F );
float calc( const cv::Mat &sum, const cv::Mat &tilted, size_t y) const;
void write( cv::FileStorage &fs ) const;
bool tilted;
struct
{
cv::Rect r;
float weight;
} rect[CV_HAAR_FEATURE_MAX];
struct
{
int p0, p1, p2, p3;
} fastRect[CV_HAAR_FEATURE_MAX];
};
std::vector<Feature> features;
cv::Mat sum; /* sum images (each row represents image) */
cv::Mat tilted; /* tilted sum images (each row represents image) */
cv::Mat normfactor; /* normalization factor */
};
inline float CvHaarEvaluator::operator()(int featureIdx, int sampleIdx) const
{
float nf = normfactor.at<float>(0, sampleIdx);
return !nf ? 0.0f : (features[featureIdx].calc( sum, tilted, sampleIdx)/nf);
}
inline float CvHaarEvaluator::Feature::calc( const cv::Mat &_sum, const cv::Mat &_tilted, size_t y) const
{
const int* img = tilted ? _tilted.ptr<int>((int)y) : _sum.ptr<int>((int)y);
float ret = rect[0].weight * (img[fastRect[0].p0] - img[fastRect[0].p1] - img[fastRect[0].p2] + img[fastRect[0].p3] ) +
rect[1].weight * (img[fastRect[1].p0] - img[fastRect[1].p1] - img[fastRect[1].p2] + img[fastRect[1].p3] );
if( rect[2].weight != 0.0f )
ret += rect[2].weight * (img[fastRect[2].p0] - img[fastRect[2].p1] - img[fastRect[2].p2] + img[fastRect[2].p3] );
return ret;
}
#endif

@ -1,186 +0,0 @@
#include "opencv2/core.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "imagestorage.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
bool CvCascadeImageReader::create( const string _posFilename, const string _negFilename, Size _winSize )
{
return posReader.create(_posFilename) && negReader.create(_negFilename, _winSize);
}
CvCascadeImageReader::NegReader::NegReader()
{
src.create( 0, 0 , CV_8UC1 );
img.create( 0, 0, CV_8UC1 );
point = offset = Point( 0, 0 );
scale = 1.0F;
scaleFactor = 1.4142135623730950488016887242097F;
stepFactor = 0.5F;
}
bool CvCascadeImageReader::NegReader::create( const string _filename, Size _winSize )
{
string str;
std::ifstream file(_filename.c_str());
if ( !file.is_open() )
return false;
while( !file.eof() )
{
std::getline(file, str);
str.erase(str.find_last_not_of(" \n\r\t")+1);
if (str.empty()) break;
if (str.at(0) == '#' ) continue; /* comment */
imgFilenames.push_back(str);
}
file.close();
winSize = _winSize;
last = round = 0;
return true;
}
bool CvCascadeImageReader::NegReader::nextImg()
{
Point _offset = Point(0,0);
size_t count = imgFilenames.size();
for( size_t i = 0; i < count; i++ )
{
src = imread( imgFilenames[last++], IMREAD_GRAYSCALE );
if( src.empty() ){
last %= count;
continue;
}
round += last / count;
round = round % (winSize.width * winSize.height);
last %= count;
_offset.x = std::min( (int)round % winSize.width, src.cols - winSize.width );
_offset.y = std::min( (int)round / winSize.width, src.rows - winSize.height );
if( !src.empty() && src.type() == CV_8UC1
&& _offset.x >= 0 && _offset.y >= 0 )
break;
}
if( src.empty() )
return false; // no appropriate image
point = offset = _offset;
scale = max( ((float)winSize.width + point.x) / ((float)src.cols),
((float)winSize.height + point.y) / ((float)src.rows) );
Size sz( (int)(scale*src.cols + 0.5F), (int)(scale*src.rows + 0.5F) );
resize( src, img, sz, 0, 0, INTER_LINEAR_EXACT );
return true;
}
bool CvCascadeImageReader::NegReader::get( Mat& _img )
{
CV_Assert( !_img.empty() );
CV_Assert( _img.type() == CV_8UC1 );
CV_Assert( _img.cols == winSize.width );
CV_Assert( _img.rows == winSize.height );
if( img.empty() )
if ( !nextImg() )
return false;
Mat mat( winSize.height, winSize.width, CV_8UC1,
(void*)(img.ptr(point.y) + point.x * img.elemSize()), img.step );
mat.copyTo(_img);
if( (int)( point.x + (1.0F + stepFactor ) * winSize.width ) < img.cols )
point.x += (int)(stepFactor * winSize.width);
else
{
point.x = offset.x;
if( (int)( point.y + (1.0F + stepFactor ) * winSize.height ) < img.rows )
point.y += (int)(stepFactor * winSize.height);
else
{
point.y = offset.y;
scale *= scaleFactor;
if( scale <= 1.0F )
resize( src, img, Size( (int)(scale*src.cols), (int)(scale*src.rows) ), 0, 0, INTER_LINEAR_EXACT );
else
{
if ( !nextImg() )
return false;
}
}
}
return true;
}
CvCascadeImageReader::PosReader::PosReader()
{
file = 0;
vec = 0;
}
bool CvCascadeImageReader::PosReader::create( const string _filename )
{
if ( file )
fclose( file );
file = fopen( _filename.c_str(), "rb" );
if( !file )
return false;
short tmp = 0;
if( fread( &count, sizeof( count ), 1, file ) != 1 ||
fread( &vecSize, sizeof( vecSize ), 1, file ) != 1 ||
fread( &tmp, sizeof( tmp ), 1, file ) != 1 ||
fread( &tmp, sizeof( tmp ), 1, file ) != 1 )
CV_Error_( CV_StsParseError, ("wrong file format for %s\n", _filename.c_str()) );
base = sizeof( count ) + sizeof( vecSize ) + 2*sizeof( tmp );
if( feof( file ) )
return false;
last = 0;
vec = (short*) cvAlloc( sizeof( *vec ) * vecSize );
CV_Assert( vec );
return true;
}
bool CvCascadeImageReader::PosReader::get( Mat &_img )
{
CV_Assert( _img.rows * _img.cols == vecSize );
uchar tmp = 0;
size_t elements_read = fread( &tmp, sizeof( tmp ), 1, file );
if( elements_read != 1 )
CV_Error( CV_StsBadArg, "Can not get new positive sample. The most possible reason is "
"insufficient count of samples in given vec-file.\n");
elements_read = fread( vec, sizeof( vec[0] ), vecSize, file );
if( elements_read != (size_t)(vecSize) )
CV_Error( CV_StsBadArg, "Can not get new positive sample. Seems that vec-file has incorrect structure.\n");
if( feof( file ) || last++ >= count )
CV_Error( CV_StsBadArg, "Can not get new positive sample. vec-file is over.\n");
for( int r = 0; r < _img.rows; r++ )
{
for( int c = 0; c < _img.cols; c++ )
_img.ptr(r)[c] = (uchar)vec[r * _img.cols + c];
}
return true;
}
void CvCascadeImageReader::PosReader::restart()
{
CV_Assert( file );
last = 0;
fseek( file, base, SEEK_SET );
}
CvCascadeImageReader::PosReader::~PosReader()
{
if (file)
fclose( file );
cvFree( &vec );
}

@ -1,50 +0,0 @@
#ifndef _OPENCV_IMAGESTORAGE_H_
#define _OPENCV_IMAGESTORAGE_H_
class CvCascadeImageReader
{
public:
bool create( const std::string _posFilename, const std::string _negFilename, cv::Size _winSize );
void restart() { posReader.restart(); }
bool getNeg(cv::Mat &_img) { return negReader.get( _img ); }
bool getPos(cv::Mat &_img) { return posReader.get( _img ); }
private:
class PosReader
{
public:
PosReader();
virtual ~PosReader();
bool create( const std::string _filename );
bool get( cv::Mat &_img );
void restart();
short* vec;
FILE* file;
int count;
int vecSize;
int last;
int base;
} posReader;
class NegReader
{
public:
NegReader();
bool create( const std::string _filename, cv::Size _winSize );
bool get( cv::Mat& _img );
bool nextImg();
cv::Mat src, img;
std::vector<std::string> imgFilenames;
cv::Point offset, point;
float scale;
float scaleFactor;
float stepFactor;
size_t last, round;
cv::Size winSize;
} negReader;
};
#endif

@ -1,67 +0,0 @@
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "lbpfeatures.h"
#include "cascadeclassifier.h"
using namespace cv;
CvLBPFeatureParams::CvLBPFeatureParams()
{
maxCatCount = 256;
name = LBPF_NAME;
}
void CvLBPEvaluator::init(const CvFeatureParams *_featureParams, int _maxSampleCount, Size _winSize)
{
CV_Assert( _maxSampleCount > 0);
sum.create((int)_maxSampleCount, (_winSize.width + 1) * (_winSize.height + 1), CV_32SC1);
CvFeatureEvaluator::init( _featureParams, _maxSampleCount, _winSize );
}
void CvLBPEvaluator::setImage(const Mat &img, uchar clsLabel, int idx)
{
CV_DbgAssert( !sum.empty() );
CvFeatureEvaluator::setImage( img, clsLabel, idx );
Mat innSum(winSize.height + 1, winSize.width + 1, sum.type(), sum.ptr<int>((int)idx));
integral( img, innSum );
}
void CvLBPEvaluator::writeFeatures( FileStorage &fs, const Mat& featureMap ) const
{
_writeFeatures( features, fs, featureMap );
}
void CvLBPEvaluator::generateFeatures()
{
int offset = winSize.width + 1;
for( int x = 0; x < winSize.width; x++ )
for( int y = 0; y < winSize.height; y++ )
for( int w = 1; w <= winSize.width / 3; w++ )
for( int h = 1; h <= winSize.height / 3; h++ )
if ( (x+3*w <= winSize.width) && (y+3*h <= winSize.height) )
features.push_back( Feature(offset, x, y, w, h ) );
numFeatures = (int)features.size();
}
CvLBPEvaluator::Feature::Feature()
{
rect = cvRect(0, 0, 0, 0);
}
CvLBPEvaluator::Feature::Feature( int offset, int x, int y, int _blockWidth, int _blockHeight )
{
Rect tr = rect = cvRect(x, y, _blockWidth, _blockHeight);
CV_SUM_OFFSETS( p[0], p[1], p[4], p[5], tr, offset )
tr.x += 2*rect.width;
CV_SUM_OFFSETS( p[2], p[3], p[6], p[7], tr, offset )
tr.y +=2*rect.height;
CV_SUM_OFFSETS( p[10], p[11], p[14], p[15], tr, offset )
tr.x -= 2*rect.width;
CV_SUM_OFFSETS( p[8], p[9], p[12], p[13], tr, offset )
}
void CvLBPEvaluator::Feature::write(FileStorage &fs) const
{
fs << CC_RECT << "[:" << rect.x << rect.y << rect.width << rect.height << "]";
}

@ -1,57 +0,0 @@
#ifndef _OPENCV_LBPFEATURES_H_
#define _OPENCV_LBPFEATURES_H_
#include "traincascade_features.h"
#define LBPF_NAME "lbpFeatureParams"
struct CvLBPFeatureParams : CvFeatureParams
{
CvLBPFeatureParams();
};
class CvLBPEvaluator : public CvFeatureEvaluator
{
public:
virtual ~CvLBPEvaluator() {}
virtual void init(const CvFeatureParams *_featureParams,
int _maxSampleCount, cv::Size _winSize );
virtual void setImage(const cv::Mat& img, uchar clsLabel, int idx);
virtual float operator()(int featureIdx, int sampleIdx) const
{ return (float)features[featureIdx].calc( sum, sampleIdx); }
virtual void writeFeatures( cv::FileStorage &fs, const cv::Mat& featureMap ) const;
protected:
virtual void generateFeatures();
class Feature
{
public:
Feature();
Feature( int offset, int x, int y, int _block_w, int _block_h );
uchar calc( const cv::Mat& _sum, size_t y ) const;
void write( cv::FileStorage &fs ) const;
cv::Rect rect;
int p[16];
};
std::vector<Feature> features;
cv::Mat sum;
};
inline uchar CvLBPEvaluator::Feature::calc(const cv::Mat &_sum, size_t y) const
{
const int* psum = _sum.ptr<int>((int)y);
int cval = psum[p[5]] - psum[p[6]] - psum[p[9]] + psum[p[10]];
return (uchar)((psum[p[0]] - psum[p[1]] - psum[p[4]] + psum[p[5]] >= cval ? 128 : 0) | // 0
(psum[p[1]] - psum[p[2]] - psum[p[5]] + psum[p[6]] >= cval ? 64 : 0) | // 1
(psum[p[2]] - psum[p[3]] - psum[p[6]] + psum[p[7]] >= cval ? 32 : 0) | // 2
(psum[p[6]] - psum[p[7]] - psum[p[10]] + psum[p[11]] >= cval ? 16 : 0) | // 5
(psum[p[10]] - psum[p[11]] - psum[p[14]] + psum[p[15]] >= cval ? 8 : 0) | // 8
(psum[p[9]] - psum[p[10]] - psum[p[13]] + psum[p[14]] >= cval ? 4 : 0) | // 7
(psum[p[8]] - psum[p[9]] - psum[p[12]] + psum[p[13]] >= cval ? 2 : 0) | // 6
(psum[p[4]] - psum[p[5]] - psum[p[8]] + psum[p[9]] >= cval ? 1 : 0)); // 3
}
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,792 +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
//
// 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 "old_ml_precomp.hpp"
#include <ctype.h>
#define MISS_VAL FLT_MAX
#define CV_VAR_MISS 0
CvTrainTestSplit::CvTrainTestSplit()
{
train_sample_part_mode = CV_COUNT;
train_sample_part.count = -1;
mix = false;
}
CvTrainTestSplit::CvTrainTestSplit( int _train_sample_count, bool _mix )
{
train_sample_part_mode = CV_COUNT;
train_sample_part.count = _train_sample_count;
mix = _mix;
}
CvTrainTestSplit::CvTrainTestSplit( float _train_sample_portion, bool _mix )
{
train_sample_part_mode = CV_PORTION;
train_sample_part.portion = _train_sample_portion;
mix = _mix;
}
////////////////
CvMLData::CvMLData()
{
values = missing = var_types = var_idx_mask = response_out = var_idx_out = var_types_out = 0;
train_sample_idx = test_sample_idx = 0;
header_lines_number = 0;
sample_idx = 0;
response_idx = -1;
train_sample_count = -1;
delimiter = ',';
miss_ch = '?';
//flt_separator = '.';
rng = &cv::theRNG();
}
CvMLData::~CvMLData()
{
clear();
}
void CvMLData::free_train_test_idx()
{
cvReleaseMat( &train_sample_idx );
cvReleaseMat( &test_sample_idx );
sample_idx = 0;
}
void CvMLData::clear()
{
class_map.clear();
cvReleaseMat( &values );
cvReleaseMat( &missing );
cvReleaseMat( &var_types );
cvReleaseMat( &var_idx_mask );
cvReleaseMat( &response_out );
cvReleaseMat( &var_idx_out );
cvReleaseMat( &var_types_out );
free_train_test_idx();
total_class_count = 0;
response_idx = -1;
train_sample_count = -1;
}
void CvMLData::set_header_lines_number( int idx )
{
header_lines_number = std::max(0, idx);
}
int CvMLData::get_header_lines_number() const
{
return header_lines_number;
}
static char *fgets_chomp(char *str, int n, FILE *stream)
{
char *head = fgets(str, n, stream);
if( head )
{
for(char *tail = head + strlen(head) - 1; tail >= head; --tail)
{
if( *tail != '\r' && *tail != '\n' )
break;
*tail = '\0';
}
}
return head;
}
int CvMLData::read_csv(const char* filename)
{
const int M = 1000000;
const char str_delimiter[3] = { ' ', delimiter, '\0' };
FILE* file = 0;
CvMemStorage* storage;
CvSeq* seq;
char *ptr;
float* el_ptr;
CvSeqReader reader;
int cols_count = 0;
uchar *var_types_ptr = 0;
clear();
file = fopen( filename, "rt" );
if( !file )
return -1;
std::vector<char> _buf(M);
char* buf = &_buf[0];
// skip header lines
for( int i = 0; i < header_lines_number; i++ )
{
if( fgets( buf, M, file ) == 0 )
{
fclose(file);
return -1;
}
}
// read the first data line and determine the number of variables
if( !fgets_chomp( buf, M, file ))
{
fclose(file);
return -1;
}
ptr = buf;
while( *ptr == ' ' )
ptr++;
for( ; *ptr != '\0'; )
{
if(*ptr == delimiter || *ptr == ' ')
{
cols_count++;
ptr++;
while( *ptr == ' ' ) ptr++;
}
else
ptr++;
}
cols_count++;
if ( cols_count == 0)
{
fclose(file);
return -1;
}
// create temporary memory storage to store the whole database
el_ptr = new float[cols_count];
storage = cvCreateMemStorage();
seq = cvCreateSeq( 0, sizeof(*seq), cols_count*sizeof(float), storage );
var_types = cvCreateMat( 1, cols_count, CV_8U );
cvZero( var_types );
var_types_ptr = var_types->data.ptr;
for(;;)
{
char *token = NULL;
int type;
token = strtok(buf, str_delimiter);
if (!token)
break;
for (int i = 0; i < cols_count-1; i++)
{
str_to_flt_elem( token, el_ptr[i], type);
var_types_ptr[i] |= type;
token = strtok(NULL, str_delimiter);
if (!token)
{
fclose(file);
delete [] el_ptr;
return -1;
}
}
str_to_flt_elem( token, el_ptr[cols_count-1], type);
var_types_ptr[cols_count-1] |= type;
cvSeqPush( seq, el_ptr );
if( !fgets_chomp( buf, M, file ) )
break;
}
fclose(file);
values = cvCreateMat( seq->total, cols_count, CV_32FC1 );
missing = cvCreateMat( seq->total, cols_count, CV_8U );
var_idx_mask = cvCreateMat( 1, values->cols, CV_8UC1 );
cvSet( var_idx_mask, cvRealScalar(1) );
train_sample_count = seq->total;
cvStartReadSeq( seq, &reader );
for(int i = 0; i < seq->total; i++ )
{
const float* sdata = (float*)reader.ptr;
float* ddata = values->data.fl + cols_count*i;
uchar* dm = missing->data.ptr + cols_count*i;
for( int j = 0; j < cols_count; j++ )
{
ddata[j] = sdata[j];
dm[j] = ( fabs( MISS_VAL - sdata[j] ) <= FLT_EPSILON );
}
CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
}
if ( cvNorm( missing, 0, CV_L1 ) <= FLT_EPSILON )
cvReleaseMat( &missing );
cvReleaseMemStorage( &storage );
delete []el_ptr;
return 0;
}
const CvMat* CvMLData::get_values() const
{
return values;
}
const CvMat* CvMLData::get_missing() const
{
CV_FUNCNAME( "CvMLData::get_missing" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
__END__;
return missing;
}
const std::map<cv::String, int>& CvMLData::get_class_labels_map() const
{
return class_map;
}
void CvMLData::str_to_flt_elem( const char* token, float& flt_elem, int& type)
{
char* stopstring = NULL;
flt_elem = (float)strtod( token, &stopstring );
assert( stopstring );
type = CV_VAR_ORDERED;
if ( *stopstring == miss_ch && strlen(stopstring) == 1 ) // missed value
{
flt_elem = MISS_VAL;
type = CV_VAR_MISS;
}
else
{
if ( (*stopstring != 0) && (*stopstring != '\n') && (strcmp(stopstring, "\r\n") != 0) ) // class label
{
int idx = class_map[token];
if ( idx == 0)
{
total_class_count++;
idx = total_class_count;
class_map[token] = idx;
}
flt_elem = (float)idx;
type = CV_VAR_CATEGORICAL;
}
}
}
void CvMLData::set_delimiter(char ch)
{
CV_FUNCNAME( "CvMLData::set_delimited" );
__BEGIN__;
if (ch == miss_ch /*|| ch == flt_separator*/)
CV_ERROR(CV_StsBadArg, "delimited, miss_character and flt_separator must be different");
delimiter = ch;
__END__;
}
char CvMLData::get_delimiter() const
{
return delimiter;
}
void CvMLData::set_miss_ch(char ch)
{
CV_FUNCNAME( "CvMLData::set_miss_ch" );
__BEGIN__;
if (ch == delimiter/* || ch == flt_separator*/)
CV_ERROR(CV_StsBadArg, "delimited, miss_character and flt_separator must be different");
miss_ch = ch;
__END__;
}
char CvMLData::get_miss_ch() const
{
return miss_ch;
}
void CvMLData::set_response_idx( int idx )
{
CV_FUNCNAME( "CvMLData::set_response_idx" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
if ( idx >= values->cols)
CV_ERROR( CV_StsBadArg, "idx value is not correct" );
if ( response_idx >= 0 )
chahge_var_idx( response_idx, true );
if ( idx >= 0 )
chahge_var_idx( idx, false );
response_idx = idx;
__END__;
}
int CvMLData::get_response_idx() const
{
CV_FUNCNAME( "CvMLData::get_response_idx" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
__END__;
return response_idx;
}
void CvMLData::change_var_type( int var_idx, int type )
{
CV_FUNCNAME( "CvMLData::change_var_type" );
__BEGIN__;
int var_count = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
var_count = values->cols;
if ( var_idx < 0 || var_idx >= var_count)
CV_ERROR( CV_StsBadArg, "var_idx is not correct" );
if ( type != CV_VAR_ORDERED && type != CV_VAR_CATEGORICAL)
CV_ERROR( CV_StsBadArg, "type is not correct" );
assert( var_types );
if ( var_types->data.ptr[var_idx] == CV_VAR_CATEGORICAL && type == CV_VAR_ORDERED)
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" );
var_types->data.ptr[var_idx] = (uchar)type;
__END__;
return;
}
void CvMLData::set_var_types( const char* str )
{
CV_FUNCNAME( "CvMLData::set_var_types" );
__BEGIN__;
const char* ord = 0, *cat = 0;
int var_count = 0, set_var_type_count = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
var_count = values->cols;
assert( var_types );
ord = strstr( str, "ord" );
cat = strstr( str, "cat" );
if ( !ord && !cat )
CV_ERROR( CV_StsBadArg, "types string is not correct" );
if ( !ord && strlen(cat) == 3 ) // str == "cat"
{
cvSet( var_types, cvScalarAll(CV_VAR_CATEGORICAL) );
return;
}
if ( !cat && strlen(ord) == 3 ) // str == "ord"
{
cvSet( var_types, cvScalarAll(CV_VAR_ORDERED) );
return;
}
if ( ord ) // parse ord str
{
char* stopstring = NULL;
if ( ord[3] != '[')
CV_ERROR( CV_StsBadArg, "types string is not correct" );
ord += 4; // pass "ord["
do
{
int b1 = (int)strtod( ord, &stopstring );
if ( *stopstring == 0 || (*stopstring != ',' && *stopstring != ']' && *stopstring != '-') )
CV_ERROR( CV_StsBadArg, "types string is not correct" );
ord = stopstring + 1;
if ( (stopstring[0] == ',') || (stopstring[0] == ']'))
{
if ( var_types->data.ptr[b1] == CV_VAR_CATEGORICAL)
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" );
var_types->data.ptr[b1] = CV_VAR_ORDERED;
set_var_type_count++;
}
else
{
if ( stopstring[0] == '-')
{
int b2 = (int)strtod( ord, &stopstring);
if ( (*stopstring == 0) || (*stopstring != ',' && *stopstring != ']') )
CV_ERROR( CV_StsBadArg, "types string is not correct" );
ord = stopstring + 1;
for (int i = b1; i <= b2; i++)
{
if ( var_types->data.ptr[i] == CV_VAR_CATEGORICAL)
CV_ERROR( CV_StsBadArg, "it`s impossible to assign CV_VAR_ORDERED type to categorical variable" );
var_types->data.ptr[i] = CV_VAR_ORDERED;
}
set_var_type_count += b2 - b1 + 1;
}
else
CV_ERROR( CV_StsBadArg, "types string is not correct" );
}
}
while (*stopstring != ']');
if ( stopstring[1] != '\0' && stopstring[1] != ',')
CV_ERROR( CV_StsBadArg, "types string is not correct" );
}
if ( cat ) // parse cat str
{
char* stopstring = NULL;
if ( cat[3] != '[')
CV_ERROR( CV_StsBadArg, "types string is not correct" );
cat += 4; // pass "cat["
do
{
int b1 = (int)strtod( cat, &stopstring );
if ( *stopstring == 0 || (*stopstring != ',' && *stopstring != ']' && *stopstring != '-') )
CV_ERROR( CV_StsBadArg, "types string is not correct" );
cat = stopstring + 1;
if ( (stopstring[0] == ',') || (stopstring[0] == ']'))
{
var_types->data.ptr[b1] = CV_VAR_CATEGORICAL;
set_var_type_count++;
}
else
{
if ( stopstring[0] == '-')
{
int b2 = (int)strtod( cat, &stopstring);
if ( (*stopstring == 0) || (*stopstring != ',' && *stopstring != ']') )
CV_ERROR( CV_StsBadArg, "types string is not correct" );
cat = stopstring + 1;
for (int i = b1; i <= b2; i++)
var_types->data.ptr[i] = CV_VAR_CATEGORICAL;
set_var_type_count += b2 - b1 + 1;
}
else
CV_ERROR( CV_StsBadArg, "types string is not correct" );
}
}
while (*stopstring != ']');
if ( stopstring[1] != '\0' && stopstring[1] != ',')
CV_ERROR( CV_StsBadArg, "types string is not correct" );
}
if (set_var_type_count != var_count)
CV_ERROR( CV_StsBadArg, "types string is not correct" );
__END__;
}
const CvMat* CvMLData::get_var_types()
{
CV_FUNCNAME( "CvMLData::get_var_types" );
__BEGIN__;
uchar *var_types_out_ptr = 0;
int avcount, vt_size;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
assert( var_idx_mask );
avcount = cvFloor( cvNorm( var_idx_mask, 0, CV_L1 ) );
vt_size = avcount + (response_idx >= 0);
if ( avcount == values->cols || (avcount == values->cols-1 && response_idx == values->cols-1) )
return var_types;
if ( !var_types_out || ( var_types_out && var_types_out->cols != vt_size ) )
{
cvReleaseMat( &var_types_out );
var_types_out = cvCreateMat( 1, vt_size, CV_8UC1 );
}
var_types_out_ptr = var_types_out->data.ptr;
for( int i = 0; i < var_types->cols; i++)
{
if (i == response_idx || !var_idx_mask->data.ptr[i]) continue;
*var_types_out_ptr = var_types->data.ptr[i];
var_types_out_ptr++;
}
if ( response_idx >= 0 )
*var_types_out_ptr = var_types->data.ptr[response_idx];
__END__;
return var_types_out;
}
int CvMLData::get_var_type( int var_idx ) const
{
return var_types->data.ptr[var_idx];
}
const CvMat* CvMLData::get_responses()
{
CV_FUNCNAME( "CvMLData::get_responses_ptr" );
__BEGIN__;
int var_count = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
var_count = values->cols;
if ( response_idx < 0 || response_idx >= var_count )
return 0;
if ( !response_out )
response_out = cvCreateMatHeader( values->rows, 1, CV_32FC1 );
else
cvInitMatHeader( response_out, values->rows, 1, CV_32FC1);
cvGetCol( values, response_out, response_idx );
__END__;
return response_out;
}
void CvMLData::set_train_test_split( const CvTrainTestSplit * spl)
{
CV_FUNCNAME( "CvMLData::set_division" );
__BEGIN__;
int sample_count = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
sample_count = values->rows;
float train_sample_portion;
if (spl->train_sample_part_mode == CV_COUNT)
{
train_sample_count = spl->train_sample_part.count;
if (train_sample_count > sample_count)
CV_ERROR( CV_StsBadArg, "train samples count is not correct" );
train_sample_count = train_sample_count<=0 ? sample_count : train_sample_count;
}
else // dtype.train_sample_part_mode == CV_PORTION
{
train_sample_portion = spl->train_sample_part.portion;
if ( train_sample_portion > 1)
CV_ERROR( CV_StsBadArg, "train samples count is not correct" );
train_sample_portion = train_sample_portion <= FLT_EPSILON ||
1 - train_sample_portion <= FLT_EPSILON ? 1 : train_sample_portion;
train_sample_count = std::max(1, cvFloor( train_sample_portion * sample_count ));
}
if ( train_sample_count == sample_count )
{
free_train_test_idx();
return;
}
if ( train_sample_idx && train_sample_idx->cols != train_sample_count )
free_train_test_idx();
if ( !sample_idx)
{
int test_sample_count = sample_count- train_sample_count;
sample_idx = (int*)cvAlloc( sample_count * sizeof(sample_idx[0]) );
for (int i = 0; i < sample_count; i++ )
sample_idx[i] = i;
train_sample_idx = cvCreateMatHeader( 1, train_sample_count, CV_32SC1 );
*train_sample_idx = cvMat( 1, train_sample_count, CV_32SC1, &sample_idx[0] );
CV_Assert(test_sample_count > 0);
test_sample_idx = cvCreateMatHeader( 1, test_sample_count, CV_32SC1 );
*test_sample_idx = cvMat( 1, test_sample_count, CV_32SC1, &sample_idx[train_sample_count] );
}
mix = spl->mix;
if ( mix )
mix_train_and_test_idx();
__END__;
}
const CvMat* CvMLData::get_train_sample_idx() const
{
CV_FUNCNAME( "CvMLData::get_train_sample_idx" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
__END__;
return train_sample_idx;
}
const CvMat* CvMLData::get_test_sample_idx() const
{
CV_FUNCNAME( "CvMLData::get_test_sample_idx" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
__END__;
return test_sample_idx;
}
void CvMLData::mix_train_and_test_idx()
{
CV_FUNCNAME( "CvMLData::mix_train_and_test_idx" );
__BEGIN__;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
__END__;
if ( !sample_idx)
return;
if ( train_sample_count > 0 && train_sample_count < values->rows )
{
int n = values->rows;
for (int i = 0; i < n; i++)
{
int a = (*rng)(n);
int b = (*rng)(n);
int t;
CV_SWAP( sample_idx[a], sample_idx[b], t );
}
}
}
const CvMat* CvMLData::get_var_idx()
{
CV_FUNCNAME( "CvMLData::get_var_idx" );
__BEGIN__;
int avcount = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
assert( var_idx_mask );
avcount = cvFloor( cvNorm( var_idx_mask, 0, CV_L1 ) );
int* vidx;
if ( avcount == values->cols )
return 0;
if ( !var_idx_out || ( var_idx_out && var_idx_out->cols != avcount ) )
{
cvReleaseMat( &var_idx_out );
var_idx_out = cvCreateMat( 1, avcount, CV_32SC1);
if ( response_idx >=0 )
var_idx_mask->data.ptr[response_idx] = 0;
}
vidx = var_idx_out->data.i;
for(int i = 0; i < var_idx_mask->cols; i++)
if ( var_idx_mask->data.ptr[i] )
{
*vidx = i;
vidx++;
}
__END__;
return var_idx_out;
}
void CvMLData::chahge_var_idx( int vi, bool state )
{
change_var_idx( vi, state );
}
void CvMLData::change_var_idx( int vi, bool state )
{
CV_FUNCNAME( "CvMLData::change_var_idx" );
__BEGIN__;
int var_count = 0;
if ( !values )
CV_ERROR( CV_StsInternal, "data is empty" );
var_count = values->cols;
if ( vi < 0 || vi >= var_count)
CV_ERROR( CV_StsBadArg, "variable index is not correct" );
assert( var_idx_mask );
var_idx_mask->data.ptr[vi] = state;
__END__;
}
/* End of file. */

File diff suppressed because it is too large Load Diff

@ -1,376 +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
//
// 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 OPENCV_PRECOMP_H
#define OPENCV_PRECOMP_H
#include "opencv2/core.hpp"
#include "old_ml.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/private.hpp"
#include <assert.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define ML_IMPL CV_IMPL
#define __BEGIN__ __CV_BEGIN__
#define __END__ __CV_END__
#define EXIT __CV_EXIT__
#define CV_MAT_ELEM_FLAG( mat, type, comp, vect, tflag ) \
(( tflag == CV_ROW_SAMPLE ) \
? (CV_MAT_ELEM( mat, type, comp, vect )) \
: (CV_MAT_ELEM( mat, type, vect, comp )))
/* Convert matrix to vector */
#define ICV_MAT2VEC( mat, vdata, vstep, num ) \
if( MIN( (mat).rows, (mat).cols ) != 1 ) \
CV_ERROR( CV_StsBadArg, "" ); \
(vdata) = ((mat).data.ptr); \
if( (mat).rows == 1 ) \
{ \
(vstep) = CV_ELEM_SIZE( (mat).type ); \
(num) = (mat).cols; \
} \
else \
{ \
(vstep) = (mat).step; \
(num) = (mat).rows; \
}
/* get raw data */
#define ICV_RAWDATA( mat, flags, rdata, sstep, cstep, m, n ) \
(rdata) = (mat).data.ptr; \
if( CV_IS_ROW_SAMPLE( flags ) ) \
{ \
(sstep) = (mat).step; \
(cstep) = CV_ELEM_SIZE( (mat).type ); \
(m) = (mat).rows; \
(n) = (mat).cols; \
} \
else \
{ \
(cstep) = (mat).step; \
(sstep) = CV_ELEM_SIZE( (mat).type ); \
(n) = (mat).rows; \
(m) = (mat).cols; \
}
#define ICV_IS_MAT_OF_TYPE( mat, mat_type) \
(CV_IS_MAT( mat ) && CV_MAT_TYPE( mat->type ) == (mat_type) && \
(mat)->cols > 0 && (mat)->rows > 0)
/*
uchar* data; int sstep, cstep; - trainData->data
uchar* classes; int clstep; int ncl;- trainClasses
uchar* tmask; int tmstep; int ntm; - typeMask
uchar* missed;int msstep, mcstep; -missedMeasurements...
int mm, mn; == m,n == size,dim
uchar* sidx;int sistep; - sampleIdx
uchar* cidx;int cistep; - compIdx
int k, l; == n,m == dim,size (length of cidx, sidx)
int m, n; == size,dim
*/
#define ICV_DECLARE_TRAIN_ARGS() \
uchar* data; \
int sstep, cstep; \
uchar* classes; \
int clstep; \
int ncl; \
uchar* tmask; \
int tmstep; \
int ntm; \
uchar* missed; \
int msstep, mcstep; \
int mm, mn; \
uchar* sidx; \
int sistep; \
uchar* cidx; \
int cistep; \
int k, l; \
int m, n; \
\
data = classes = tmask = missed = sidx = cidx = NULL; \
sstep = cstep = clstep = ncl = tmstep = ntm = msstep = mcstep = mm = mn = 0; \
sistep = cistep = k = l = m = n = 0;
#define ICV_TRAIN_DATA_REQUIRED( param, flags ) \
if( !ICV_IS_MAT_OF_TYPE( (param), CV_32FC1 ) ) \
{ \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
else \
{ \
ICV_RAWDATA( *(param), (flags), data, sstep, cstep, m, n ); \
k = n; \
l = m; \
}
#define ICV_TRAIN_CLASSES_REQUIRED( param ) \
if( !ICV_IS_MAT_OF_TYPE( (param), CV_32FC1 ) ) \
{ \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
else \
{ \
ICV_MAT2VEC( *(param), classes, clstep, ncl ); \
if( m != ncl ) \
{ \
CV_ERROR( CV_StsBadArg, "Unmatched sizes" ); \
} \
}
#define ICV_ARG_NULL( param ) \
if( (param) != NULL ) \
{ \
CV_ERROR( CV_StsBadArg, #param " parameter must be NULL" ); \
}
#define ICV_MISSED_MEASUREMENTS_OPTIONAL( param, flags ) \
if( param ) \
{ \
if( !ICV_IS_MAT_OF_TYPE( param, CV_8UC1 ) ) \
{ \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
else \
{ \
ICV_RAWDATA( *(param), (flags), missed, msstep, mcstep, mm, mn ); \
if( mm != m || mn != n ) \
{ \
CV_ERROR( CV_StsBadArg, "Unmatched sizes" ); \
} \
} \
}
#define ICV_COMP_IDX_OPTIONAL( param ) \
if( param ) \
{ \
if( !ICV_IS_MAT_OF_TYPE( param, CV_32SC1 ) ) \
{ \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
else \
{ \
ICV_MAT2VEC( *(param), cidx, cistep, k ); \
if( k > n ) \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
}
#define ICV_SAMPLE_IDX_OPTIONAL( param ) \
if( param ) \
{ \
if( !ICV_IS_MAT_OF_TYPE( param, CV_32SC1 ) ) \
{ \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
else \
{ \
ICV_MAT2VEC( *sampleIdx, sidx, sistep, l ); \
if( l > m ) \
CV_ERROR( CV_StsBadArg, "Invalid " #param " parameter" ); \
} \
}
/****************************************************************************************/
#define ICV_CONVERT_FLOAT_ARRAY_TO_MATRICE( array, matrice ) \
{ \
CvMat a, b; \
int dims = (matrice)->cols; \
int nsamples = (matrice)->rows; \
int type = CV_MAT_TYPE((matrice)->type); \
int i, offset = dims; \
\
CV_ASSERT( type == CV_32FC1 || type == CV_64FC1 ); \
offset *= ((type == CV_32FC1) ? sizeof(float) : sizeof(double));\
\
b = cvMat( 1, dims, CV_32FC1 ); \
cvGetRow( matrice, &a, 0 ); \
for( i = 0; i < nsamples; i++, a.data.ptr += offset ) \
{ \
b.data.fl = (float*)array[i]; \
CV_CALL( cvConvert( &b, &a ) ); \
} \
}
/****************************************************************************************\
* Auxiliary functions declarations *
\****************************************************************************************/
/* Generates a set of classes centers in quantity <num_of_clusters> that are generated as
uniform random vectors in parallelepiped, where <data> is concentrated. Vectors in
<data> should have horizontal orientation. If <centers> != NULL, the function doesn't
allocate any memory and stores generated centers in <centers>, returns <centers>.
If <centers> == NULL, the function allocates memory and creates the matrice. Centers
are supposed to be oriented horizontally. */
CvMat* icvGenerateRandomClusterCenters( int seed,
const CvMat* data,
int num_of_clusters,
CvMat* centers CV_DEFAULT(0));
/* Fills the <labels> using <probs> by choosing the maximal probability. Outliers are
fixed by <oulier_tresh> and have cluster label (-1). Function also controls that there
weren't "empty" clusters by filling empty clusters with the maximal probability vector.
If probs_sums != NULL, fills it with the sums of probabilities for each sample (it is
useful for normalizing probabilities' matrice of FCM) */
void icvFindClusterLabels( const CvMat* probs, float outlier_thresh, float r,
const CvMat* labels );
typedef struct CvSparseVecElem32f
{
int idx;
float val;
}
CvSparseVecElem32f;
/* Prepare training data and related parameters */
#define CV_TRAIN_STATMODEL_DEFRAGMENT_TRAIN_DATA 1
#define CV_TRAIN_STATMODEL_SAMPLES_AS_ROWS 2
#define CV_TRAIN_STATMODEL_SAMPLES_AS_COLUMNS 4
#define CV_TRAIN_STATMODEL_CATEGORICAL_RESPONSE 8
#define CV_TRAIN_STATMODEL_ORDERED_RESPONSE 16
#define CV_TRAIN_STATMODEL_RESPONSES_ON_OUTPUT 32
#define CV_TRAIN_STATMODEL_ALWAYS_COPY_TRAIN_DATA 64
#define CV_TRAIN_STATMODEL_SPARSE_AS_SPARSE 128
int
cvPrepareTrainData( const char* /*funcname*/,
const CvMat* train_data, int tflag,
const CvMat* responses, int response_type,
const CvMat* var_idx,
const CvMat* sample_idx,
bool always_copy_data,
const float*** out_train_samples,
int* _sample_count,
int* _var_count,
int* _var_all,
CvMat** out_responses,
CvMat** out_response_map,
CvMat** out_var_idx,
CvMat** out_sample_idx=0 );
void
cvSortSamplesByClasses( const float** samples, const CvMat* classes,
int* class_ranges, const uchar** mask CV_DEFAULT(0) );
void
cvCombineResponseMaps (CvMat* _responses,
const CvMat* old_response_map,
CvMat* new_response_map,
CvMat** out_response_map);
void
cvPreparePredictData( const CvArr* sample, int dims_all, const CvMat* comp_idx,
int class_count, const CvMat* prob, float** row_sample,
int as_sparse CV_DEFAULT(0) );
/* copies clustering [or batch "predict"] results
(labels and/or centers and/or probs) back to the output arrays */
void
cvWritebackLabels( const CvMat* labels, CvMat* dst_labels,
const CvMat* centers, CvMat* dst_centers,
const CvMat* probs, CvMat* dst_probs,
const CvMat* sample_idx, int samples_all,
const CvMat* comp_idx, int dims_all );
#define cvWritebackResponses cvWritebackLabels
#define XML_FIELD_NAME "_name"
cv::FileNode icvFileNodeGetChild( cv::FileNode& father, const char* name );
cv::FileNode icvFileNodeGetChildArrayElem( cv::FileNode& father, const char* name,int index );
cv::FileNode icvFileNodeGetNext( cv::FileNode& n, const char* name );
void cvCheckTrainData( const CvMat* train_data, int tflag,
const CvMat* missing_mask,
int* var_all, int* sample_all );
CvMat* cvPreprocessIndexArray( const CvMat* idx_arr, int data_arr_size, bool check_for_duplicates=false );
CvMat* cvPreprocessVarType( const CvMat* type_mask, const CvMat* var_idx,
int var_all, int* response_type );
CvMat* cvPreprocessOrderedResponses( const CvMat* responses,
const CvMat* sample_idx, int sample_all );
CvMat* cvPreprocessCategoricalResponses( const CvMat* responses,
const CvMat* sample_idx, int sample_all,
CvMat** out_response_map, CvMat** class_counts=0 );
const float** cvGetTrainSamples( const CvMat* train_data, int tflag,
const CvMat* var_idx, const CvMat* sample_idx,
int* _var_count, int* _sample_count,
bool always_copy_data=false );
namespace cv
{
struct DTreeBestSplitFinder
{
DTreeBestSplitFinder(){ splitSize = 0, tree = 0; node = 0; }
DTreeBestSplitFinder( CvDTree* _tree, CvDTreeNode* _node);
DTreeBestSplitFinder( const DTreeBestSplitFinder& finder, Split );
virtual ~DTreeBestSplitFinder() {}
virtual void operator()(const BlockedRange& range);
void join( DTreeBestSplitFinder& rhs );
Ptr<CvDTreeSplit> bestSplit;
Ptr<CvDTreeSplit> split;
int splitSize;
CvDTree* tree;
CvDTreeNode* node;
};
struct ForestTreeBestSplitFinder : DTreeBestSplitFinder
{
ForestTreeBestSplitFinder() : DTreeBestSplitFinder() {}
ForestTreeBestSplitFinder( CvForestTree* _tree, CvDTreeNode* _node );
ForestTreeBestSplitFinder( const ForestTreeBestSplitFinder& finder, Split );
virtual void operator()(const BlockedRange& range);
};
}
#endif /* __ML_H__ */

File diff suppressed because it is too large Load Diff

@ -1,129 +0,0 @@
#include "opencv2/core.hpp"
#include "cascadeclassifier.h"
using namespace std;
using namespace cv;
/*
traincascade.cpp is the source file of the program used for cascade training.
User has to provide training input in form of positive and negative training images,
and other data related to training in form of command line argument.
*/
int main( int argc, char* argv[] )
{
CvCascadeClassifier classifier;
string cascadeDirName, vecName, bgName;
int numPos = 2000;
int numNeg = 1000;
int numStages = 20;
int numThreads = getNumThreads();
int precalcValBufSize = 1024,
precalcIdxBufSize = 1024;
bool baseFormatSave = false;
double acceptanceRatioBreakValue = -1.0;
CvCascadeParams cascadeParams;
CvCascadeBoostParams stageParams;
Ptr<CvFeatureParams> featureParams[] = { makePtr<CvHaarFeatureParams>(),
makePtr<CvLBPFeatureParams>(),
makePtr<CvHOGFeatureParams>()
};
int fc = sizeof(featureParams)/sizeof(featureParams[0]);
if( argc == 1 )
{
cout << "Usage: " << argv[0] << endl;
cout << " -data <cascade_dir_name>" << endl;
cout << " -vec <vec_file_name>" << endl;
cout << " -bg <background_file_name>" << endl;
cout << " [-numPos <number_of_positive_samples = " << numPos << ">]" << endl;
cout << " [-numNeg <number_of_negative_samples = " << numNeg << ">]" << endl;
cout << " [-numStages <number_of_stages = " << numStages << ">]" << endl;
cout << " [-precalcValBufSize <precalculated_vals_buffer_size_in_Mb = " << precalcValBufSize << ">]" << endl;
cout << " [-precalcIdxBufSize <precalculated_idxs_buffer_size_in_Mb = " << precalcIdxBufSize << ">]" << endl;
cout << " [-baseFormatSave]" << endl;
cout << " [-numThreads <max_number_of_threads = " << numThreads << ">]" << endl;
cout << " [-acceptanceRatioBreakValue <value> = " << acceptanceRatioBreakValue << ">]" << endl;
cascadeParams.printDefaults();
stageParams.printDefaults();
for( int fi = 0; fi < fc; fi++ )
featureParams[fi]->printDefaults();
return 0;
}
for( int i = 1; i < argc; i++ )
{
bool set = false;
if( !strcmp( argv[i], "-data" ) )
{
cascadeDirName = argv[++i];
}
else if( !strcmp( argv[i], "-vec" ) )
{
vecName = argv[++i];
}
else if( !strcmp( argv[i], "-bg" ) )
{
bgName = argv[++i];
}
else if( !strcmp( argv[i], "-numPos" ) )
{
numPos = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-numNeg" ) )
{
numNeg = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-numStages" ) )
{
numStages = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-precalcValBufSize" ) )
{
precalcValBufSize = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-precalcIdxBufSize" ) )
{
precalcIdxBufSize = atoi( argv[++i] );
}
else if( !strcmp( argv[i], "-baseFormatSave" ) )
{
baseFormatSave = true;
}
else if( !strcmp( argv[i], "-numThreads" ) )
{
numThreads = atoi(argv[++i]);
}
else if( !strcmp( argv[i], "-acceptanceRatioBreakValue" ) )
{
acceptanceRatioBreakValue = atof(argv[++i]);
}
else if ( cascadeParams.scanAttr( argv[i], argv[i+1] ) ) { i++; }
else if ( stageParams.scanAttr( argv[i], argv[i+1] ) ) { i++; }
else if ( !set )
{
for( int fi = 0; fi < fc; fi++ )
{
set = featureParams[fi]->scanAttr(argv[i], argv[i+1]);
if ( !set )
{
i++;
break;
}
}
}
}
setNumThreads( numThreads );
classifier.train( cascadeDirName,
vecName,
bgName,
numPos, numNeg,
precalcValBufSize, precalcIdxBufSize,
numStages,
cascadeParams,
*featureParams[cascadeParams.featureType],
stageParams,
baseFormatSave,
acceptanceRatioBreakValue );
return 0;
}

@ -1,101 +0,0 @@
#ifndef _OPENCV_FEATURES_H_
#define _OPENCV_FEATURES_H_
#include "imagestorage.h"
#include <stdio.h>
#define FEATURES "features"
#define CV_SUM_OFFSETS( p0, p1, p2, p3, rect, step ) \
/* (x, y) */ \
(p0) = (rect).x + (step) * (rect).y; \
/* (x + w, y) */ \
(p1) = (rect).x + (rect).width + (step) * (rect).y; \
/* (x + w, y) */ \
(p2) = (rect).x + (step) * ((rect).y + (rect).height); \
/* (x + w, y + h) */ \
(p3) = (rect).x + (rect).width + (step) * ((rect).y + (rect).height);
#define CV_TILTED_OFFSETS( p0, p1, p2, p3, rect, step ) \
/* (x, y) */ \
(p0) = (rect).x + (step) * (rect).y; \
/* (x - h, y + h) */ \
(p1) = (rect).x - (rect).height + (step) * ((rect).y + (rect).height);\
/* (x + w, y + w) */ \
(p2) = (rect).x + (rect).width + (step) * ((rect).y + (rect).width); \
/* (x + w - h, y + w + h) */ \
(p3) = (rect).x + (rect).width - (rect).height \
+ (step) * ((rect).y + (rect).width + (rect).height);
float calcNormFactor( const cv::Mat& sum, const cv::Mat& sqSum );
template<class Feature>
void _writeFeatures( const std::vector<Feature> features, cv::FileStorage &fs, const cv::Mat& featureMap )
{
fs << FEATURES << "[";
const cv::Mat_<int>& featureMap_ = (const cv::Mat_<int>&)featureMap;
for ( int fi = 0; fi < featureMap.cols; fi++ )
if ( featureMap_(0, fi) >= 0 )
{
fs << "{";
features[fi].write( fs );
fs << "}";
}
fs << "]";
}
class CvParams
{
public:
CvParams();
virtual ~CvParams() {}
// from|to file
virtual void write( cv::FileStorage &fs ) const = 0;
virtual bool read( const cv::FileNode &node ) = 0;
// from|to screen
virtual void printDefaults() const;
virtual void printAttrs() const;
virtual bool scanAttr( const std::string prmName, const std::string val );
std::string name;
};
class CvFeatureParams : public CvParams
{
public:
enum { HAAR = 0, LBP = 1, HOG = 2 };
CvFeatureParams();
virtual void init( const CvFeatureParams& fp );
virtual void write( cv::FileStorage &fs ) const;
virtual bool read( const cv::FileNode &node );
static cv::Ptr<CvFeatureParams> create( int featureType );
int maxCatCount; // 0 in case of numerical features
int featSize; // 1 in case of simple features (HAAR, LBP) and N_BINS(9)*N_CELLS(4) in case of Dalal's HOG features
};
class CvFeatureEvaluator
{
public:
virtual ~CvFeatureEvaluator() {}
virtual void init(const CvFeatureParams *_featureParams,
int _maxSampleCount, cv::Size _winSize );
virtual void setImage(const cv::Mat& img, uchar clsLabel, int idx);
virtual void writeFeatures( cv::FileStorage &fs, const cv::Mat& featureMap ) const = 0;
virtual float operator()(int featureIdx, int sampleIdx) const = 0;
static cv::Ptr<CvFeatureEvaluator> create(int type);
int getNumFeatures() const { return numFeatures; }
int getMaxCatCount() const { return featureParams->maxCatCount; }
int getFeatureSize() const { return featureParams->featSize; }
const cv::Mat& getCls() const { return cls; }
float getCls(int si) const { return cls.at<float>(si, 0); }
protected:
virtual void generateFeatures() = 0;
int npos, nneg;
int numFeatures;
cv::Size winSize;
CvFeatureParams *featureParams;
cv::Mat cls;
};
#endif

@ -3,7 +3,7 @@ Barcode Recognition {#tutorial_barcode_detect_and_decode}
@tableofcontents
@prev_tutorial{tutorial_traincascade}
@prev_tutorial{tutorial_cascade_classifier}
@next_tutorial{tutorial_introduction_to_pca}
| | |

@ -4,7 +4,7 @@ Cascade Classifier {#tutorial_cascade_classifier}
@tableofcontents
@prev_tutorial{tutorial_optical_flow}
@next_tutorial{tutorial_traincascade}
@next_tutorial{tutorial_barcode_detect_and_decode}
| | |
| -: | :- |
@ -95,8 +95,8 @@ more details or check out the references in the Additional Resources section.
Haar-cascade Detection in OpenCV
--------------------------------
OpenCV provides a training method (see @ref tutorial_traincascade) or pretrained models, that can be read using the @ref cv::CascadeClassifier::load method.
The pretrained models are located in the data folder in the OpenCV installation or can be found [here](https://github.com/opencv/opencv/tree/5.x/data).
OpenCV provides pretrained models that can be read using the @ref cv::CascadeClassifier::load method.
These models are located in the data folder in the OpenCV installation or can be found [here](https://github.com/opencv/opencv/tree/5.x/data).
The following code example will use pretrained Haar cascade models to detect faces and eyes in an image.
First, a @ref cv::CascadeClassifier is created and the necessary XML file is loaded using the @ref cv::CascadeClassifier::load method.

@ -7,6 +7,5 @@ Other tutorials (objdetect, photo, stitching, video) {#tutorial_table_of_content
- video. @subpage tutorial_meanshift
- video. @subpage tutorial_optical_flow
- objdetect. @subpage tutorial_cascade_classifier
- objdetect. @subpage tutorial_traincascade
- objdetect. @subpage tutorial_barcode_detect_and_decode
- ml. @subpage tutorial_introduction_to_pca

@ -1,224 +0,0 @@
Cascade Classifier Training {#tutorial_traincascade}
===========================
@tableofcontents
@prev_tutorial{tutorial_cascade_classifier}
@next_tutorial{tutorial_barcode_detect_and_decode}
Introduction
------------
Working with a boosted cascade of weak classifiers includes two major stages: the training and the detection stage. The detection stage using either HAAR or LBP based models, is described in the @ref tutorial_cascade_classifier "object detection tutorial". This documentation gives an overview of the functionality needed to train your own boosted cascade of weak classifiers. The current guide will walk through all the different stages: collecting training data, preparation of the training data and executing the actual model training.
To support this tutorial, several official OpenCV applications will be used: [opencv_createsamples](https://github.com/opencv/opencv/tree/5.x/apps/createsamples), [opencv_annotation](https://github.com/opencv/opencv/tree/5.x/apps/annotation), [opencv_traincascade](https://github.com/opencv/opencv/tree/5.x/apps/traincascade) and [opencv_visualisation](https://github.com/opencv/opencv/tree/5.x/apps/visualisation).
@note Createsamples and traincascade are disabled since OpenCV 4.0. Consider using these apps for training from 3.4 branch for Cascade Classifier. Model format is the same between 3.4 and 4.x.
### Important notes
- If you come across any tutorial mentioning the old opencv_haartraining tool <i>(which is deprecated and still using the OpenCV1.x interface)</i>, then please ignore that tutorial and stick to the opencv_traincascade tool. This tool is a newer version, written in C++ in accordance to the OpenCV 2.x and OpenCV 3.x API. The opencv_traincascade supports both HAAR like wavelet features @cite Viola01 and LBP (Local Binary Patterns) @cite Liao2007 features. LBP features yield integer precision in contrast to HAAR features, yielding floating point precision, so both training and detection with LBP are several times faster then with HAAR features. Regarding the LBP and HAAR detection quality, it mainly depends on the training data used and the training parameters selected. It's possible to train a LBP-based classifier that will provide almost the same quality as HAAR-based one, within a percentage of the training time.
- The newer cascade classifier detection interface from OpenCV 2.x and OpenCV 3.x (@ref cv::CascadeClassifier) supports working with both old and new model formats. opencv_traincascade can even save (export) a trained cascade in the older format if for some reason you are stuck using the old interface. At least training the model could then be done in the most stable interface.
- The opencv_traincascade application can use TBB for multi-threading. To use it in multicore mode OpenCV must be built with TBB support enabled.
Preparation of the training data
--------------------------------
For training a boosted cascade of weak classifiers we need a set of positive samples (containing actual objects you want to detect) and a set of negative images (containing everything you do not want to detect). The set of negative samples must be prepared manually, whereas set of positive samples is created using the opencv_createsamples application.
### Negative Samples
Negative samples are taken from arbitrary images, not containing objects you want to detect. These negative images, from which the samples are generated, should be listed in a special negative image file containing one image path per line <i>(can be absolute or relative)</i>. Note that negative samples and sample images are also called background samples or background images, and are used interchangeably in this document.
Described images may be of different sizes. However, each image should be equal or larger than the desired training window size <i>(which corresponds to the model dimensions, most of the times being the average size of your object)</i>, because these images are used to subsample a given negative image into several image samples having this training window size.
An example of such a negative description file:
Directory structure:
@code{.text}
/img
img1.jpg
img2.jpg
bg.txt
@endcode
File bg.txt:
@code{.text}
img/img1.jpg
img/img2.jpg
@endcode
Your set of negative window samples will be used to tell the machine learning step, boosting in this case, what not to look for, when trying to find your objects of interest.
### Positive Samples
Positive samples are created by the opencv_createsamples application. They are used by the boosting process to define what the model should actually look for when trying to find your objects of interest. The application supports two ways of generating a positive sample dataset.
1. You can generate a bunch of positives from a single positive object image.
2. You can supply all the positives yourself and only use the tool to cut them out, resize them and put them in the opencv needed binary format.
While the first approach works decently for fixed objects, like very rigid logo's, it tends to fail rather soon for less rigid objects. In that case we do suggest to use the second approach. Many tutorials on the web even state that 100 real object images, can lead to a better model than 1000 artificially generated positives, by using the opencv_createsamples application. If you however do decide to take the first approach, keep some things in mind:
- Please note that you need more than a single positive samples before you give it to the mentioned application, because it only applies perspective transformation.
- If you want a robust model, take samples that cover the wide range of varieties that can occur within your object class. For example in the case of faces you should consider different races and age groups, emotions and perhaps beard styles. This also applies when using the second approach.
The first approach takes a single object image with for example a company logo and creates a large set of positive samples from the given object image by randomly rotating the object, changing the image intensity as well as placing the image on arbitrary backgrounds. The amount and range of randomness can be controlled by command line arguments of the opencv_createsamples application.
Command line arguments:
- `-vec <vec_file_name>` : Name of the output file containing the positive samples for training.
- `-img <image_file_name>` : Source object image (e.g., a company logo).
- `-bg <background_file_name>` : Background description file; contains a list of images which are used as a background for randomly distorted versions of the object.
- `-num <number_of_samples>` : Number of positive samples to generate.
- `-bgcolor <background_color>` : Background color (currently grayscale images are assumed); the background color denotes the transparent color. Since there might be compression artifacts, the amount of color tolerance can be specified by -bgthresh. All pixels within bgcolor-bgthresh and bgcolor+bgthresh range are interpreted as transparent.
- `-bgthresh <background_color_threshold>`
- `-inv` : If specified, colors will be inverted.
- `-randinv` : If specified, colors will be inverted randomly.
- `-maxidev <max_intensity_deviation>` : Maximal intensity deviation of pixels in foreground samples.
- `-maxxangle <max_x_rotation_angle>` : Maximal rotation angle towards x-axis, must be given in radians.
- `-maxyangle <max_y_rotation_angle>` : Maximal rotation angle towards y-axis, must be given in radians.
- `-maxzangle <max_z_rotation_angle>` : Maximal rotation angle towards z-axis, must be given in radians.
- `-show` : Useful debugging option. If specified, each sample will be shown. Pressing Esc will continue the samples creation process without showing each sample.
- `-w <sample_width>` : Width (in pixels) of the output samples.
- `-h <sample_height>` : Height (in pixels) of the output samples.
When running opencv_createsamples in this way, the following procedure is used to create a sample object instance: The given source image is rotated randomly around all three axes. The chosen angle is limited by `-maxxangle`, `-maxyangle` and `-maxzangle`. Then pixels having the intensity from the [bg_color-bg_color_threshold; bg_color+bg_color_threshold] range are interpreted as transparent. White noise is added to the intensities of the foreground. If the `-inv` key is specified then foreground pixel intensities are inverted. If `-randinv` key is specified then algorithm randomly selects whether inversion should be applied to this sample. Finally, the obtained image is placed onto an arbitrary background from the background description file, resized to the desired size specified by `-w` and `-h` and stored to the vec-file, specified by the `-vec` command line option.
Positive samples also may be obtained from a collection of previously marked up images, which is the desired way when building robust object models. This collection is described by a text file similar to the background description file. Each line of this file corresponds to an image. The first element of the line is the filename, followed by the number of object annotations, followed by numbers describing the coordinates of the objects bounding rectangles (x, y, width, height).
An example of description file:
Directory structure:
@code{.text}
/img
img1.jpg
img2.jpg
info.dat
@endcode
File info.dat:
@code{.text}
img/img1.jpg 1 140 100 45 45
img/img2.jpg 2 100 200 50 50 50 30 25 25
@endcode
Image img1.jpg contains single object instance with the following coordinates of bounding rectangle:
(140, 100, 45, 45). Image img2.jpg contains two object instances.
In order to create positive samples from such collection, `-info` argument should be specified instead of `-img`:
- `-info <collection_file_name>` : Description file of marked up images collection.
Note that in this case, parameters like `-bg, -bgcolor, -bgthreshold, -inv, -randinv, -maxxangle, -maxyangle, -maxzangle` are simply ignored and not used anymore. The scheme of samples creation in this case is as follows. The object instances are taken from the given images, by cutting out the supplied bounding boxes from the original images. Then they are resized to target samples size (defined by `-w` and `-h`) and stored in output vec-file, defined by the `-vec` parameter. No distortion is applied, so the only affecting arguments are `-w`, `-h`, `-show` and `-num`.
The manual process of creating the `-info` file can also been done by using the opencv_annotation tool. This is an open source tool for visually selecting the regions of interest of your object instances in any given images. The following subsection will discuss in more detail on how to use this application.
#### Extra remarks
- opencv_createsamples utility may be used for examining samples stored in any given positive samples file. In order to do this only `-vec`, `-w` and `-h` parameters should be specified.
- Example of vec-file is available here `opencv/data/vec_files/trainingfaces_24-24.vec`. It can be used to train a face detector with the following window size: `-w 24 -h 24`.
### Using OpenCV's integrated annotation tool
Since OpenCV 3.x the community has been supplying and maintaining a open source annotation tool, used for generating the `-info` file. The tool can be accessed by the command opencv_annotation if the OpenCV applications where build.
Using the tool is quite straightforward. The tool accepts several required and some optional parameters:
- `--annotations` <b>(required)</b> : path to annotations txt file, where you want to store your annotations, which is then passed to the `-info` parameter [example - /data/annotations.txt]
- `--images` <b>(required)</b> : path to folder containing the images with your objects [example - /data/testimages/]
- `--maxWindowHeight` <i>(optional)</i> : if the input image is larger in height then the given resolution here, resize the image for easier annotation, using `--resizeFactor`.
- `--resizeFactor` <i>(optional)</i> : factor used to resize the input image when using the `--maxWindowHeight` parameter.
Note that the optional parameters can only be used together. An example of a command that could be used can be seen below
@code{.text}
opencv_annotation --annotations=/path/to/annotations/file.txt --images=/path/to/image/folder/
@endcode
This command will fire up a window containing the first image and your mouse cursor which will be used for annotation. A video on how to use the annotation tool can be found [here](https://www.youtube.com/watch?v=EV5gmvoCTSk). Basically there are several keystrokes that trigger an action. The left mouse button is used to select the first corner of your object, then keeps drawing until you are fine, and stops when a second left mouse button click is registered. After each selection you have the following choices:
- Pressing `c` : confirm the annotation, turning the annotation green and confirming it is stored
- Pressing `d` : delete the last annotation from the list of annotations (easy for removing wrong annotations)
- Pressing `n` : continue to the next image
- Pressing `ESC` : this will exit the annotation software
Finally you will end up with a usable annotation file that can be passed to the `-info` argument of opencv_createsamples.
Cascade Training
----------------
The next step is the actual training of the boosted cascade of weak classifiers, based on the positive and negative dataset that was prepared beforehand.
Command line arguments of opencv_traincascade application grouped by purposes:
- Common arguments:
- `-data <cascade_dir_name>` : Where the trained classifier should be stored. This folder should be created manually beforehand.
- `-vec <vec_file_name>` : vec-file with positive samples (created by opencv_createsamples utility).
- `-bg <background_file_name>` : Background description file. This is the file containing the negative sample images.
- `-numPos <number_of_positive_samples>` : Number of positive samples used in training for every classifier stage.
- `-numNeg <number_of_negative_samples>` : Number of negative samples used in training for every classifier stage.
- `-numStages <number_of_stages>` : Number of cascade stages to be trained.
- `-precalcValBufSize <precalculated_vals_buffer_size_in_Mb>` : Size of buffer for precalculated feature values (in Mb). The more memory you assign the faster the training process, however keep in mind that `-precalcValBufSize` and `-precalcIdxBufSize` combined should not exceed you available system memory.
- `-precalcIdxBufSize <precalculated_idxs_buffer_size_in_Mb>` : Size of buffer for precalculated feature indices (in Mb). The more memory you assign the faster the training process, however keep in mind that `-precalcValBufSize` and `-precalcIdxBufSize` combined should not exceed you available system memory.
- `-baseFormatSave` : This argument is actual in case of Haar-like features. If it is specified, the cascade will be saved in the old format. This is only available for backwards compatibility reasons and to allow users stuck to the old deprecated interface, to at least train models using the newer interface.
- `-numThreads <max_number_of_threads>` : Maximum number of threads to use during training. Notice that the actual number of used threads may be lower, depending on your machine and compilation options. By default, the maximum available threads are selected if you built OpenCV with TBB support, which is needed for this optimization.
- `-acceptanceRatioBreakValue <break_value>` : This argument is used to determine how precise your model should keep learning and when to stop. A good guideline is to train not further than 10e-5, to ensure the model does not overtrain on your training data. By default this value is set to -1 to disable this feature.
- Cascade parameters:
- `-stageType <BOOST(default)>` : Type of stages. Only boosted classifiers are supported as a stage type at the moment.
- `-featureType<{HAAR(default), LBP}>` : Type of features: HAAR - Haar-like features, LBP - local binary patterns.
- `-w <sampleWidth>` : Width of training samples (in pixels). Must have exactly the same value as used during training samples creation (opencv_createsamples utility).
- `-h <sampleHeight>` : Height of training samples (in pixels). Must have exactly the same value as used during training samples creation (opencv_createsamples utility).
- Boosted classifier parameters:
- `-bt <{DAB, RAB, LB, GAB(default)}>` : Type of boosted classifiers: DAB - Discrete AdaBoost, RAB - Real AdaBoost, LB - LogitBoost, GAB - Gentle AdaBoost.
- `-minHitRate <min_hit_rate>` : Minimal desired hit rate for each stage of the classifier. Overall hit rate may be estimated as (min_hit_rate ^ number_of_stages), @cite Viola04 §4.1.
- `-maxFalseAlarmRate <max_false_alarm_rate>` : Maximal desired false alarm rate for each stage of the classifier. Overall false alarm rate may be estimated as (max_false_alarm_rate ^ number_of_stages), @cite Viola04 §4.1.
- `-weightTrimRate <weight_trim_rate>` : Specifies whether trimming should be used and its weight. A decent choice is 0.95.
- `-maxDepth <max_depth_of_weak_tree>` : Maximal depth of a weak tree. A decent choice is 1, that is case of stumps.
- `-maxWeakCount <max_weak_tree_count>` : Maximal count of weak trees for every cascade stage. The boosted classifier (stage) will have so many weak trees (<=maxWeakCount), as needed to achieve the given `-maxFalseAlarmRate`.
- Haar-like feature parameters:
- `-mode <BASIC (default) | CORE | ALL>` : Selects the type of Haar features set used in training. BASIC use only upright features, while ALL uses the full set of upright and 45 degree rotated feature set. See @cite Lienhart02 for more details.
- Local Binary Patterns parameters: Local Binary Patterns don't have parameters.
After the opencv_traincascade application has finished its work, the trained cascade will be saved in `cascade.xml` file in the `-data` folder. Other files in this folder are created for the case of interrupted training, so you may delete them after completion of training.
Training is finished and you can test your cascade classifier!
Visualising Cascade Classifiers
-------------------------------
From time to time it can be useful to visualise the trained cascade, to see which features it selected and how complex its stages are. For this OpenCV supplies a opencv_visualisation application. This application has the following commands:
- `--image` <b>(required)</b> : path to a reference image for your object model. This should be an annotation with dimensions [`-w`,`-h`] as passed to both opencv_createsamples and opencv_traincascade application.
- `--model` <b>(required)</b> : path to the trained model, which should be in the folder supplied to the `-data` parameter of the opencv_traincascade application.
- `--data` <i>(optional)</i> : if a data folder is supplied, which has to be manually created beforehand, stage output and a video of the features will be stored.
An example command can be seen below
@code{.text}
opencv_visualisation --image=/data/object.png --model=/data/model.xml --data=/data/result/
@endcode
Some limitations of the current visualisation tool
- Only handles cascade classifier models, trained with the opencv_traincascade tool, containing __stumps__ as decision trees [default settings].
- The image provided needs to be a sample window with the original model dimensions, passed to the `--image` parameter.
Example of the HAAR/LBP face model ran on a given window of Angelina Jolie, which had the same preprocessing as cascade classifier files -->24x24 pixel image, grayscale conversion and histogram equalisation:
_A video is made with for each stage each feature visualised:_
![](images/visualisation_video.png)
_Each stage is stored as an image for future validation of the features:_
![](images/visualisation_single_stage.png)
_This work was created for [OpenCV 3 Blueprints](https://www.packtpub.com/application-development/opencv-3-blueprints) by StevenPuttemans but Packt Publishing agreed integration into OpenCV._

@ -41,7 +41,6 @@
//M*/
#include "precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "distortion_model.hpp"
#include <stdio.h>
#include <iterator>
@ -146,7 +145,7 @@ void cv::Rodrigues(InputArray _src, OutputArray _dst, OutputArray _jacobian)
dst.setZero();
if( depth != CV_32F && depth != CV_64F )
CV_Error( CV_StsUnsupportedFormat, "The matrices must have 32f or 64f data type" );
CV_Error( cv::Error::StsUnsupportedFormat, "The matrices must have 32f or 64f data type" );
if( v2m )
{
@ -532,7 +531,7 @@ void cv::projectPoints( InputArray _objectPoints,
if(total % 3 != 0)
{
//we have stopped support of homogeneous coordinates because it cause ambiguity in interpretation of the input data
CV_Error( CV_StsBadArg, "Homogeneous coordinates are not supported" );
CV_Error( cv::Error::StsBadArg, "Homogeneous coordinates are not supported" );
}
count = total / 3;
CV_Assert(objpt_depth == CV_32F || objpt_depth == CV_64F);
@ -560,7 +559,7 @@ void cv::projectPoints( InputArray _objectPoints,
(rvec.size() == Size(3, 3) ||
(rvec.rows == 1 && rvec.cols*rvec.channels() == 3) ||
(rvec.rows == 3 && rvec.cols*rvec.channels() == 1)))) {
CV_Error(CV_StsBadArg, "rvec must be 3x3 or 1x3 or 3x1 floating-point array");
CV_Error(cv::Error::StsBadArg, "rvec must be 3x3 or 1x3 or 3x1 floating-point array");
}
if( rvec.size() == Size(3, 3) )
@ -582,7 +581,7 @@ void cv::projectPoints( InputArray _objectPoints,
if(!((tvec.depth() == CV_32F || tvec.depth() == CV_64F) &&
((tvec.rows == 1 && tvec.cols*tvec.channels() == 3) ||
(tvec.rows == 3 && tvec.cols*tvec.channels() == 1)))) {
CV_Error(CV_StsBadArg, "tvec must be 1x3 or 3x1 floating-point array");
CV_Error(cv::Error::StsBadArg, "tvec must be 1x3 or 3x1 floating-point array");
}
Mat _t(tvec.size(), CV_64FC(tvec.channels()), t);
@ -591,7 +590,7 @@ void cv::projectPoints( InputArray _objectPoints,
Mat cameraMatrix = _cameraMatrix.getMat();
if(cameraMatrix.size() != Size(3, 3) || cameraMatrix.channels() != 1)
CV_Error( CV_StsBadArg, "Intrinsic parameters must be 3x3 floating-point matrix" );
CV_Error( cv::Error::StsBadArg, "Intrinsic parameters must be 3x3 floating-point matrix" );
Mat _a(3, 3, CV_64F, a);
cameraMatrix.convertTo(_a, CV_64F);
@ -609,7 +608,7 @@ void cv::projectPoints( InputArray _objectPoints,
ktotal = (int)distCoeffs.total()*kcn;
if( (distCoeffs.rows != 1 && distCoeffs.cols != 1) ||
(ktotal != 4 && ktotal != 5 && ktotal != 8 && ktotal != 12 && ktotal != 14))
CV_Error( CV_StsBadArg, cvDistCoeffErr );
CV_Error( cv::Error::StsBadArg, cvDistCoeffErr );
Mat _k(distCoeffs.size(), CV_64FC(kcn), k);
distCoeffs.convertTo(_k, CV_64F);

@ -542,7 +542,7 @@ struct LevMarqDenseLinearBackend : public detail::LevMarqBackend
}
else
{
CV_Error(CV_StsBadArg, "Geodesic acceleration is disabled");
CV_Error(cv::Error::StsBadArg, "Geodesic acceleration is disabled");
}
}
else
@ -698,7 +698,7 @@ struct LevMarqDenseLinearBackend : public detail::LevMarqBackend
{
if (cb_alt)
{
CV_Error(CV_StsNotImplemented, "Geodesic acceleration is not implemented for normal callbacks, please use \"long\" callbacks");
CV_Error(cv::Error::StsNotImplemented, "Geodesic acceleration is not implemented for normal callbacks, please use \"long\" callbacks");
}
else
{
@ -744,9 +744,9 @@ LevMarq::LevMarq(int nvars, LongCallback callback, const Settings& settings, Inp
MatrixType matrixType, VariableType paramType, int nerrs, int solveMethod)
{
if (matrixType != MatrixType::AUTO && matrixType != MatrixType::DENSE)
CV_Error(CV_StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
if (paramType != VariableType::LINEAR)
CV_Error(CV_StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
auto backend = makePtr<LevMarqDenseLinearBackend>(nvars, callback, mask, nerrs, solveMethod);
pImpl = makePtr<LevMarq::Impl>(backend, settings);
@ -756,9 +756,9 @@ LevMarq::LevMarq(int nvars, NormalCallback callback, const Settings& settings, I
MatrixType matrixType, VariableType paramType, bool LtoR, int solveMethod)
{
if (matrixType != MatrixType::AUTO && matrixType != MatrixType::DENSE)
CV_Error(CV_StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
if (paramType != VariableType::LINEAR)
CV_Error(CV_StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
auto backend = makePtr<LevMarqDenseLinearBackend>(nvars, callback, mask, LtoR, solveMethod);
pImpl = makePtr<LevMarq::Impl>(backend, settings);
@ -768,9 +768,9 @@ LevMarq::LevMarq(InputOutputArray param, LongCallback callback, const Settings&
MatrixType matrixType, VariableType paramType, int nerrs, int solveMethod)
{
if (matrixType != MatrixType::AUTO && matrixType != MatrixType::DENSE)
CV_Error(CV_StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
if (paramType != VariableType::LINEAR)
CV_Error(CV_StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
auto backend = makePtr<LevMarqDenseLinearBackend>(param, callback, mask, nerrs, solveMethod);
pImpl = makePtr<LevMarq::Impl>(backend, settings);
@ -780,9 +780,9 @@ LevMarq::LevMarq(InputOutputArray param, NormalCallback callback, const Settings
MatrixType matrixType, VariableType paramType, bool LtoR, int solveMethod)
{
if (matrixType != MatrixType::AUTO && matrixType != MatrixType::DENSE)
CV_Error(CV_StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "General purpuse sparse solver for LevMarq is not implemented yet");
if (paramType != VariableType::LINEAR)
CV_Error(CV_StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
CV_Error(cv::Error::StsNotImplemented, "SO(3) and SE(3) params for LevMarq are not implemented yet");
auto backend = makePtr<LevMarqDenseLinearBackend>(param, callback, mask, LtoR, solveMethod);
pImpl = makePtr<LevMarq::Impl>(backend, settings);

@ -761,7 +761,7 @@ public:
{
if (geo && !useGeo)
{
CV_Error(CV_StsBadArg, "Geodesic acceleration is disabled");
CV_Error(cv::Error::StsBadArg, "Geodesic acceleration is disabled");
}
std::map<size_t, PoseGraphImpl::Node>& nodes = geo ? geoNodes : tempNodes;

@ -1027,7 +1027,7 @@ int solvePnPGeneric( InputArray _opoints, InputArray _ipoints,
vec_tvecs.push_back(tvec);
}*/
else
CV_Error(CV_StsBadArg, "The flags argument must be one of SOLVEPNP_ITERATIVE, SOLVEPNP_P3P, "
CV_Error(cv::Error::StsBadArg, "The flags argument must be one of SOLVEPNP_ITERATIVE, SOLVEPNP_P3P, "
"SOLVEPNP_EPNP, SOLVEPNP_DLS, SOLVEPNP_UPNP, SOLVEPNP_AP3P, SOLVEPNP_IPPE, SOLVEPNP_IPPE_SQUARE or SOLVEPNP_SQPNP");
CV_Assert(vec_rvecs.size() == vec_tvecs.size());

@ -173,9 +173,9 @@ void correctMatches( InputArray _F, InputArray _points1, InputArray _points2,
CV_Assert(points1.size() == points2.size());
CV_Assert(points1.rows == 1 || points1.cols == 1);
if (points1.channels() != 2)
CV_Error( CV_StsUnmatchedSizes, "The first set of points must contain two channels; one for x and one for y" );
CV_Error( cv::Error::StsUnmatchedSizes, "The first set of points must contain two channels; one for x and one for y" );
if (points2.channels() != 2)
CV_Error( CV_StsUnmatchedSizes, "The second set of points must contain two channels; one for x and one for y" );
CV_Error( cv::Error::StsUnmatchedSizes, "The second set of points must contain two channels; one for x and one for y" );
_newPoints1.create(points1.size(), points1.type());
_newPoints2.create(points2.size(), points2.type());

@ -44,6 +44,8 @@
namespace cvtest {
using namespace cv;
static int cvTsRodrigues( const CvMat* src, CvMat* dst, CvMat* jacobian )
{
int depth;
@ -223,7 +225,7 @@ static int cvTsRodrigues( const CvMat* src, CvMat* dst, CvMat* jacobian )
cvMulTransposed( &matR, &matA, 0 );
cvSetIdentity( &matI );
if( cvNorm( &matA, &matI, CV_C ) > 1e-3 ||
if( cvNorm( &matA, &matI, NORM_INF ) > 1e-3 ||
fabs( cvDet(&matR) - 1 ) > 1e-3 )
return 0;
@ -717,7 +719,7 @@ void CV_RodriguesTest::prepare_to_validation( int /*test_case_idx*/ )
cvtest::Rodrigues( m, vec2, m2v_jac );
cvtest::copy( vec, vec2 );
theta0 = cvtest::norm( vec2, CV_L2 );
theta0 = cvtest::norm( vec2, NORM_L2 );
theta1 = fmod( theta0, CV_PI*2 );
if( theta1 > CV_PI )
@ -727,7 +729,7 @@ void CV_RodriguesTest::prepare_to_validation( int /*test_case_idx*/ )
if( calc_jacobians )
{
//cvInvert( v2m_jac, m2v_jac, CV_SVD );
double nrm = cvtest::norm(test_mat[REF_OUTPUT][3], CV_C);
double nrm = cvtest::norm(test_mat[REF_OUTPUT][3], NORM_INF);
if( FLT_EPSILON < nrm && nrm < 1000 )
{
gemm( test_mat[OUTPUT][1], test_mat[OUTPUT][3],

@ -41,7 +41,7 @@
//M*/
#include "test_precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/core/core_c.h"
namespace opencv_test { namespace {

@ -106,15 +106,15 @@ void CV_UndistortPointsBadArgTest::run(int)
src_points = cv::cvarrToMat(&_src_points_orig);
src_points.create(2, 2, CV_32FC2);
errcount += run_test_case( CV_StsAssert, "Invalid input data matrix size" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid input data matrix size" );
src_points = cv::cvarrToMat(&_src_points_orig);
src_points.create(1, 4, CV_64FC2);
errcount += run_test_case( CV_StsAssert, "Invalid input data matrix type" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid input data matrix type" );
src_points = cv::cvarrToMat(&_src_points_orig);
src_points = cv::Mat();
errcount += run_test_case( CV_StsBadArg, "Input data matrix is not continuous" );
errcount += run_test_case( cv::Error::StsBadArg, "Input data matrix is not continuous" );
src_points = cv::cvarrToMat(&_src_points_orig);
//------------
@ -181,19 +181,19 @@ void CV_InitUndistortRectifyMapBadArgTest::run(int)
mapy = cv::cvarrToMat(&_mapy_orig);
mat_type = CV_64F;
errcount += run_test_case( CV_StsAssert, "Invalid map matrix type" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid map matrix type" );
mat_type = mat_type_orig;
camera_mat.create(3, 2, CV_32F);
errcount += run_test_case( CV_StsAssert, "Invalid camera data matrix size" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid camera data matrix size" );
camera_mat = cv::cvarrToMat(&_camera_mat_orig);
R.create(4, 3, CV_32F);
errcount += run_test_case( CV_StsAssert, "Invalid R data matrix size" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid R data matrix size" );
R = cv::cvarrToMat(&_R_orig);
distortion_coeffs.create(6, 1, CV_32F);
errcount += run_test_case( CV_StsAssert, "Invalid distortion coefficients data matrix size" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid distortion coefficients data matrix size" );
distortion_coeffs = cv::cvarrToMat(&_distortion_coeffs_orig);
//------------
@ -256,7 +256,7 @@ void CV_UndistortBadArgTest::run(int)
dst = cv::cvarrToMat(&_dst_orig);
camera_mat.create(5, 5, CV_64F);
errcount += run_test_case( CV_StsAssert, "Invalid camera data matrix size" );
errcount += run_test_case( cv::Error::StsAssert, "Invalid camera data matrix size" );
//------------
ts->set_failed_test_info(errcount > 0 ? cvtest::TS::FAIL_BAD_ARG_CHECK : cvtest::TS::OK);

@ -71,7 +71,6 @@
#include "precomp.hpp"
#include "circlesgrid.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/flann.hpp"
#include <stack>

@ -70,7 +70,7 @@ static void initIntrinsicParams2D( const Mat& objectPoints,
imagePoints.type() == CV_64FC2 );
if( objectPoints.rows != 1 || imagePoints.rows != 1 )
CV_Error( CV_StsBadSize, "object points and image points must be a single-row matrices" );
CV_Error( cv::Error::StsBadSize, "object points and image points must be a single-row matrices" );
Mat_<double> matA(2*nimages, 2);
Mat_<double> matb(2*nimages, 1, CV_64F );
@ -177,20 +177,20 @@ static double calibrateCameraInternal( const Mat& objectPoints,
// 0. check the parameters & allocate buffers
if( imageSize.width <= 0 || imageSize.height <= 0 )
CV_Error( CV_StsOutOfRange, "image width and height must be positive" );
CV_Error( cv::Error::StsOutOfRange, "image width and height must be positive" );
if(flags & CALIB_TILTED_MODEL)
{
//when the tilted sensor model is used the distortion coefficients matrix must have 14 parameters
if (ndistCoeffs != 14)
CV_Error( CV_StsBadArg, "The tilted sensor model must have 14 parameters in the distortion matrix" );
CV_Error( cv::Error::StsBadArg, "The tilted sensor model must have 14 parameters in the distortion matrix" );
}
else
{
//when the thin prism model is used the distortion coefficients matrix must have 12 parameters
if(flags & CALIB_THIN_PRISM_MODEL)
if (ndistCoeffs != 12)
CV_Error( CV_StsBadArg, "Thin prism model must have 12 parameters in the distortion matrix" );
CV_Error( cv::Error::StsBadArg, "Thin prism model must have 12 parameters in the distortion matrix" );
}
if( !rvecs.empty() )
@ -225,7 +225,7 @@ static double calibrateCameraInternal( const Mat& objectPoints,
int ni = npoints.at<int>(i);
if( ni < 4 )
{
CV_Error_( CV_StsOutOfRange, ("The number of points in the view #%d is < 4", i));
CV_Error_( cv::Error::StsOutOfRange, ("The number of points in the view #%d is < 4", i));
}
maxPoints = MAX( maxPoints, ni );
total += ni;
@ -286,15 +286,15 @@ static double calibrateCameraInternal( const Mat& objectPoints,
if( flags & CALIB_USE_INTRINSIC_GUESS )
{
if( A(0, 0) <= 0 || A(1, 1) <= 0 )
CV_Error( CV_StsOutOfRange, "Focal length (fx and fy) must be positive" );
CV_Error( cv::Error::StsOutOfRange, "Focal length (fx and fy) must be positive" );
if( A(0, 2) < 0 || A(0, 2) >= imageSize.width ||
A(1, 2) < 0 || A(1, 2) >= imageSize.height )
CV_Error( CV_StsOutOfRange, "Principal point must be within the image" );
CV_Error( cv::Error::StsOutOfRange, "Principal point must be within the image" );
if( fabs(A(0, 1)) > 1e-5 )
CV_Error( CV_StsOutOfRange, "Non-zero skew is not supported by the function" );
CV_Error( cv::Error::StsOutOfRange, "Non-zero skew is not supported by the function" );
if( fabs(A(1, 0)) > 1e-5 || fabs(A(2, 0)) > 1e-5 ||
fabs(A(2, 1)) > 1e-5 || fabs(A(2,2)-1) > 1e-5 )
CV_Error( CV_StsOutOfRange,
CV_Error( cv::Error::StsOutOfRange,
"The intrinsic matrix must have [fx 0 cx; 0 fy cy; 0 0 1] shape" );
A(0, 1) = A(1, 0) = A(2, 0) = A(2, 1) = 0.;
A(2, 2) = 1.;
@ -304,7 +304,7 @@ static double calibrateCameraInternal( const Mat& objectPoints,
aspectRatio = A(0, 0)/A(1, 1);
if( aspectRatio < minValidAspectRatio || aspectRatio > maxValidAspectRatio )
CV_Error( CV_StsOutOfRange,
CV_Error( cv::Error::StsOutOfRange,
"The specified aspect ratio (= cameraMatrix[0][0] / cameraMatrix[1][1]) is incorrect" );
}
distCoeffs.convertTo(_k, CV_64F);
@ -314,7 +314,7 @@ static double calibrateCameraInternal( const Mat& objectPoints,
Scalar mean, sdv;
meanStdDev(matM, mean, sdv);
if( fabs(mean[2]) > 1e-5 || fabs(sdv[2]) > 1e-5 )
CV_Error( CV_StsBadArg,
CV_Error( cv::Error::StsBadArg,
"For non-planar calibration rigs the initial intrinsic matrix must be specified" );
for(int i = 0; i < total; i++ )
matM.at<Point3d>(i).z = 0.;
@ -324,7 +324,7 @@ static double calibrateCameraInternal( const Mat& objectPoints,
aspectRatio = A(0, 0);
aspectRatio /= A(1, 1);
if( aspectRatio < minValidAspectRatio || aspectRatio > maxValidAspectRatio )
CV_Error( CV_StsOutOfRange,
CV_Error( cv::Error::StsOutOfRange,
"The specified aspect ratio (= cameraMatrix[0][0] / cameraMatrix[1][1]) is incorrect" );
}
initIntrinsicParams2D( matM, _m, npoints, imageSize, A, aspectRatio );
@ -689,7 +689,7 @@ static double stereoCalibrateImpl(
if( (depth != CV_32F && depth != CV_64F) ||
((rvecs.rows != nimages || (rvecs.cols*cn != 3 && rvecs.cols*cn != 9)) &&
(rvecs.rows != 1 || rvecs.cols != nimages || cn != 3)) )
CV_Error( CV_StsBadArg, "the output array of rotation vectors must be 3-channel "
CV_Error( cv::Error::StsBadArg, "the output array of rotation vectors must be 3-channel "
"1xn or nx1 array or 1-channel nx3 or nx9 array, where n is the number of views" );
}
if( !tvecs.empty() )
@ -699,7 +699,7 @@ static double stereoCalibrateImpl(
if( (depth != CV_32F && depth != CV_64F) ||
((tvecs.rows != nimages || tvecs.cols*cn != 3) &&
(tvecs.rows != 1 || tvecs.cols != nimages || cn != 3)) )
CV_Error( CV_StsBadArg, "the output array of translation vectors must be 3-channel "
CV_Error( cv::Error::StsBadArg, "the output array of translation vectors must be 3-channel "
"1xn or nx1 array or 1-channel nx3 array, where n is the number of views" );
}
@ -1237,7 +1237,7 @@ static double registerCamerasImpl(
CV_Assert(depth == CV_32F || depth == CV_64F);
if(((rvecs.rows != nimages || (rvecs.cols*cn != 3 && rvecs.cols*cn != 9)) &&
(rvecs.rows != 1 || rvecs.cols != nimages || cn != 3)) )
CV_Error( CV_StsBadArg, "the output array of rotation vectors must be 3-channel "
CV_Error( cv::Error::StsBadArg, "the output array of rotation vectors must be 3-channel "
"1xn or nx1 array or 1-channel nx3 or nx9 array, where n is the number of views" );
}
if( !tvecs.empty() )
@ -1247,7 +1247,7 @@ static double registerCamerasImpl(
CV_Assert(depth == CV_32F || depth == CV_64F);
if(((tvecs.rows != nimages || tvecs.cols*cn != 3) &&
(tvecs.rows != 1 || tvecs.cols != nimages || cn != 3)) )
CV_Error( CV_StsBadArg, "the output array of translation vectors must be 3-channel "
CV_Error( cv::Error::StsBadArg, "the output array of translation vectors must be 3-channel "
"1xn or nx1 array or 1-channel nx3 array, where n is the number of views" );
}
@ -1308,7 +1308,7 @@ static double registerCamerasImpl(
else if (cameraModels[k] == CALIB_MODEL_FISHEYE)
fisheye::solvePnP(objpt_i, imgpt_ik, A[k], tdists[k], rv, T[k], false, SOLVEPNP_ITERATIVE );
else
CV_Error(CV_StsBadArg, cv::format("Camera type %d is not supported", cameraModels[k]));
CV_Error(cv::Error::StsBadArg, cv::format("Camera type %d is not supported", cameraModels[k]));
Rodrigues(rv, R[k]);
@ -1596,17 +1596,17 @@ static void collectCalibrationData( InputArrayOfArrays objectPoints,
{
Mat objectPoint = objectPoints.getMat(i);
if (objectPoint.empty())
CV_Error(CV_StsBadSize, "objectPoints should not contain empty vector of vectors of points");
CV_Error(cv::Error::StsBadSize, "objectPoints should not contain empty vector of vectors of points");
int numberOfObjectPoints = objectPoint.checkVector(3, CV_32F);
if (numberOfObjectPoints <= 0)
CV_Error(CV_StsUnsupportedFormat, "objectPoints should contain vector of vectors of points of type Point3f");
CV_Error(cv::Error::StsUnsupportedFormat, "objectPoints should contain vector of vectors of points of type Point3f");
Mat imagePoint1 = imagePoints1.getMat(i);
if (imagePoint1.empty())
CV_Error(CV_StsBadSize, "imagePoints1 should not contain empty vector of vectors of points");
CV_Error(cv::Error::StsBadSize, "imagePoints1 should not contain empty vector of vectors of points");
int numberOfImagePoints = imagePoint1.checkVector(2, CV_32F);
if (numberOfImagePoints <= 0)
CV_Error(CV_StsUnsupportedFormat, "imagePoints1 should contain vector of vectors of points of type Point2f");
CV_Error(cv::Error::StsUnsupportedFormat, "imagePoints1 should contain vector of vectors of points of type Point2f");
CV_CheckEQ(numberOfObjectPoints, numberOfImagePoints, "Number of object and image points must be equal");
total += numberOfObjectPoints;
@ -1664,14 +1664,14 @@ static void collectCalibrationData( InputArrayOfArrays objectPoints,
{
if( nPointsMat.at<int>(i) != ni )
{
CV_Error( CV_StsBadArg, "All objectPoints[i].size() should be equal when "
CV_Error( cv::Error::StsBadArg, "All objectPoints[i].size() should be equal when "
"object-releasing method is requested." );
}
Mat ocmp = objPtMat.colRange(ni * i, ni * i + ni) != objPtMat.colRange(0, ni);
ocmp = ocmp.reshape(1);
if( countNonZero(ocmp) )
{
CV_Error( CV_StsBadArg, "All objectPoints[i] should be identical when object-releasing"
CV_Error( cv::Error::StsBadArg, "All objectPoints[i] should be identical when object-releasing"
" method is requested." );
}
}
@ -1914,7 +1914,7 @@ void calibrationMatrixValues( InputArray _cameraMatrix, Size imageSize,
CV_INSTRUMENT_REGION();
if(_cameraMatrix.size() != Size(3, 3))
CV_Error(CV_StsUnmatchedSizes, "Size of cameraMatrix must be 3x3!");
CV_Error(cv::Error::StsUnmatchedSizes, "Size of cameraMatrix must be 3x3!");
Matx33d A;
_cameraMatrix.getMat().convertTo(A, CV_64F);

@ -212,7 +212,7 @@ void CV_ProjectPointsTest::prepare_to_validation( int /*test_case_idx*/ )
cvTsProjectPoints( m, vec2, m2v_jac );
cvTsCopy( vec, vec2 );
theta0 = cvtest::norm( cvarrtomat(vec2), 0, CV_L2 );
theta0 = cvtest::norm( cvarrtomat(vec2), 0, NORM_L2 );
theta1 = fmod( theta0, CV_PI*2 );
if( theta1 > CV_PI )
@ -222,7 +222,7 @@ void CV_ProjectPointsTest::prepare_to_validation( int /*test_case_idx*/ )
if( calc_jacobians )
{
//cvInvert( v2m_jac, m2v_jac, CV_SVD );
if( cvtest::norm(cvarrtomat(&test_mat[OUTPUT][3]), 0, CV_C) < 1000 )
if( cvtest::norm(cvarrtomat(&test_mat[OUTPUT][3]), 0, NORM_INF) < 1000 )
{
cvTsGEMM( &test_mat[OUTPUT][1], &test_mat[OUTPUT][3],
1, 0, 0, &test_mat[OUTPUT][4],

@ -149,49 +149,49 @@ void CV_CameraCalibrationBadArgTest::run( int /* start_from */ )
caller.initArgs();
caller.objPts_arg = noArray();
errors += run_test_case( CV_StsBadArg, "None passed in objPts", caller);
errors += run_test_case( cv::Error::StsBadArg, "None passed in objPts", caller);
caller.initArgs();
caller.imgPts_arg = noArray();
errors += run_test_case( CV_StsBadArg, "None passed in imgPts", caller );
errors += run_test_case( cv::Error::StsBadArg, "None passed in imgPts", caller );
caller.initArgs();
caller.cameraMatrix_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero passed in cameraMatrix", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero passed in cameraMatrix", caller );
caller.initArgs();
caller.distCoeffs_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero passed in distCoeffs", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero passed in distCoeffs", caller );
caller.initArgs();
caller.imageSize.width = -1;
errors += run_test_case( CV_StsOutOfRange, "Bad image width", caller );
errors += run_test_case( cv::Error::StsOutOfRange, "Bad image width", caller );
caller.initArgs();
caller.imageSize.height = -1;
errors += run_test_case( CV_StsOutOfRange, "Bad image height", caller );
errors += run_test_case( cv::Error::StsOutOfRange, "Bad image height", caller );
caller.initArgs();
caller.imgPts[0].clear();
errors += run_test_case( CV_StsBadSize, "Bad imgpts[0]", caller );
errors += run_test_case( cv::Error::StsBadSize, "Bad imgpts[0]", caller );
caller.imgPts[0] = caller.imgPts[1];
caller.initArgs();
caller.objPts[1].clear();
errors += run_test_case( CV_StsBadSize, "Bad objpts[1]", caller );
errors += run_test_case( cv::Error::StsBadSize, "Bad objpts[1]", caller );
caller.objPts[1] = caller.objPts[0];
caller.initArgs();
Mat badCM = Mat::zeros(4, 4, CV_64F);
caller.cameraMatrix_arg = badCM;
caller.flags = CALIB_USE_INTRINSIC_GUESS;
errors += run_test_case( CV_StsBadArg, "Bad camearaMatrix header", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad camearaMatrix header", caller );
caller.initArgs();
Mat badDC = Mat::zeros(10, 10, CV_64F);
caller.distCoeffs_arg = badDC;
caller.flags = CALIB_USE_INTRINSIC_GUESS;
errors += run_test_case( CV_StsBadArg, "Bad camearaMatrix header", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad camearaMatrix header", caller );
if (errors)
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
@ -242,15 +242,15 @@ protected:
caller.initArgs();
caller.src_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Src is empty matrix", caller );
errors += run_test_case( cv::Error::StsBadArg, "Src is empty matrix", caller );
caller.initArgs();
caller.src = Mat::zeros(3, 1, CV_8U);
errors += run_test_case( CV_StsUnsupportedFormat, "Bad src formart", caller );
errors += run_test_case( cv::Error::StsUnsupportedFormat, "Bad src formart", caller );
caller.initArgs();
caller.src = Mat::zeros(1, 1, CV_32F);
errors += run_test_case( CV_StsBadSize, "Bad src size", caller );
errors += run_test_case( cv::Error::StsBadSize, "Bad src size", caller );
if (errors)
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
@ -329,57 +329,57 @@ protected:
caller.initArgs();
caller.objectPoints_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero objectPoints", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero objectPoints", caller );
caller.initArgs();
caller.rvec_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero r_vec", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero r_vec", caller );
caller.initArgs();
caller.tvec_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero t_vec", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero t_vec", caller );
caller.initArgs();
caller.A_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero camMat", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero camMat", caller );
caller.initArgs();
caller.imagePoints_arg = noArray();
errors += run_test_case( CV_StsBadArg, "Zero imagePoints", caller );
errors += run_test_case( cv::Error::StsBadArg, "Zero imagePoints", caller );
Mat save_rvec = caller.r_vec;
caller.initArgs();
caller.r_vec.create(2, 2, CV_32F);
errors += run_test_case( CV_StsBadArg, "Bad rvec format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad rvec format", caller );
caller.initArgs();
caller.r_vec.create(1, 3, CV_8U);
errors += run_test_case( CV_StsBadArg, "Bad rvec format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad rvec format", caller );
caller.r_vec = save_rvec;
/****************************/
Mat save_tvec = caller.t_vec;
caller.initArgs();
caller.t_vec.create(3, 3, CV_32F);
errors += run_test_case( CV_StsBadArg, "Bad tvec format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad tvec format", caller );
caller.initArgs();
caller.t_vec.create(1, 3, CV_8U);
errors += run_test_case( CV_StsBadArg, "Bad tvec format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad tvec format", caller );
caller.t_vec = save_tvec;
/****************************/
Mat save_A = caller.A;
caller.initArgs();
caller.A.create(2, 2, CV_32F);
errors += run_test_case( CV_StsBadArg, "Bad A format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad A format", caller );
caller.A = save_A;
/****************************/
Mat save_DC = caller.distCoeffs;
caller.initArgs();
caller.distCoeffs.create(3, 3, CV_32F);
errors += run_test_case( CV_StsBadArg, "Bad distCoeffs format", caller );
errors += run_test_case( cv::Error::StsBadArg, "Bad distCoeffs format", caller );
caller.distCoeffs = save_DC;
if (errors)

@ -40,7 +40,6 @@
//M*/
#include "test_precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "test_chessboardgenerator.hpp"
namespace opencv_test { namespace {

@ -134,13 +134,6 @@ static inline int cvAlign( int size, int align )
return (size + align - 1) & -align;
}
#ifdef IPL_DEPTH_8U
static inline cv::Size cvGetMatSize( const CvMat* mat )
{
return cv::Size(mat->cols, mat->rows);
}
#endif
namespace cv
{
CV_EXPORTS void scalarToRawData(const cv::Scalar& s, void* buf, int type, int unroll_to = 0);

@ -975,7 +975,7 @@ OCL_PERF_TEST_P(InRangeFixture, InRange,
///////////// Normalize ////////////////////////
CV_ENUM(NormalizeModes, CV_MINMAX, CV_L2, CV_L1, CV_C)
CV_ENUM(NormalizeModes, NORM_MINMAX, NORM_L2, NORM_L1, NORM_INF)
typedef tuple<Size, MatType, NormalizeModes> NormalizeParams;
typedef TestBaseWithParam<NormalizeParams> NormalizeFixture;
@ -995,7 +995,7 @@ OCL_PERF_TEST_P(NormalizeFixture, Normalize,
OCL_TEST_CYCLE() cv::normalize(src, dst, 10, 110, mode);
SANITY_CHECK(dst, 5e-2);
SANITY_CHECK_NOTHING();
}
OCL_PERF_TEST_P(NormalizeFixture, NormalizeWithMask,
@ -1013,7 +1013,7 @@ OCL_PERF_TEST_P(NormalizeFixture, NormalizeWithMask,
OCL_TEST_CYCLE() cv::normalize(src, dst, 10, 110, mode, -1, mask);
SANITY_CHECK(dst, 5e-2);
SANITY_CHECK_NOTHING();
}
///////////// ConvertScaleAbs ////////////////////////
@ -1232,7 +1232,7 @@ OCL_PERF_TEST_P(PSNRFixture, PSNR,
///////////// Reduce ////////////////////////
CV_ENUM(ReduceMinMaxOp, CV_REDUCE_MIN, CV_REDUCE_MAX)
CV_ENUM(ReduceMinMaxOp, REDUCE_MIN, REDUCE_MAX)
typedef tuple<Size, std::pair<MatType, MatType>, int, ReduceMinMaxOp> ReduceMinMaxParams;
typedef TestBaseWithParam<ReduceMinMaxParams> ReduceMinMaxFixture;
@ -1250,7 +1250,6 @@ OCL_PERF_TEST_P(ReduceMinMaxFixture, Reduce,
dim = get<2>(params), op = get<3>(params);
const Size srcSize = get<0>(params),
dstSize(dim == 0 ? srcSize.width : 1, dim == 0 ? 1 : srcSize.height);
const double eps = CV_MAT_DEPTH(dtype) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, stype);
checkDeviceMaxMemoryAllocSize(srcSize, dtype);
@ -1260,7 +1259,7 @@ OCL_PERF_TEST_P(ReduceMinMaxFixture, Reduce,
OCL_TEST_CYCLE() cv::reduce(src, dst, dim, op, dtype);
SANITY_CHECK(dst, eps);
SANITY_CHECK_NOTHING();
}
CV_ENUM(ReduceAccOp, REDUCE_SUM, REDUCE_AVG, REDUCE_SUM2)

@ -70,7 +70,7 @@ namespace cv {
static void* OutOfMemoryError(size_t size)
{
CV_Error_(CV_StsNoMem, ("Failed to allocate %llu bytes", (unsigned long long)size));
CV_Error_(cv::Error::StsNoMem, ("Failed to allocate %llu bytes", (unsigned long long)size));
}
CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics();

@ -209,7 +209,7 @@ static void binary_op( InputArray _src1, InputArray _src2, OutputArray _dst,
swap(sz1, sz2);
}
else if( !checkScalar(*psrc2, type1, kind2, kind1) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The operation is neither 'array op array' (where arrays have the same size and type), "
"nor 'array op scalar', nor 'scalar op array'" );
haveScalar = true;
@ -673,7 +673,7 @@ static void arithm_op(InputArray _src1, InputArray _src2, OutputArray _dst,
oclop = OCL_OP_RDIV_SCALE;
}
else if( !checkScalar(*psrc2, type1, kind2, kind1) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The operation is neither 'array op array' "
"(where arrays have the same size and the same number of channels), "
"nor 'array op scalar', nor 'scalar op array'" );
@ -698,7 +698,7 @@ static void arithm_op(InputArray _src1, InputArray _src2, OutputArray _dst,
else
{
if( !haveScalar && type1 != type2 )
CV_Error(CV_StsBadArg,
CV_Error(cv::Error::StsBadArg,
"When the input arrays in add/subtract/multiply/divide functions have different types, "
"the output array type must be explicitly specified");
dtype = type1;
@ -1289,7 +1289,7 @@ void cv::compare(InputArray _src1, InputArray _src2, OutputArray _dst, int op)
return;
}
else if(is_src1_scalar == is_src2_scalar)
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The operation is neither 'array op array' (where arrays have the same size and the same type), "
"nor 'array op scalar', nor 'scalar op array'" );
haveScalar = true;
@ -1791,7 +1791,7 @@ static bool ocl_inRange( InputArray _src, InputArray _lowerb,
ssize != lsize || stype != ltype )
{
if( !checkScalar(_lowerb, stype, lkind, skind) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The lower boundary is neither an array of the same size and same type as src, nor a scalar");
lbScalar = true;
}
@ -1800,7 +1800,7 @@ static bool ocl_inRange( InputArray _src, InputArray _lowerb,
ssize != usize || stype != utype )
{
if( !checkScalar(_upperb, stype, ukind, skind) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The upper boundary is neither an array of the same size and same type as src, nor a scalar");
ubScalar = true;
}
@ -1914,7 +1914,7 @@ void cv::inRange(InputArray _src, InputArray _lowerb,
src.size != lb.size || src.type() != lb.type() )
{
if( !checkScalar(lb, src.type(), lkind, skind) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The lower boundary is neither an array of the same size and same type as src, nor a scalar");
lbScalar = true;
}
@ -1923,7 +1923,7 @@ void cv::inRange(InputArray _src, InputArray _lowerb,
src.size != ub.size || src.type() != ub.type() )
{
if( !checkScalar(ub, src.type(), ukind, skind) )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"The upper boundary is neither an array of the same size and same type as src, nor a scalar");
ubScalar = true;
}

@ -79,7 +79,7 @@ cvSetIPLAllocators( Cv_iplCreateImageHeader createHeader,
(createROI != 0) + (cloneImage != 0);
if( count != 0 && count != 5 )
CV_Error( CV_StsBadArg, "Either all the pointers should be null or "
CV_Error( cv::Error::StsBadArg, "Either all the pointers should be null or "
"they all should be non-null" );
CvIPL.createHeader = createHeader;
@ -118,11 +118,11 @@ cvCreateMatHeader( int rows, int cols, int type )
type = CV_MAT_TYPE(type);
if( rows < 0 || cols < 0 )
CV_Error( CV_StsBadSize, "Non-positive width or height" );
CV_Error( cv::Error::StsBadSize, "Non-positive width or height" );
int min_step = CV_ELEM_SIZE(type);
if( min_step <= 0 )
CV_Error( CV_StsUnsupportedFormat, "Invalid matrix type" );
CV_Error( cv::Error::StsUnsupportedFormat, "Invalid matrix type" );
min_step *= cols;
CvMat* arr = (CvMat*)cvAlloc( sizeof(*arr));
@ -146,13 +146,13 @@ cvInitMatHeader( CvMat* arr, int rows, int cols,
int type, void* data, int step )
{
if( !arr )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( (unsigned)CV_MAT_DEPTH(type) > CV_DEPTH_MAX )
CV_Error( CV_BadNumChannels, "" );
CV_Error( cv::Error::BadNumChannels, "" );
if( rows < 0 || cols < 0 )
CV_Error( CV_StsBadSize, "Non-positive cols or rows" );
CV_Error( cv::Error::StsBadSize, "Non-positive cols or rows" );
type = CV_MAT_TYPE( type );
arr->type = type | CV_MAT_MAGIC_VAL;
@ -168,7 +168,7 @@ cvInitMatHeader( CvMat* arr, int rows, int cols,
if( step != CV_AUTOSTEP && step != 0 )
{
if( step < min_step )
CV_Error( CV_BadStep, "" );
CV_Error( cv::Error::BadStep, "" );
arr->step = step;
}
else
@ -196,7 +196,7 @@ cvReleaseMat( CvMat** array )
CvMat* arr = *array;
if( !CV_IS_MAT_HDR_Z(arr) && !CV_IS_MATND_HDR(arr) )
CV_Error( CV_StsBadFlag, "" );
CV_Error( cv::Error::StsBadFlag, "" );
*array = 0;
@ -211,7 +211,7 @@ CV_IMPL CvMat*
cvCloneMat( const CvMat* src )
{
if( !CV_IS_MAT_HDR( src ))
CV_Error( CV_StsBadArg, "Bad CvMat header" );
CV_Error( cv::Error::StsBadArg, "Bad CvMat header" );
CvMat* dst = cvCreateMatHeader( src->rows, src->cols, src->type );
@ -237,25 +237,25 @@ cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
int64 esz = CV_ELEM_SIZE(type), step = esz;
if( !mat )
CV_Error( CV_StsNullPtr, "NULL matrix header pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL matrix header pointer" );
if( step == 0 )
CV_Error( CV_StsUnsupportedFormat, "invalid array data type" );
CV_Error( cv::Error::StsUnsupportedFormat, "invalid array data type" );
if( !sizes )
CV_Error( CV_StsNullPtr, "NULL <sizes> pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL <sizes> pointer" );
if( dims <= 0 || dims > CV_MAX_DIM )
CV_Error( CV_StsOutOfRange,
CV_Error( cv::Error::StsOutOfRange,
"non-positive or too large number of dimensions" );
for( int i = dims - 1; i >= 0; i-- )
{
if( sizes[i] < 0 )
CV_Error( CV_StsBadSize, "one of dimension sizes is non-positive" );
CV_Error( cv::Error::StsBadSize, "one of dimension sizes is non-positive" );
mat->dim[i].size = sizes[i];
if( step > INT_MAX )
CV_Error( CV_StsOutOfRange, "The array is too big" );
CV_Error( cv::Error::StsOutOfRange, "The array is too big" );
mat->dim[i].step = (int)step;
step *= sizes[i];
}
@ -292,7 +292,7 @@ CV_IMPL CvMatND*
cvCreateMatNDHeader( int dims, const int* sizes, int type )
{
if( dims <= 0 || dims > CV_MAX_DIM )
CV_Error( CV_StsOutOfRange,
CV_Error( cv::Error::StsOutOfRange,
"non-positive or too large number of dimensions" );
CvMatND* arr = (CvMatND*)cvAlloc( sizeof(*arr) );
@ -308,7 +308,7 @@ CV_IMPL CvMatND*
cvCloneMatND( const CvMatND* src )
{
if( !CV_IS_MATND_HDR( src ))
CV_Error( CV_StsBadArg, "Bad CvMatND header" );
CV_Error( cv::Error::StsBadArg, "Bad CvMatND header" );
CV_Assert( src->dims <= CV_MAX_DIM );
int sizes[CV_MAX_DIM];
@ -349,18 +349,18 @@ cvCreateSparseMat( int dims, const int* sizes, int type )
CvMemStorage* storage;
if( pix_size == 0 )
CV_Error( CV_StsUnsupportedFormat, "invalid array data type" );
CV_Error( cv::Error::StsUnsupportedFormat, "invalid array data type" );
if( dims <= 0 || dims > CV_MAX_DIM )
CV_Error( CV_StsOutOfRange, "bad number of dimensions" );
CV_Error( cv::Error::StsOutOfRange, "bad number of dimensions" );
if( !sizes )
CV_Error( CV_StsNullPtr, "NULL <sizes> pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL <sizes> pointer" );
for( i = 0; i < dims; i++ )
{
if( sizes[i] <= 0 )
CV_Error( CV_StsBadSize, "one of dimension sizes is non-positive" );
CV_Error( cv::Error::StsBadSize, "one of dimension sizes is non-positive" );
}
CvSparseMat* arr = (CvSparseMat*)cvAlloc(sizeof(*arr)+MAX(0,dims-CV_MAX_DIM)*sizeof(arr->size[0]));
@ -400,7 +400,7 @@ cvReleaseSparseMat( CvSparseMat** array )
CvSparseMat* arr = *array;
if( !CV_IS_SPARSE_MAT_HDR(arr) )
CV_Error( CV_StsBadFlag, "" );
CV_Error( cv::Error::StsBadFlag, "" );
*array = 0;
@ -417,7 +417,7 @@ CV_IMPL CvSparseMat*
cvCloneSparseMat( const CvSparseMat* src )
{
if( !CV_IS_SPARSE_MAT_HDR(src) )
CV_Error( CV_StsBadArg, "Invalid sparse array header" );
CV_Error( cv::Error::StsBadArg, "Invalid sparse array header" );
CvSparseMat* dst = cvCreateSparseMat( src->dims, src->size, src->type );
cvCopy( src, dst );
@ -432,10 +432,10 @@ cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* iterator )
int idx;
if( !CV_IS_SPARSE_MAT( mat ))
CV_Error( CV_StsBadArg, "Invalid sparse matrix header" );
CV_Error( cv::Error::StsBadArg, "Invalid sparse matrix header" );
if( !iterator )
CV_Error( CV_StsNullPtr, "NULL iterator pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL iterator pointer" );
iterator->mat = (CvSparseMat*)mat;
iterator->node = 0;
@ -469,7 +469,7 @@ icvGetNodePtr( CvSparseMat* mat, const int* idx, int* _type,
{
int t = idx[i];
if( (unsigned)t >= (unsigned)mat->size[i] )
CV_Error( CV_StsOutOfRange, "One of indices is out of range" );
CV_Error( cv::Error::StsOutOfRange, "One of indices is out of range" );
hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t;
}
}
@ -563,7 +563,7 @@ icvDeleteNode( CvSparseMat* mat, const int* idx, unsigned* precalc_hashval )
{
int t = idx[i];
if( (unsigned)t >= (unsigned)mat->size[i] )
CV_Error( CV_StsOutOfRange, "One of indices is out of range" );
CV_Error( cv::Error::StsOutOfRange, "One of indices is out of range" );
hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t;
}
}
@ -618,7 +618,7 @@ cvCreateData( CvArr* arr )
return;
if( mat->data.ptr != 0 )
CV_Error( CV_StsError, "Data is already allocated" );
CV_Error( cv::Error::StsError, "Data is already allocated" );
if( step == 0 )
step = CV_ELEM_SIZE(mat->type)*mat->cols;
@ -626,7 +626,7 @@ cvCreateData( CvArr* arr )
int64 _total_size = (int64)step*mat->rows + sizeof(int) + CV_MALLOC_ALIGN;
total_size = (size_t)_total_size;
if(_total_size != (int64)total_size)
CV_Error(CV_StsNoMem, "Too big buffer is allocated" );
CV_Error(cv::Error::StsNoMem, "Too big buffer is allocated" );
mat->refcount = (int*)cvAlloc( (size_t)total_size );
mat->data.ptr = (uchar*)cvAlignPtr( mat->refcount + 1, CV_MALLOC_ALIGN );
*mat->refcount = 1;
@ -636,13 +636,13 @@ cvCreateData( CvArr* arr )
IplImage* img = (IplImage*)arr;
if( img->imageData != 0 )
CV_Error( CV_StsError, "Data is already allocated" );
CV_Error( cv::Error::StsError, "Data is already allocated" );
if( !CvIPL.allocateData )
{
const int64 imageSize_tmp = (int64)img->widthStep*(int64)img->height;
if( (int64)img->imageSize != imageSize_tmp )
CV_Error( CV_StsNoMem, "Overflow for imageSize" );
CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" );
img->imageData = img->imageDataOrigin =
(char*)cvAlloc( (size_t)img->imageSize );
}
@ -672,7 +672,7 @@ cvCreateData( CvArr* arr )
return;
if( mat->data.ptr != 0 )
CV_Error( CV_StsError, "Data is already allocated" );
CV_Error( cv::Error::StsError, "Data is already allocated" );
if( CV_IS_MAT_CONT( mat->type ))
{
@ -697,7 +697,7 @@ cvCreateData( CvArr* arr )
*mat->refcount = 1;
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
@ -721,7 +721,7 @@ cvSetData( CvArr* arr, void* data, int step )
if( step != CV_AUTOSTEP && step != 0 )
{
if( step < min_step && data != 0 )
CV_Error( CV_BadStep, "" );
CV_Error( cv::Error::BadStep, "" );
mat->step = step;
}
else
@ -742,7 +742,7 @@ cvSetData( CvArr* arr, void* data, int step )
if( step != CV_AUTOSTEP && img->height > 1 )
{
if( step < min_step && data != 0 )
CV_Error( CV_BadStep, "" );
CV_Error( cv::Error::BadStep, "" );
img->widthStep = step;
}
else
@ -753,7 +753,7 @@ cvSetData( CvArr* arr, void* data, int step )
const int64 imageSize_tmp = (int64)img->widthStep*(int64)img->height;
img->imageSize = (int)imageSize_tmp;
if( (int64)img->imageSize != imageSize_tmp )
CV_Error( CV_StsNoMem, "Overflow for imageSize" );
CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" );
img->imageData = img->imageDataOrigin = (char*)data;
if( (((int)(size_t)data | step) & 7) == 0 &&
@ -769,7 +769,7 @@ cvSetData( CvArr* arr, void* data, int step )
int64 cur_step;
if( step != CV_AUTOSTEP )
CV_Error( CV_BadStep,
CV_Error( cv::Error::BadStep,
"For multidimensional array only CV_AUTOSTEP is allowed here" );
mat->data.ptr = (uchar*)data;
@ -778,13 +778,13 @@ cvSetData( CvArr* arr, void* data, int step )
for( i = mat->dims - 1; i >= 0; i-- )
{
if( cur_step > INT_MAX )
CV_Error( CV_StsOutOfRange, "The array is too big" );
CV_Error( cv::Error::StsOutOfRange, "The array is too big" );
mat->dim[i].step = (int)cur_step;
cur_step *= mat->dim[i].size;
}
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
@ -813,9 +813,13 @@ cvReleaseData( CvArr* arr )
}
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
static inline cv::Size cvGetMatSize( const CvMat* mat )
{
return cv::Size(mat->cols, mat->rows);
}
// Retrieves essential information about image ROI or CvMat data
CV_IMPL void
@ -861,7 +865,7 @@ cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
CvMatND* mat = (CvMatND*)arr;
if( !CV_IS_MAT_CONT( mat->type ))
CV_Error( CV_StsBadArg, "Only continuous nD arrays are supported here" );
CV_Error( cv::Error::StsBadArg, "Only continuous nD arrays are supported here" );
if( data )
*data = mat->data.ptr;
@ -890,7 +894,7 @@ cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
}
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
@ -906,7 +910,7 @@ cvGetElemType( const CvArr* arr )
type = CV_MAKETYPE( IPL2CV_DEPTH(img->depth), img->nChannels );
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
return type;
}
@ -960,7 +964,7 @@ cvGetDims( const CvArr* arr, int* sizes )
memcpy( sizes, mat->size, dims*sizeof(sizes[0]));
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
return dims;
}
@ -985,7 +989,7 @@ cvGetDimSize( const CvArr* arr, int index )
size = mat->cols;
break;
default:
CV_Error( CV_StsOutOfRange, "bad dimension index" );
CV_Error( cv::Error::StsOutOfRange, "bad dimension index" );
}
}
else if( CV_IS_IMAGE( arr ))
@ -1001,7 +1005,7 @@ cvGetDimSize( const CvArr* arr, int index )
size = !img->roi ? img->width : img->roi->width;
break;
default:
CV_Error( CV_StsOutOfRange, "bad dimension index" );
CV_Error( cv::Error::StsOutOfRange, "bad dimension index" );
}
}
else if( CV_IS_MATND_HDR( arr ))
@ -1009,7 +1013,7 @@ cvGetDimSize( const CvArr* arr, int index )
CvMatND* mat = (CvMatND*)arr;
if( (unsigned)index >= (unsigned)mat->dims )
CV_Error( CV_StsOutOfRange, "bad dimension index" );
CV_Error( cv::Error::StsOutOfRange, "bad dimension index" );
size = mat->dim[index].size;
}
@ -1018,12 +1022,12 @@ cvGetDimSize( const CvArr* arr, int index )
CvSparseMat* mat = (CvSparseMat*)arr;
if( (unsigned)index >= (unsigned)mat->dims )
CV_Error( CV_StsOutOfRange, "bad dimension index" );
CV_Error( cv::Error::StsOutOfRange, "bad dimension index" );
size = mat->size[index];
}
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
return size;
}
@ -1058,7 +1062,7 @@ cvGetSize( const CvArr* arr )
}
}
else
CV_Error( CV_StsBadArg, "Array should be CvMat or IplImage" );
CV_Error( cv::Error::StsBadArg, "Array should be CvMat or IplImage" );
return size;
}
@ -1075,14 +1079,14 @@ cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect )
mat = cvGetMat( mat, &stub );
if( !submat )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( (rect.x|rect.y|rect.width|rect.height) < 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
if( rect.x + rect.width > mat->cols ||
rect.y + rect.height > mat->rows )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
{
/*
@ -1120,11 +1124,11 @@ cvGetRows( const CvArr* arr, CvMat* submat,
mat = cvGetMat( mat, &stub );
if( !submat )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( (unsigned)start_row >= (unsigned)mat->rows ||
(unsigned)end_row > (unsigned)mat->rows || delta_row <= 0 )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
{
/*
@ -1172,12 +1176,12 @@ cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col )
mat = cvGetMat( mat, &stub );
if( !submat )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
cols = mat->cols;
if( (unsigned)start_col >= (unsigned)cols ||
(unsigned)end_col > (unsigned)cols )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
{
/*
@ -1216,7 +1220,7 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
CV_Assert( scalar && data );
if( (unsigned)(cn - 1) >= 4 )
CV_Error( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
CV_Error( cv::Error::StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
switch( depth )
{
@ -1262,7 +1266,7 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
break;
default:
CV_Assert(0);
CV_Error( CV_BadDepth, "" );
CV_Error( cv::Error::BadDepth, "" );
}
if( extend_to_12 )
@ -1289,7 +1293,7 @@ cvRawDataToScalar( const void* data, int flags, CvScalar* scalar )
CV_Assert( scalar && data );
if( (unsigned)(cn - 1) >= 4 )
CV_Error( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
CV_Error( cv::Error::StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
memset( scalar->val, 0, sizeof(scalar->val));
@ -1325,7 +1329,7 @@ cvRawDataToScalar( const void* data, int flags, CvScalar* scalar )
break;
default:
CV_Assert(0);
CV_Error( CV_BadDepth, "" );
CV_Error( cv::Error::BadDepth, "" );
}
}
@ -1412,7 +1416,7 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
// that the index is within the matrix
if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
(unsigned)idx >= (unsigned)(mat->rows*mat->cols))
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
if( CV_IS_MAT_CONT(mat->type))
{
@ -1449,7 +1453,7 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
size *= mat->dim[j].size;
if((unsigned)idx >= (unsigned)size )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
if( CV_IS_MAT_CONT(mat->type))
{
@ -1493,7 +1497,7 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
}
else
{
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
return ptr;
@ -1512,7 +1516,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
if( (unsigned)y >= (unsigned)(mat->rows) ||
(unsigned)x >= (unsigned)(mat->cols) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
type = CV_MAT_TYPE(mat->type);
if( _type )
@ -1542,7 +1546,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
{
int coi = img->roi->coi;
if( !coi )
CV_Error( CV_BadCOI,
CV_Error( cv::Error::BadCOI,
"COI must be non-null in case of planar images" );
ptr += (coi - 1)*img->imageSize;
}
@ -1555,7 +1559,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
if( (unsigned)y >= (unsigned)height ||
(unsigned)x >= (unsigned)width )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr += y*img->widthStep + x*pix_size;
@ -1563,7 +1567,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
{
int type = IPL2CV_DEPTH(img->depth);
if( type < 0 || (unsigned)(img->nChannels - 1) > 3 )
CV_Error( CV_StsUnsupportedFormat, "" );
CV_Error( cv::Error::StsUnsupportedFormat, "" );
*_type = CV_MAKETYPE( type, img->nChannels );
}
@ -1575,7 +1579,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
if( mat->dims != 2 ||
(unsigned)y >= (unsigned)(mat->dim[0].size) ||
(unsigned)x >= (unsigned)(mat->dim[1].size) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)y*mat->dim[0].step + x*mat->dim[1].step;
if( _type )
@ -1589,7 +1593,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
}
else
{
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
return ptr;
@ -1609,7 +1613,7 @@ cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type )
(unsigned)z >= (unsigned)(mat->dim[0].size) ||
(unsigned)y >= (unsigned)(mat->dim[1].size) ||
(unsigned)x >= (unsigned)(mat->dim[2].size) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)z*mat->dim[0].step +
(size_t)y*mat->dim[1].step + x*mat->dim[2].step;
@ -1624,7 +1628,7 @@ cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type )
}
else
{
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
}
return ptr;
@ -1638,7 +1642,7 @@ cvPtrND( const CvArr* arr, const int* idx, int* _type,
{
uchar* ptr = 0;
if( !idx )
CV_Error( CV_StsNullPtr, "NULL pointer to indices" );
CV_Error( cv::Error::StsNullPtr, "NULL pointer to indices" );
if( CV_IS_SPARSE_MAT( arr ))
ptr = icvGetNodePtr( (CvSparseMat*)arr, idx,
@ -1652,7 +1656,7 @@ cvPtrND( const CvArr* arr, const int* idx, int* _type,
for( i = 0; i < mat->dims; i++ )
{
if( (unsigned)idx[i] >= (unsigned)(mat->dim[i].size) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr += (size_t)idx[i]*mat->dim[i].step;
}
@ -1662,7 +1666,7 @@ cvPtrND( const CvArr* arr, const int* idx, int* _type,
else if( CV_IS_MAT_HDR(arr) || CV_IS_IMAGE_HDR(arr) )
ptr = cvPtr2D( arr, idx[0], idx[1], _type );
else
CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadArg, "unrecognized or unsupported array type" );
return ptr;
}
@ -1687,7 +1691,7 @@ cvGet1D( const CvArr* arr, int idx )
// that the index is within the matrix
if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
(unsigned)idx >= (unsigned)(mat->rows*mat->cols))
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)idx*pix_size;
}
@ -1717,7 +1721,7 @@ cvGet2D( const CvArr* arr, int y, int x )
if( (unsigned)y >= (unsigned)(mat->rows) ||
(unsigned)x >= (unsigned)(mat->cols) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
type = CV_MAT_TYPE(mat->type);
ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@ -1798,7 +1802,7 @@ cvGetReal1D( const CvArr* arr, int idx )
// that the index is within the matrix
if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
(unsigned)idx >= (unsigned)(mat->rows*mat->cols))
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)idx*pix_size;
}
@ -1810,7 +1814,7 @@ cvGetReal1D( const CvArr* arr, int idx )
if( ptr )
{
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" );
value = icvGetReal( ptr, type );
}
@ -1832,7 +1836,7 @@ cvGetReal2D( const CvArr* arr, int y, int x )
if( (unsigned)y >= (unsigned)(mat->rows) ||
(unsigned)x >= (unsigned)(mat->cols) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
type = CV_MAT_TYPE(mat->type);
ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@ -1848,7 +1852,7 @@ cvGetReal2D( const CvArr* arr, int y, int x )
if( ptr )
{
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" );
value = icvGetReal( ptr, type );
}
@ -1876,7 +1880,7 @@ cvGetReal3D( const CvArr* arr, int z, int y, int x )
if( ptr )
{
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" );
value = icvGetReal( ptr, type );
}
@ -1901,7 +1905,7 @@ cvGetRealND( const CvArr* arr, const int* idx )
if( ptr )
{
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvGetReal* support only single-channel arrays" );
value = icvGetReal( ptr, type );
}
@ -1928,7 +1932,7 @@ cvSet1D( CvArr* arr, int idx, CvScalar scalar )
// that the index is within the matrix
if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
(unsigned)idx >= (unsigned)(mat->rows*mat->cols))
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)idx*pix_size;
}
@ -1954,7 +1958,7 @@ cvSet2D( CvArr* arr, int y, int x, CvScalar scalar )
if( (unsigned)y >= (unsigned)(mat->rows) ||
(unsigned)x >= (unsigned)(mat->cols) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
type = CV_MAT_TYPE(mat->type);
ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@ -2020,7 +2024,7 @@ cvSetReal1D( CvArr* arr, int idx, double value )
// that the index is within the matrix
if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
(unsigned)idx >= (unsigned)(mat->rows*mat->cols))
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
ptr = mat->data.ptr + (size_t)idx*pix_size;
}
@ -2030,7 +2034,7 @@ cvSetReal1D( CvArr* arr, int idx, double value )
ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, -1, 0 );
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" );
if( ptr )
icvSetReal( value, ptr, type );
@ -2049,7 +2053,7 @@ cvSetReal2D( CvArr* arr, int y, int x, double value )
if( (unsigned)y >= (unsigned)(mat->rows) ||
(unsigned)x >= (unsigned)(mat->cols) )
CV_Error( CV_StsOutOfRange, "index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "index is out of range" );
type = CV_MAT_TYPE(mat->type);
ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@ -2064,7 +2068,7 @@ cvSetReal2D( CvArr* arr, int y, int x, double value )
ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
}
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" );
if( ptr )
icvSetReal( value, ptr, type );
@ -2085,7 +2089,7 @@ cvSetReal3D( CvArr* arr, int z, int y, int x, double value )
ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
}
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" );
if( ptr )
icvSetReal( value, ptr, type );
@ -2104,7 +2108,7 @@ cvSetRealND( CvArr* arr, const int* idx, double value )
ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
if( CV_MAT_CN( type ) > 1 )
CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
CV_Error( cv::Error::BadNumChannels, "cvSetReal* support only single-channel arrays" );
if( ptr )
icvSetReal( value, ptr, type );
@ -2141,12 +2145,12 @@ cvGetMat( const CvArr* array, CvMat* mat,
int coi = 0;
if( !mat || !src )
CV_Error( CV_StsNullPtr, "NULL array pointer is passed" );
CV_Error( cv::Error::StsNullPtr, "NULL array pointer is passed" );
if( CV_IS_MAT_HDR(src))
{
if( !src->data.ptr )
CV_Error( CV_StsNullPtr, "The matrix has NULL data pointer" );
CV_Error( cv::Error::StsNullPtr, "The matrix has NULL data pointer" );
result = (CvMat*)src;
}
@ -2156,11 +2160,11 @@ cvGetMat( const CvArr* array, CvMat* mat,
int depth, order;
if( img->imageData == 0 )
CV_Error( CV_StsNullPtr, "The image has NULL data pointer" );
CV_Error( cv::Error::StsNullPtr, "The image has NULL data pointer" );
depth = IPL2CV_DEPTH( img->depth );
if( depth < 0 )
CV_Error( CV_BadDepth, "" );
CV_Error( cv::Error::BadDepth, "" );
order = img->dataOrder & (img->nChannels > 1 ? -1 : 0);
@ -2171,7 +2175,7 @@ cvGetMat( const CvArr* array, CvMat* mat,
int type = depth;
if( img->roi->coi == 0 )
CV_Error( CV_StsBadFlag,
CV_Error( cv::Error::StsBadFlag,
"Images with planar data layout should be used with COI selected" );
cvInitMatHeader( mat, img->roi->height,
@ -2187,7 +2191,7 @@ cvGetMat( const CvArr* array, CvMat* mat,
coi = img->roi->coi;
if( img->nChannels > CV_CN_MAX )
CV_Error( CV_BadNumChannels,
CV_Error( cv::Error::BadNumChannels,
"The image is interleaved and has over CV_CN_MAX channels" );
cvInitMatHeader( mat, img->roi->height, img->roi->width,
@ -2202,7 +2206,7 @@ cvGetMat( const CvArr* array, CvMat* mat,
int type = CV_MAKETYPE( depth, img->nChannels );
if( order != IPL_DATA_ORDER_PIXEL )
CV_Error( CV_StsBadFlag, "Pixel order should be used with coi == 0" );
CV_Error( cv::Error::StsBadFlag, "Pixel order should be used with coi == 0" );
cvInitMatHeader( mat, img->height, img->width, type,
img->imageData, img->widthStep );
@ -2216,10 +2220,10 @@ cvGetMat( const CvArr* array, CvMat* mat,
int size1 = matnd->dim[0].size, size2 = 1;
if( !src->data.ptr )
CV_Error( CV_StsNullPtr, "Input array has NULL data pointer" );
CV_Error( cv::Error::StsNullPtr, "Input array has NULL data pointer" );
if( !CV_IS_MAT_CONT( matnd->type ))
CV_Error( CV_StsBadArg, "Only continuous nD arrays are supported here" );
CV_Error( cv::Error::StsBadArg, "Only continuous nD arrays are supported here" );
if( matnd->dims > 2 )
{
@ -2243,7 +2247,7 @@ cvGetMat( const CvArr* array, CvMat* mat,
result = mat;
}
else
CV_Error( CV_StsBadFlag, "Unrecognized or unsupported array type" );
CV_Error( cv::Error::StsBadFlag, "Unrecognized or unsupported array type" );
if( pCOI )
*pCOI = coi;
@ -2261,20 +2265,20 @@ cvReshape( const CvArr* array, CvMat* header,
int total_width, new_width;
if( !header )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !CV_IS_MAT( mat ))
{
int coi = 0;
mat = cvGetMat( mat, header, &coi, 1 );
if( coi )
CV_Error( CV_BadCOI, "COI is not supported" );
CV_Error( cv::Error::BadCOI, "COI is not supported" );
}
if( new_cn == 0 )
new_cn = CV_MAT_CN(mat->type);
else if( (unsigned)(new_cn - 1) > 3 )
CV_Error( CV_BadNumChannels, "" );
CV_Error( cv::Error::BadNumChannels, "" );
if( mat != header )
{
@ -2298,16 +2302,16 @@ cvReshape( const CvArr* array, CvMat* header,
{
int total_size = total_width * mat->rows;
if( !CV_IS_MAT_CONT( mat->type ))
CV_Error( CV_BadStep,
CV_Error( cv::Error::BadStep,
"The matrix is not continuous, thus its number of rows can not be changed" );
if( (unsigned)new_rows > (unsigned)total_size )
CV_Error( CV_StsOutOfRange, "Bad new number of rows" );
CV_Error( cv::Error::StsOutOfRange, "Bad new number of rows" );
total_width = total_size / new_rows;
if( total_width * new_rows != total_size )
CV_Error( CV_StsBadArg, "The total number of matrix elements "
CV_Error( cv::Error::StsBadArg, "The total number of matrix elements "
"is not divisible by the new number of rows" );
header->rows = new_rows;
@ -2317,7 +2321,7 @@ cvReshape( const CvArr* array, CvMat* header,
new_width = total_width / new_cn;
if( new_width * new_cn != total_width )
CV_Error( CV_BadNumChannels,
CV_Error( cv::Error::BadNumChannels,
"The total width is not divisible by the new number of channels" );
header->cols = new_width;
@ -2336,17 +2340,17 @@ cvGetImage( const CvArr* array, IplImage* img )
const IplImage* src = (const IplImage*)array;
if( !img )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !CV_IS_IMAGE_HDR(src) )
{
const CvMat* mat = (const CvMat*)src;
if( !CV_IS_MAT_HDR(mat))
CV_Error( CV_StsBadFlag, "" );
CV_Error( cv::Error::StsBadFlag, "" );
if( mat->data.ptr == 0 )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
int depth = cvIplDepth(mat->type);
@ -2479,19 +2483,19 @@ cvInitImageHeader( IplImage * image, CvSize size, int depth,
}
if( size.width < 0 || size.height < 0 )
CV_Error( CV_BadROISize, "Bad input roi" );
CV_Error( cv::Error::BadROISize, "Bad input roi" );
if( (depth != (int)IPL_DEPTH_1U && depth != (int)IPL_DEPTH_8U &&
depth != (int)IPL_DEPTH_8S && depth != (int)IPL_DEPTH_16U &&
depth != (int)IPL_DEPTH_16S && depth != (int)IPL_DEPTH_32S &&
depth != (int)IPL_DEPTH_32F && depth != (int)IPL_DEPTH_64F) ||
channels < 0 )
CV_Error( CV_BadDepth, "Unsupported format" );
CV_Error( cv::Error::BadDepth, "Unsupported format" );
if( origin != CV_ORIGIN_BL && origin != CV_ORIGIN_TL )
CV_Error( CV_BadOrigin, "Bad input origin" );
CV_Error( cv::Error::BadOrigin, "Bad input origin" );
if( align != 4 && align != 8 )
CV_Error( CV_BadAlign, "Bad input align" );
CV_Error( cv::Error::BadAlign, "Bad input align" );
image->width = size.width;
image->height = size.height;
@ -2513,7 +2517,7 @@ cvInitImageHeader( IplImage * image, CvSize size, int depth,
const int64 imageSize_tmp = (int64)image->widthStep*(int64)image->height;
image->imageSize = (int)imageSize_tmp;
if( (int64)image->imageSize != imageSize_tmp )
CV_Error( CV_StsNoMem, "Overflow for imageSize" );
CV_Error( cv::Error::StsNoMem, "Overflow for imageSize" );
return image;
}
@ -2523,7 +2527,7 @@ CV_IMPL void
cvReleaseImageHeader( IplImage** image )
{
if( !image )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( *image )
{
@ -2547,7 +2551,7 @@ CV_IMPL void
cvReleaseImage( IplImage ** image )
{
if( !image )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( *image )
{
@ -2621,7 +2625,7 @@ cvGetImageROI( const IplImage* img )
{
CvRect rect = {0, 0, 0, 0};
if( !img )
CV_Error( CV_StsNullPtr, "Null pointer to image" );
CV_Error( cv::Error::StsNullPtr, "Null pointer to image" );
if( img->roi )
rect = cvRect( img->roi->xOffset, img->roi->yOffset,
@ -2640,7 +2644,7 @@ cvSetImageCOI( IplImage* image, int coi )
CV_Error( CV_HeaderIsNull, "" );
if( (unsigned)coi > (unsigned)(image->nChannels) )
CV_Error( CV_BadCOI, "" );
CV_Error( cv::Error::BadCOI, "" );
if( image->roi || coi != 0 )
{
@ -2672,7 +2676,7 @@ cvCloneImage( const IplImage* src )
IplImage* dst = 0;
if( !CV_IS_IMAGE_HDR( src ))
CV_Error( CV_StsBadArg, "Bad image header" );
CV_Error( cv::Error::StsBadArg, "Bad image header" );
if( !CvIPL.cloneImage )
{
@ -2718,13 +2722,13 @@ cvCheckTermCriteria( CvTermCriteria criteria, double default_eps,
crit.epsilon = (float)default_eps;
if( (criteria.type & ~(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) != 0 )
CV_Error( CV_StsBadArg,
CV_Error( cv::Error::StsBadArg,
"Unknown type of term criteria" );
if( (criteria.type & CV_TERMCRIT_ITER) != 0 )
{
if( criteria.max_iter <= 0 )
CV_Error( CV_StsBadArg,
CV_Error( cv::Error::StsBadArg,
"Iterations flag is set and maximum number of iterations is <= 0" );
crit.max_iter = criteria.max_iter;
}
@ -2732,13 +2736,13 @@ cvCheckTermCriteria( CvTermCriteria criteria, double default_eps,
if( (criteria.type & CV_TERMCRIT_EPS) != 0 )
{
if( criteria.epsilon < 0 )
CV_Error( CV_StsBadArg, "Accuracy flag is set and epsilon is < 0" );
CV_Error( cv::Error::StsBadArg, "Accuracy flag is set and epsilon is < 0" );
crit.epsilon = criteria.epsilon;
}
if( (criteria.type & (CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) == 0 )
CV_Error( CV_StsBadArg,
CV_Error( cv::Error::StsBadArg,
"Neither accuracy nor maximum iterations "
"number flags are set in criteria type" );
@ -2765,7 +2769,7 @@ CV_IMPL void
cvRelease( void** struct_ptr )
{
if( !struct_ptr )
CV_Error( CV_StsNullPtr, "NULL double pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL double pointer" );
if( *struct_ptr )
{
@ -2774,7 +2778,7 @@ cvRelease( void** struct_ptr )
else if( CV_IS_IMAGE(*struct_ptr))
cvReleaseImage((IplImage**)struct_ptr);
else
CV_Error( CV_StsError, "Unknown object type" );
CV_Error( cv::Error::StsError, "Unknown object type" );
}
}

@ -377,7 +377,7 @@ void cv::batchDistance( InputArray _src1, InputArray _src2,
}
if( func == 0 )
CV_Error_(CV_StsUnsupportedFormat,
CV_Error_(cv::Error::StsUnsupportedFormat,
("The combination of type=%d, dtype=%d and normType=%d is not supported",
type, dtype, normType));

@ -464,7 +464,7 @@ std::vector<String> CommandLineParser::Impl::split_range_string(const String& _s
{
if (begin == true)
{
throw cv::Exception(CV_StsParseError,
throw cv::Exception(cv::Error::StsParseError,
String("error in split_range_string(")
+ str
+ String(", ")
@ -484,7 +484,7 @@ std::vector<String> CommandLineParser::Impl::split_range_string(const String& _s
{
if (begin == false)
{
throw cv::Exception(CV_StsParseError,
throw cv::Exception(cv::Error::StsParseError,
String("error in split_range_string(")
+ str
+ String(", ")
@ -508,7 +508,7 @@ std::vector<String> CommandLineParser::Impl::split_range_string(const String& _s
if (begin == true)
{
throw cv::Exception(CV_StsParseError,
throw cv::Exception(cv::Error::StsParseError,
String("error in split_range_string(")
+ str
+ String(", ")

@ -111,7 +111,7 @@ void scalarToRawData(const Scalar& s, void* _buf, int type, int unroll_to)
scalarToRawData_(s, (double*)_buf, cn, unroll_to);
break;
default:
CV_Error(CV_StsUnsupportedFormat,"");
CV_Error(cv::Error::StsUnsupportedFormat,"");
}
}
@ -826,7 +826,7 @@ int cv::borderInterpolate( int p, int len, int borderType )
else if( borderType == BORDER_CONSTANT )
p = -1;
else
CV_Error( CV_StsBadArg, "Unknown/unsupported border type" );
CV_Error( cv::Error::StsBadArg, "Unknown/unsupported border type" );
return p;
}

@ -91,7 +91,7 @@ static void
icvInitMemStorage( CvMemStorage* storage, int block_size )
{
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( block_size <= 0 )
block_size = CV_STORAGE_BLOCK_SIZE;
@ -120,7 +120,7 @@ CV_IMPL CvMemStorage *
cvCreateChildMemStorage( CvMemStorage * parent )
{
if( !parent )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
CvMemStorage* storage = cvCreateMemStorage(parent->block_size);
storage->parent = parent;
@ -137,7 +137,7 @@ icvDestroyMemStorage( CvMemStorage* storage )
CvMemBlock *dst_top = 0;
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( storage->parent )
dst_top = storage->parent->top;
@ -180,7 +180,7 @@ CV_IMPL void
cvReleaseMemStorage( CvMemStorage** storage )
{
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
CvMemStorage* st = *storage;
*storage = 0;
@ -197,7 +197,7 @@ CV_IMPL void
cvClearMemStorage( CvMemStorage * storage )
{
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( storage->parent )
icvDestroyMemStorage( storage );
@ -215,7 +215,7 @@ static void
icvGoNextMemBlock( CvMemStorage * storage )
{
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !storage->top || !storage->top->next )
{
@ -273,7 +273,7 @@ CV_IMPL void
cvSaveMemStoragePos( const CvMemStorage * storage, CvMemStoragePos * pos )
{
if( !storage || !pos )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
pos->top = storage->top;
pos->free_space = storage->free_space;
@ -285,9 +285,9 @@ CV_IMPL void
cvRestoreMemStoragePos( CvMemStorage * storage, CvMemStoragePos * pos )
{
if( !storage || !pos )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( pos->free_space > storage->block_size )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
/*
// this breaks icvGoNextMemBlock, so comment it off for now
@ -324,10 +324,10 @@ cvMemStorageAlloc( CvMemStorage* storage, size_t size )
{
schar *ptr = 0;
if( !storage )
CV_Error( CV_StsNullPtr, "NULL storage pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" );
if( size > INT_MAX )
CV_Error( CV_StsOutOfRange, "Too large memory block is requested" );
CV_Error( cv::Error::StsOutOfRange, "Too large memory block is requested" );
CV_Assert( storage->free_space % CV_STRUCT_ALIGN == 0 );
@ -335,7 +335,7 @@ cvMemStorageAlloc( CvMemStorage* storage, size_t size )
{
size_t max_free_space = cvAlignLeft(storage->block_size - sizeof(CvMemBlock), CV_STRUCT_ALIGN);
if( max_free_space < size )
CV_Error( CV_StsOutOfRange, "requested size is negative or too big" );
CV_Error( cv::Error::StsOutOfRange, "requested size is negative or too big" );
icvGoNextMemBlock( storage );
}
@ -374,9 +374,9 @@ cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage*
CvSeq *seq = 0;
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( header_size < sizeof( CvSeq ) || elem_size <= 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
/* allocate sequence header */
seq = (CvSeq*)cvMemStorageAlloc( storage, header_size );
@ -390,7 +390,7 @@ cvCreateSeq( int seq_flags, size_t header_size, size_t elem_size, CvMemStorage*
if( elemtype != CV_SEQ_ELTYPE_GENERIC && elemtype != CV_SEQ_ELTYPE_PTR &&
typesize != 0 && typesize != (int)elem_size )
CV_Error( CV_StsBadSize,
CV_Error( cv::Error::StsBadSize,
"Specified element size doesn't match to the size of the specified element type "
"(try to use 0 for element type)" );
}
@ -412,9 +412,9 @@ cvSetSeqBlockSize( CvSeq *seq, int delta_elements )
int useful_block_size;
if( !seq || !seq->storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( delta_elements < 0 )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
useful_block_size = cvAlignLeft(seq->storage->block_size - sizeof(CvMemBlock) -
sizeof(CvSeqBlock), CV_STRUCT_ALIGN);
@ -429,7 +429,7 @@ cvSetSeqBlockSize( CvSeq *seq, int delta_elements )
{
delta_elements = useful_block_size / elem_size;
if( delta_elements == 0 )
CV_Error( CV_StsOutOfRange, "Storage block size is too small "
CV_Error( cv::Error::StsOutOfRange, "Storage block size is too small "
"to fit the sequence elements" );
}
@ -487,7 +487,7 @@ cvSeqElemIdx( const CvSeq* seq, const void* _element, CvSeqBlock** _block )
CvSeqBlock *block;
if( !seq || !element )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
block = first_block = seq->first;
elem_size = seq->elem_size;
@ -548,7 +548,7 @@ cvCvtSeqToArray( const CvSeq *seq, void *array, CvSlice slice )
char *dst = (char*)array;
if( !seq || !array )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = seq->elem_size;
total = cvSliceLength( slice, seq )*elem_size;
@ -587,10 +587,10 @@ cvMakeSeqHeaderForArray( int seq_flags, int header_size, int elem_size,
CvSeq* result = 0;
if( elem_size <= 0 || header_size < (int)sizeof( CvSeq ) || total < 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
if( !seq || ((!array || !block) && total > 0) )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
memset( seq, 0, header_size );
@ -602,7 +602,7 @@ cvMakeSeqHeaderForArray( int seq_flags, int header_size, int elem_size,
if( elemtype != CV_SEQ_ELTYPE_GENERIC &&
typesize != 0 && typesize != elem_size )
CV_Error( CV_StsBadSize,
CV_Error( cv::Error::StsBadSize,
"Element size doesn't match to the size of predefined element type "
"(try to use 0 for sequence element type)" );
}
@ -634,7 +634,7 @@ icvGrowSeq( CvSeq *seq, int in_front_of )
CvSeqBlock *block;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
block = seq->free_blocks;
if( !block )
@ -647,7 +647,7 @@ icvGrowSeq( CvSeq *seq, int in_front_of )
cvSetSeqBlockSize( seq, delta_elems*2 );
if( !storage )
CV_Error( CV_StsNullPtr, "The sequence has NULL storage pointer" );
CV_Error( cv::Error::StsNullPtr, "The sequence has NULL storage pointer" );
/* If there is a free space just after last allocated block
and it is big enough then enlarge the last block.
@ -817,7 +817,7 @@ CV_IMPL void
cvStartAppendToSeq( CvSeq *seq, CvSeqWriter * writer )
{
if( !seq || !writer )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
memset( writer, 0, sizeof( *writer ));
writer->header_size = sizeof( CvSeqWriter );
@ -835,7 +835,7 @@ cvStartWriteSeq( int seq_flags, int header_size,
int elem_size, CvMemStorage * storage, CvSeqWriter * writer )
{
if( !storage || !writer )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
CvSeq* seq = cvCreateSeq( seq_flags, header_size, elem_size, storage );
cvStartAppendToSeq( seq, writer );
@ -847,7 +847,7 @@ CV_IMPL void
cvFlushSeqWriter( CvSeqWriter * writer )
{
if( !writer )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
CvSeq* seq = writer->seq;
seq->ptr = writer->ptr;
@ -878,7 +878,7 @@ CV_IMPL CvSeq *
cvEndWriteSeq( CvSeqWriter * writer )
{
if( !writer )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
cvFlushSeqWriter( writer );
CvSeq* seq = writer->seq;
@ -909,7 +909,7 @@ CV_IMPL void
cvCreateSeqBlock( CvSeqWriter * writer )
{
if( !writer || !writer->seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
CvSeq* seq = writer->seq;
@ -942,7 +942,7 @@ cvStartReadSeq( const CvSeq *seq, CvSeqReader * reader, int reverse )
}
if( !seq || !reader )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
reader->header_size = sizeof( CvSeqReader );
reader->seq = (CvSeq*)seq;
@ -992,7 +992,7 @@ cvChangeSeqBlock( void* _reader, int direction )
CvSeqReader* reader = (CvSeqReader*)_reader;
if( !reader )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( direction > 0 )
{
@ -1017,7 +1017,7 @@ cvGetSeqReaderPos( CvSeqReader* reader )
int index = -1;
if( !reader || !reader->ptr )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = reader->seq->elem_size;
if( elem_size <= ICV_SHIFT_TAB_MAX && (index = icvPower2ShiftTab[elem_size - 1]) >= 0 )
@ -1042,7 +1042,7 @@ cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative )
int elem_size, count, total;
if( !reader || !reader->seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
total = reader->seq->total;
elem_size = reader->seq->elem_size;
@ -1052,14 +1052,14 @@ cvSetSeqReaderPos( CvSeqReader* reader, int index, int is_relative )
if( index < 0 )
{
if( index < -total )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
index += total;
}
else if( index >= total )
{
index -= total;
if( index >= total )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
}
block = reader->seq->first;
@ -1135,7 +1135,7 @@ cvSeqPush( CvSeq *seq, const void *element )
size_t elem_size;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = seq->elem_size;
ptr = seq->ptr;
@ -1166,9 +1166,9 @@ cvSeqPop( CvSeq *seq, void *element )
int elem_size;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( seq->total <= 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
elem_size = seq->elem_size;
seq->ptr = ptr = seq->ptr - elem_size;
@ -1195,7 +1195,7 @@ cvSeqPushFront( CvSeq *seq, const void *element )
CvSeqBlock *block;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = seq->elem_size;
block = seq->first;
@ -1228,9 +1228,9 @@ cvSeqPopFront( CvSeq *seq, void *element )
CvSeqBlock *block;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( seq->total <= 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
elem_size = seq->elem_size;
block = seq->first;
@ -1257,14 +1257,14 @@ cvSeqInsert( CvSeq *seq, int before_index, const void *element )
schar* ret_ptr = 0;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
total = seq->total;
before_index += before_index < 0 ? total : 0;
before_index -= before_index > total ? total : 0;
if( (unsigned)before_index > (unsigned)total )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
if( before_index == total )
{
@ -1375,7 +1375,7 @@ cvSeqRemove( CvSeq *seq, int index )
int total, front = 0;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
total = seq->total;
@ -1383,7 +1383,7 @@ cvSeqRemove( CvSeq *seq, int index )
index -= index >= total ? total : 0;
if( (unsigned) index >= (unsigned) total )
CV_Error( CV_StsOutOfRange, "Invalid index" );
CV_Error( cv::Error::StsOutOfRange, "Invalid index" );
if( index == total - 1 )
{
@ -1456,9 +1456,9 @@ cvSeqPushMulti( CvSeq *seq, const void *_elements, int count, int front )
char *elements = (char *) _elements;
if( !seq )
CV_Error( CV_StsNullPtr, "NULL sequence pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL sequence pointer" );
if( count < 0 )
CV_Error( CV_StsBadSize, "number of removed elements is negative" );
CV_Error( cv::Error::StsBadSize, "number of removed elements is negative" );
int elem_size = seq->elem_size;
@ -1525,9 +1525,9 @@ cvSeqPopMulti( CvSeq *seq, void *_elements, int count, int front )
char *elements = (char *) _elements;
if( !seq )
CV_Error( CV_StsNullPtr, "NULL sequence pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL sequence pointer" );
if( count < 0 )
CV_Error( CV_StsBadSize, "number of removed elements is negative" );
CV_Error( cv::Error::StsBadSize, "number of removed elements is negative" );
count = MIN( count, seq->total );
@ -1593,7 +1593,7 @@ CV_IMPL void
cvClearSeq( CvSeq *seq )
{
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
cvSeqPopMulti( seq, 0, seq->total );
}
@ -1607,13 +1607,13 @@ cvSeqSlice( const CvSeq* seq, CvSlice slice, CvMemStorage* storage, int copy_dat
CvSeqBlock *block, *first_block = 0, *last_block = 0;
if( !CV_IS_SEQ(seq) )
CV_Error( CV_StsBadArg, "Invalid sequence header" );
CV_Error( cv::Error::StsBadArg, "Invalid sequence header" );
if( !storage )
{
storage = seq->storage;
if( !storage )
CV_Error( CV_StsNullPtr, "NULL storage pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" );
}
elem_size = seq->elem_size;
@ -1624,7 +1624,7 @@ cvSeqSlice( const CvSeq* seq, CvSlice slice, CvMemStorage* storage, int copy_dat
slice.start_index -= seq->total;
if( (unsigned)length > (unsigned)seq->total ||
((unsigned)slice.start_index >= (unsigned)seq->total && length != 0) )
CV_Error( CV_StsOutOfRange, "Bad sequence slice" );
CV_Error( cv::Error::StsOutOfRange, "Bad sequence slice" );
subseq = cvCreateSeq( seq->flags, seq->header_size, elem_size, storage );
@ -1680,7 +1680,7 @@ cvSeqRemoveSlice( CvSeq* seq, CvSlice slice )
int total, length;
if( !CV_IS_SEQ(seq) )
CV_Error( CV_StsBadArg, "Invalid sequence header" );
CV_Error( cv::Error::StsBadArg, "Invalid sequence header" );
length = cvSliceLength( slice, seq );
total = seq->total;
@ -1691,7 +1691,7 @@ cvSeqRemoveSlice( CvSeq* seq, CvSlice slice )
slice.start_index -= total;
if( (unsigned)slice.start_index >= (unsigned)total )
CV_Error( CV_StsOutOfRange, "start slice index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "start slice index is out of range" );
slice.end_index = slice.start_index + length;
@ -1757,16 +1757,16 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
CvSeqBlock block;
if( !CV_IS_SEQ(seq) )
CV_Error( CV_StsBadArg, "Invalid destination sequence header" );
CV_Error( cv::Error::StsBadArg, "Invalid destination sequence header" );
if( !CV_IS_SEQ(from))
{
CvMat* mat = (CvMat*)from;
if( !CV_IS_MAT(mat))
CV_Error( CV_StsBadArg, "Source is not a sequence nor matrix" );
CV_Error( cv::Error::StsBadArg, "Source is not a sequence nor matrix" );
if( !CV_IS_MAT_CONT(mat->type) || (mat->rows != 1 && mat->cols != 1) )
CV_Error( CV_StsBadArg, "The source array must be 1d continuous vector" );
CV_Error( cv::Error::StsBadArg, "The source array must be 1d continuous vector" );
from = cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC, sizeof(from_header),
CV_ELEM_SIZE(mat->type),
@ -1775,7 +1775,7 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
}
if( seq->elem_size != from->elem_size )
CV_Error( CV_StsUnmatchedSizes,
CV_Error( cv::Error::StsUnmatchedSizes,
"Source and destination sequence element sizes are different." );
from_total = from->total;
@ -1788,7 +1788,7 @@ cvSeqInsertSlice( CvSeq* seq, int index, const CvArr* from_arr )
index -= index > total ? total : 0;
if( (unsigned)index > (unsigned)total )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
elem_size = seq->elem_size;
@ -1918,10 +1918,10 @@ cvSeqSort( CvSeq* seq, CvCmpFunc cmp_func, void* aux )
stack[48];
if( !CV_IS_SEQ(seq) )
CV_Error( !seq ? CV_StsNullPtr : CV_StsBadArg, "Bad input sequence" );
CV_Error( !seq ? cv::Error::StsNullPtr : cv::Error::StsBadArg, "Bad input sequence" );
if( !cmp_func )
CV_Error( CV_StsNullPtr, "Null compare function" );
CV_Error( cv::Error::StsNullPtr, "Null compare function" );
if( seq->total <= 1 )
return;
@ -2195,10 +2195,10 @@ cvSeqSearch( CvSeq* seq, const void* _elem, CvCmpFunc cmp_func,
*_idx = idx;
if( !CV_IS_SEQ(seq) )
CV_Error( !seq ? CV_StsNullPtr : CV_StsBadArg, "Bad input sequence" );
CV_Error( !seq ? cv::Error::StsNullPtr : cv::Error::StsBadArg, "Bad input sequence" );
if( !elem )
CV_Error( CV_StsNullPtr, "Null element pointer" );
CV_Error( cv::Error::StsNullPtr, "Null element pointer" );
int elem_size = seq->elem_size;
int total = seq->total;
@ -2256,7 +2256,7 @@ cvSeqSearch( CvSeq* seq, const void* _elem, CvCmpFunc cmp_func,
else
{
if( !cmp_func )
CV_Error( CV_StsNullPtr, "Null compare function" );
CV_Error( cv::Error::StsNullPtr, "Null compare function" );
i = 0, j = total;
@ -2340,16 +2340,16 @@ cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, CvSeq** labels,
int is_set;
if( !labels )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !seq || !is_equal )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !storage )
storage = seq->storage;
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
is_set = CV_IS_SET(seq);
@ -2483,11 +2483,11 @@ CV_IMPL CvSet*
cvCreateSet( int set_flags, int header_size, int elem_size, CvMemStorage * storage )
{
if( !storage )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( header_size < (int)sizeof( CvSet ) ||
elem_size < (int)sizeof(void*)*2 ||
(elem_size & (sizeof(void*)-1)) != 0 )
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
CvSet* set = (CvSet*) cvCreateSeq( set_flags, header_size, elem_size, storage );
set->flags = (set->flags & ~CV_MAGIC_MASK) | CV_SET_MAGIC_VAL;
@ -2504,7 +2504,7 @@ cvSetAdd( CvSet* set, CvSetElem* element, CvSetElem** inserted_element )
CvSetElem *free_elem;
if( !set )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !(set->free_elems) )
{
@ -2552,7 +2552,7 @@ cvSetRemove( CvSet* set, int index )
if( elem )
cvSetRemoveByPtr( set, elem );
else if( !set )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
}
@ -2583,7 +2583,7 @@ cvCreateGraph( int graph_type, int header_size,
|| edge_size < (int) sizeof( CvGraphEdge )
|| vtx_size < (int) sizeof( CvGraphVtx )
){
CV_Error( CV_StsBadSize, "" );
CV_Error( cv::Error::StsBadSize, "" );
}
vertices = cvCreateSet( graph_type, header_size, vtx_size, storage );
@ -2602,7 +2602,7 @@ CV_IMPL void
cvClearGraph( CvGraph * graph )
{
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
cvClearSet( graph->edges );
cvClearSet( (CvSet*)graph );
@ -2617,7 +2617,7 @@ cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* _vertex, CvGraphVtx** _inserted
int index = -1;
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
vertex = (CvGraphVtx*)cvSetNew((CvSet*)graph);
if( vertex )
@ -2642,10 +2642,10 @@ cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx )
int count = -1;
if( !graph || !vtx )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( !CV_IS_SET_ELEM(vtx))
CV_Error( CV_StsBadArg, "The vertex does not belong to the graph" );
CV_Error( cv::Error::StsBadArg, "The vertex does not belong to the graph" );
count = graph->edges->active_count;
for( ;; )
@ -2670,11 +2670,11 @@ cvGraphRemoveVtx( CvGraph* graph, int index )
CvGraphVtx *vtx = 0;
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
vtx = cvGetGraphVtx( graph, index );
if( !vtx )
CV_Error( CV_StsBadArg, "The vertex is not found" );
CV_Error( cv::Error::StsBadArg, "The vertex is not found" );
count = graph->edges->active_count;
for( ;; )
@ -2702,7 +2702,7 @@ cvFindGraphEdgeByPtr( const CvGraph* graph,
int ofs = 0;
if( !graph || !start_vtx || !end_vtx )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( start_vtx == end_vtx )
return 0;
@ -2735,7 +2735,7 @@ cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx )
CvGraphVtx *end_vtx;
if( !graph )
CV_Error( CV_StsNullPtr, "graph pointer is NULL" );
CV_Error( cv::Error::StsNullPtr, "graph pointer is NULL" );
start_vtx = cvGetGraphVtx( graph, start_idx );
end_vtx = cvGetGraphVtx( graph, end_idx );
@ -2759,7 +2759,7 @@ cvGraphAddEdgeByPtr( CvGraph* graph,
int delta;
if( !graph )
CV_Error( CV_StsNullPtr, "graph pointer is NULL" );
CV_Error( cv::Error::StsNullPtr, "graph pointer is NULL" );
if( !CV_IS_GRAPH_ORIENTED( graph ) &&
(start_vtx->flags & CV_SET_ELEM_IDX_MASK) > (end_vtx->flags & CV_SET_ELEM_IDX_MASK) )
@ -2778,7 +2778,7 @@ cvGraphAddEdgeByPtr( CvGraph* graph,
}
if( start_vtx == end_vtx )
CV_Error( start_vtx ? CV_StsBadArg : CV_StsNullPtr,
CV_Error( start_vtx ? cv::Error::StsBadArg : cv::Error::StsNullPtr,
"vertex pointers coincide (or set to NULL)" );
edge = (CvGraphEdge*)cvSetNew( (CvSet*)(graph->edges) );
@ -2826,7 +2826,7 @@ cvGraphAddEdge( CvGraph* graph,
CvGraphVtx *end_vtx;
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
start_vtx = cvGetGraphVtx( graph, start_idx );
end_vtx = cvGetGraphVtx( graph, end_idx );
@ -2843,7 +2843,7 @@ cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, CvGraphVtx* end_v
CvGraphEdge *edge, *next_edge, *prev_edge;
if( !graph || !start_vtx || !end_vtx )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( start_vtx == end_vtx )
return;
@ -2902,7 +2902,7 @@ cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx )
CvGraphVtx *end_vtx;
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
start_vtx = cvGetGraphVtx( graph, start_idx );
end_vtx = cvGetGraphVtx( graph, end_idx );
@ -2919,7 +2919,7 @@ cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vertex )
int count;
if( !graph || !vertex )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
for( edge = vertex->first, count = 0; edge; )
{
@ -2940,11 +2940,11 @@ cvGraphVtxDegree( const CvGraph* graph, int vtx_idx )
int count;
if( !graph )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
vertex = cvGetGraphVtx( graph, vtx_idx );
if( !vertex )
CV_Error( CV_StsObjectNotFound, "" );
CV_Error( cv::Error::StsObjectNotFound, "" );
for( edge = vertex->first, count = 0; edge; )
{
@ -2971,13 +2971,13 @@ icvSeqElemsClearFlags( CvSeq* seq, int offset, int clear_mask )
int i, total, elem_size;
if( !seq )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = seq->elem_size;
total = seq->total;
if( (unsigned)offset > (unsigned)elem_size )
CV_Error( CV_StsBadArg, "" );
CV_Error( cv::Error::StsBadArg, "" );
cvStartReadSeq( seq, &reader );
@ -3001,14 +3001,14 @@ icvSeqFindNextElem( CvSeq* seq, int offset, int mask,
int total, elem_size, index;
if( !seq || !start_index )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
elem_size = seq->elem_size;
total = seq->total;
index = *start_index;
if( (unsigned)offset > (unsigned)elem_size )
CV_Error( CV_StsBadArg, "" );
CV_Error( cv::Error::StsBadArg, "" );
if( total == 0 )
return 0;
@ -3048,7 +3048,7 @@ CV_IMPL CvGraphScanner*
cvCreateGraphScanner( CvGraph* graph, CvGraphVtx* vtx, int mask )
{
if( !graph )
CV_Error( CV_StsNullPtr, "Null graph pointer" );
CV_Error( cv::Error::StsNullPtr, "Null graph pointer" );
CV_Assert( graph->storage != 0 );
@ -3082,7 +3082,7 @@ CV_IMPL void
cvReleaseGraphScanner( CvGraphScanner** scanner )
{
if( !scanner )
CV_Error( CV_StsNullPtr, "Null double pointer to graph scanner" );
CV_Error( cv::Error::StsNullPtr, "Null double pointer to graph scanner" );
if( *scanner )
{
@ -3103,7 +3103,7 @@ cvNextGraphItem( CvGraphScanner* scanner )
CvGraphItem item;
if( !scanner || !(scanner->stack))
CV_Error( CV_StsNullPtr, "Null graph scanner" );
CV_Error( cv::Error::StsNullPtr, "Null graph scanner" );
dst = scanner->dst;
vtx = scanner->vtx;
@ -3259,13 +3259,13 @@ cvCloneGraph( const CvGraph* graph, CvMemStorage* storage )
CvSeqReader reader;
if( !CV_IS_GRAPH(graph))
CV_Error( CV_StsBadArg, "Invalid graph pointer" );
CV_Error( cv::Error::StsBadArg, "Invalid graph pointer" );
if( !storage )
storage = graph->storage;
if( !storage )
CV_Error( CV_StsNullPtr, "NULL storage pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" );
vtx_size = graph->elem_size;
edge_size = graph->edges->elem_size;
@ -3343,7 +3343,7 @@ cvTreeToNodeSeq( const void* first, int header_size, CvMemStorage* storage )
CvTreeNodeIterator iterator;
if( !storage )
CV_Error( CV_StsNullPtr, "NULL storage pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL storage pointer" );
allseq = cvCreateSeq( 0, header_size, sizeof(first), storage );
@ -3389,7 +3389,7 @@ cvInsertNodeIntoTree( void* _node, void* _parent, void* _frame )
CvTreeNode* parent = (CvTreeNode*)_parent;
if( !node || !parent )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
node->v_prev = _parent != _frame ? parent : 0;
node->h_next = parent->v_next;
@ -3410,10 +3410,10 @@ cvRemoveNodeFromTree( void* _node, void* _frame )
CvTreeNode* frame = (CvTreeNode*)_frame;
if( !node )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( node == frame )
CV_Error( CV_StsBadArg, "frame node could not be deleted" );
CV_Error( cv::Error::StsBadArg, "frame node could not be deleted" );
if( node->h_next )
node->h_next->h_prev = node->h_prev;
@ -3440,10 +3440,10 @@ cvInitTreeNodeIterator( CvTreeNodeIterator* treeIterator,
const void* first, int max_level )
{
if( !treeIterator || !first )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
if( max_level < 0 )
CV_Error( CV_StsOutOfRange, "" );
CV_Error( cv::Error::StsOutOfRange, "" );
treeIterator->node = (void*)first;
treeIterator->level = 0;
@ -3459,7 +3459,7 @@ cvNextTreeNode( CvTreeNodeIterator* treeIterator )
int level;
if( !treeIterator )
CV_Error( CV_StsNullPtr, "NULL iterator pointer" );
CV_Error( cv::Error::StsNullPtr, "NULL iterator pointer" );
prevNode = node = (CvTreeNode*)treeIterator->node;
level = treeIterator->level;
@ -3500,7 +3500,7 @@ cvPrevTreeNode( CvTreeNodeIterator* treeIterator )
int level;
if( !treeIterator )
CV_Error( CV_StsNullPtr, "" );
CV_Error( cv::Error::StsNullPtr, "" );
prevNode = node = (CvTreeNode*)treeIterator->node;
level = treeIterator->level;

@ -3469,7 +3469,7 @@ Ptr<DFT2D> DFT2D::create(int width, int height, int depth,
{
if(width == 1 && nonzero_rows > 0 )
{
CV_Error( CV_StsNotImplemented,
CV_Error( cv::Error::StsNotImplemented,
"This mode (using nonzero_rows with a single-column matrix) breaks the function's logic, so it is prohibited.\n"
"For fast convolution/correlation use 2-column matrix or single-row matrix instead" );
}
@ -4317,7 +4317,7 @@ public:
if( len != prev_len )
{
if( len > 1 && (len & 1) )
CV_Error( CV_StsNotImplemented, "Odd-size DCT\'s are not implemented" );
CV_Error( cv::Error::StsNotImplemented, "Odd-size DCT\'s are not implemented" );
opt.nf = DFTFactorize( len, opt.factors );
bool inplace_transform = opt.factors[0] == opt.factors[opt.nf-1];

@ -276,7 +276,7 @@ static void glob_rec(const cv::String& directory, const cv::String& wildchart, s
}
else
{
CV_Error_(CV_StsObjectNotFound, ("could not open directory: %s", directory.c_str()));
CV_Error_(cv::Error::StsObjectNotFound, ("could not open directory: %s", directory.c_str()));
}
}
#endif // OPENCV_HAVE_FILESYSTEM_SUPPORT

@ -1191,7 +1191,7 @@ bool solve( InputArray _src, InputArray _src2arg, OutputArray _dst, int method )
Mat dst = _dst.getMat();
if( m < n )
CV_Error(CV_StsBadArg, "The function can not solve under-determined linear systems" );
CV_Error(cv::Error::StsBadArg, "The function can not solve under-determined linear systems" );
if( m == n )
is_normal = false;
@ -1516,7 +1516,7 @@ void SVD::backSubst( InputArray _w, InputArray _u, InputArray _vt,
vt.ptr<double>(), vt.step, true, rhs.ptr<double>(), rhs.step, nb,
dst.ptr<double>(), dst.step, buffer.data());
else
CV_Error( CV_StsUnsupportedFormat, "" );
CV_Error( cv::Error::StsUnsupportedFormat, "" );
}

@ -1566,7 +1566,7 @@ bool checkRange(InputArray _src, bool quiet, Point* pt, double minVal, double ma
{
cv::String value_str;
value_str << src(cv::Range(badPt.y, badPt.y + 1), cv::Range(badPt.x, badPt.x + 1));
CV_Error_( CV_StsOutOfRange,
CV_Error_( cv::Error::StsOutOfRange,
("the value at (%d, %d)=%s is out of range [%f, %f)", badPt.x, badPt.y, value_str.c_str(), minVal, maxVal));
}
return false;

@ -921,7 +921,7 @@ void mulTransposed(InputArray _src, OutputArray _dst, bool ata,
{
MulTransposedFunc func = getMulTransposedFunc(stype, dtype, ata);
if( !func )
CV_Error( CV_StsUnsupportedFormat, "" );
CV_Error( cv::Error::StsUnsupportedFormat, "" );
func( src, dst, delta, scale );
completeSymm( dst, false );
@ -1221,7 +1221,7 @@ cvCalcPCA( const CvArr* data_arr, CvArr* avg_arr, CvArr* eigenvals, CvArr* eigen
pca.eigenvalues = evals;
pca.eigenvectors = evects;
pca(data, (flags & CV_PCA_USE_AVG) ? mean : cv::Mat(),
pca(data, (flags & cv::PCA::USE_AVG) ? mean : cv::Mat(),
flags, !evals.empty() ? evals.rows + evals.cols - 1 : 0);
if( pca.mean.size() == mean.size() )

@ -265,7 +265,7 @@ void setSize( Mat& m, int _dims, const int* _sz, const size_t* _steps, bool auto
m.step.p[i] = total;
uint64 total1 = (uint64)total*s;
if( (uint64)total1 != (size_t)total1 )
CV_Error( CV_StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
CV_Error( cv::Error::StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
total = (size_t)total1;
}
}
@ -1101,9 +1101,9 @@ void Mat::push_back(const Mat& elems)
bool eq = size == elems.size;
size.p[0] = int(r);
if( !eq )
CV_Error(CV_StsUnmatchedSizes, "Pushed vector length is not equal to matrix row length");
CV_Error(cv::Error::StsUnmatchedSizes, "Pushed vector length is not equal to matrix row length");
if( type() != elems.type() )
CV_Error(CV_StsUnmatchedFormats, "Pushed vector type is not the same as matrix type");
CV_Error(cv::Error::StsUnmatchedFormats, "Pushed vector type is not the same as matrix type");
if( isSubmatrix() || dataend + step.p[0]*delta > datalimit )
reserve( std::max(r + delta, (r*3+1)/2) );
@ -1205,16 +1205,16 @@ Mat Mat::reshape(int new_cn, int new_rows) const
{
int total_size = total_width * rows;
if( !isContinuous() )
CV_Error( CV_BadStep,
CV_Error( cv::Error::BadStep,
"The matrix is not continuous, thus its number of rows can not be changed" );
if( (unsigned)new_rows > (unsigned)total_size )
CV_Error( CV_StsOutOfRange, "Bad new number of rows" );
CV_Error( cv::Error::StsOutOfRange, "Bad new number of rows" );
total_width = total_size / new_rows;
if( total_width * new_rows != total_size )
CV_Error( CV_StsBadArg, "The total number of matrix elements "
CV_Error( cv::Error::StsBadArg, "The total number of matrix elements "
"is not divisible by the new number of rows" );
hdr.rows = new_rows;
@ -1224,7 +1224,7 @@ Mat Mat::reshape(int new_cn, int new_rows) const
int new_width = total_width / new_cn;
if( new_width * new_cn != total_width )
CV_Error( CV_BadNumChannels,
CV_Error( cv::Error::BadNumChannels,
"The total width is not divisible by the new number of channels" );
hdr.dims = 2;
@ -1269,13 +1269,13 @@ Mat Mat::reshape(int _cn, int _newndims, const int* _newsz) const
else if (i < dims)
newsz_buf[i] = this->size[i];
else
CV_Error(CV_StsOutOfRange, "Copy dimension (which has zero size) is not present in source matrix");
CV_Error(cv::Error::StsOutOfRange, "Copy dimension (which has zero size) is not present in source matrix");
total_elem1 *= (size_t)newsz_buf[i];
}
if (total_elem1 != total_elem1_ref)
CV_Error(CV_StsUnmatchedSizes, "Requested and source matrices have different count of elements");
CV_Error(cv::Error::StsUnmatchedSizes, "Requested and source matrices have different count of elements");
Mat hdr = *this;
hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((_cn-1) << CV_CN_SHIFT);
@ -1284,7 +1284,7 @@ Mat Mat::reshape(int _cn, int _newndims, const int* _newsz) const
return hdr;
}
CV_Error(CV_StsNotImplemented, "Reshaping of n-dimensional non-continuous matrices is not supported yet");
CV_Error(cv::Error::StsNotImplemented, "Reshaping of n-dimensional non-continuous matrices is not supported yet");
// TBD
}

@ -163,7 +163,7 @@ Mat cvarrToMat(const CvArr* arr, bool copyData,
{
const IplImage* iplimg = (const IplImage*)arr;
if( coiMode == 0 && iplimg->roi && iplimg->roi->coi > 0 )
CV_Error(CV_BadCOI, "COI is not supported by the function");
CV_Error(cv::Error::BadCOI, "COI is not supported by the function");
return iplImageToMat(iplimg, copyData);
}
if( CV_IS_SEQ(arr) )
@ -187,7 +187,7 @@ Mat cvarrToMat(const CvArr* arr, bool copyData,
cvCvtSeqToArray(seq, buf.ptr(), CV_WHOLE_SEQ);
return buf;
}
CV_Error(CV_StsBadArg, "Unknown array type");
CV_Error(cv::Error::StsBadArg, "Unknown array type");
}
void extractImageCOI(const CvArr* arr, OutputArray _ch, int coi)
@ -256,14 +256,14 @@ cvReduce( const CvArr* srcarr, CvArr* dstarr, int dim, int op )
dim = src.rows > dst.rows ? 0 : src.cols > dst.cols ? 1 : dst.cols == 1;
if( dim > 1 )
CV_Error( CV_StsOutOfRange, "The reduced dimensionality index is out of range" );
CV_Error( cv::Error::StsOutOfRange, "The reduced dimensionality index is out of range" );
if( (dim == 0 && (dst.cols != src.cols || dst.rows != 1)) ||
(dim == 1 && (dst.rows != src.rows || dst.cols != 1)) )
CV_Error( CV_StsBadSize, "The output array size is incorrect" );
CV_Error( cv::Error::StsBadSize, "The output array size is incorrect" );
if( src.channels() != dst.channels() )
CV_Error( CV_StsUnmatchedFormats, "Input and output arrays must have the same number of channels" );
CV_Error( cv::Error::StsUnmatchedFormats, "Input and output arrays must have the same number of channels" );
cv::reduce(src, dst, dim, op, dst.type());
}
@ -320,7 +320,7 @@ cvRange( CvArr* arr, double start, double end )
fdata[j] = (float)val;
}
else
CV_Error( CV_StsUnsupportedFormat, "The function only supports 32sC1 and 32fC1 datatypes" );
CV_Error( cv::Error::StsUnsupportedFormat, "The function only supports 32sC1 and 32fC1 datatypes" );
return arr;
}

@ -21,7 +21,7 @@ static void checkOperandsExist(const Mat& a)
{
if (a.empty())
{
CV_Error(CV_StsBadArg, "Matrix operand is an empty matrix.");
CV_Error(cv::Error::StsBadArg, "Matrix operand is an empty matrix.");
}
}
@ -29,7 +29,7 @@ static void checkOperandsExist(const Mat& a, const Mat& b)
{
if (a.empty() || b.empty())
{
CV_Error(CV_StsBadArg, "One or more matrix operands are empty.");
CV_Error(cv::Error::StsBadArg, "One or more matrix operands are empty.");
}
}
@ -1456,7 +1456,7 @@ void MatOp_Bin::assign(const MatExpr& e, Mat& m, int _type) const
else if( e.flags == 'a' && !e.b.data )
cv::absdiff(e.a, e.s, dst);
else
CV_Error(CV_StsError, "Unknown operation");
CV_Error(cv::Error::StsError, "Unknown operation");
if( dst.data != m.data )
dst.convertTo(m, _type);
@ -1688,7 +1688,7 @@ void MatOp_Initializer::assign(const MatExpr& e, Mat& m, int _type) const
else if( e.flags == '1' )
m = Scalar(e.alpha);
else
CV_Error(CV_StsError, "Invalid matrix initializer type");
CV_Error(cv::Error::StsError, "Invalid matrix initializer type");
}
void MatOp_Initializer::multiply(const MatExpr& e, double s, MatExpr& res) const

@ -965,7 +965,7 @@ void cv::reduce(InputArray _src, OutputArray _dst, int dim, int op, int dtype)
}
if( !func )
CV_Error( CV_StsUnsupportedFormat,
CV_Error( cv::Error::StsUnsupportedFormat,
"Unsupported combination of input and output array formats" );
func( src, temp );

@ -758,7 +758,7 @@ double norm( const SparseMat& src, int normType )
}
}
else
CV_Error( CV_StsUnsupportedFormat, "Only 32f and 64f are supported" );
CV_Error( cv::Error::StsUnsupportedFormat, "Only 32f and 64f are supported" );
if( normType == NORM_L2 )
result = std::sqrt(result);
@ -821,7 +821,7 @@ void minMaxLoc( const SparseMat& src, double* _minval, double* _maxval, int* _mi
*_maxval = maxval;
}
else
CV_Error( CV_StsUnsupportedFormat, "Only 32f and 64f are supported" );
CV_Error( cv::Error::StsUnsupportedFormat, "Only 32f and 64f are supported" );
if( _minidx && minidx )
for( i = 0; i < d; i++ )
@ -837,13 +837,13 @@ void normalize( const SparseMat& src, SparseMat& dst, double a, int norm_type )
CV_INSTRUMENT_REGION();
double scale = 1;
if( norm_type == CV_L2 || norm_type == CV_L1 || norm_type == CV_C )
if( norm_type == NORM_L2 || norm_type == NORM_L1 || norm_type == NORM_INF )
{
scale = norm( src, norm_type );
scale = scale > DBL_EPSILON ? a/scale : 0.;
}
else
CV_Error( CV_StsBadArg, "Unknown/unsupported norm type" );
CV_Error( cv::Error::StsBadArg, "Unknown/unsupported norm type" );
src.convertTo( dst, -1, scale );
}

@ -964,7 +964,7 @@ bool _InputArray::isContinuous(int i) const
if( k == CUDA_GPU_MAT )
return i < 0 ? ((const cuda::GpuMat*)obj)->isContinuous() : true;
CV_Error(CV_StsNotImplemented, "Unknown/unsupported array type");
CV_Error(cv::Error::StsNotImplemented, "Unknown/unsupported array type");
}
bool _InputArray::isSubmatrix(int i) const
@ -1002,7 +1002,7 @@ bool _InputArray::isSubmatrix(int i) const
return vv[i].isSubmatrix();
}
CV_Error(CV_StsNotImplemented, "");
CV_Error(cv::Error::StsNotImplemented, "");
}
size_t _InputArray::offset(int i) const
@ -1475,14 +1475,14 @@ void _OutputArray::create(int d, const int* sizes, int mtype, int i,
((std::vector<Vec<int, 128> >*)v)->resize(len);
break;
default:
CV_Error_(CV_StsBadArg, ("Vectors with element size %d are not supported. Please, modify OutputArray::create()\n", esz));
CV_Error_(cv::Error::StsBadArg, ("Vectors with element size %d are not supported. Please, modify OutputArray::create()\n", esz));
}
return;
}
if( k == NONE )
{
CV_Error(CV_StsNullPtr, "create() called for the missing output array" );
CV_Error(cv::Error::StsNullPtr, "create() called for the missing output array" );
}
if( k == STD_VECTOR_MAT )

@ -1412,7 +1412,7 @@ void normalize(InputArray _src, InputOutputArray _dst, double a, double b,
if( rtype < 0 )
rtype = _dst.fixedType() ? _dst.depth() : depth;
if( norm_type == CV_MINMAX )
if( norm_type == NORM_MINMAX )
{
double smin = 0, smax = 0;
double dmin = MIN( a, b ), dmax = MAX( a, b );
@ -1426,14 +1426,14 @@ void normalize(InputArray _src, InputOutputArray _dst, double a, double b,
else
shift = dmin - smin*scale;
}
else if( norm_type == CV_L2 || norm_type == CV_L1 || norm_type == CV_C )
else if( norm_type == NORM_L2 || norm_type == NORM_L1 || norm_type == NORM_INF )
{
scale = norm( _src, norm_type, _mask );
scale = scale > DBL_EPSILON ? a/scale : 0.;
shift = 0;
}
else
CV_Error( CV_StsBadArg, "Unknown/unsupported norm type" );
CV_Error( cv::Error::StsBadArg, "Unknown/unsupported norm type" );
CV_OCL_RUN(_dst.isUMat(),
ocl_normalize(_src, _dst, _mask, rtype, scale, shift))

@ -70,7 +70,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp
Size mean_sz;
CV_Assert( data.channels() == 1 );
if( flags & CV_PCA_DATA_AS_COL )
if( flags & PCA::DATA_AS_COL )
{
len = data.rows;
in_count = data.cols;
@ -111,8 +111,8 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp
if( !(covar_flags & CV_COVAR_NORMAL) )
{
// CV_PCA_DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A
// CV_PCA_DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A'
// PCA::DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A
// PCA::DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A'
Mat tmp_data, tmp_mean = repeat(mean, data.rows/mean.rows, data.cols/mean.cols);
if( data.type() != ctype || tmp_mean.data == mean.data )
{
@ -127,7 +127,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, int maxComp
Mat evects1(count, len, ctype);
gemm( eigenvectors, tmp_data, 1, Mat(), 0, evects1,
(flags & CV_PCA_DATA_AS_COL) ? CV_GEMM_B_T : 0);
(flags & PCA::DATA_AS_COL) ? CV_GEMM_B_T : 0);
eigenvectors = evects1;
// normalize eigenvectors
@ -206,7 +206,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta
Size mean_sz;
CV_Assert( data.channels() == 1 );
if( flags & CV_PCA_DATA_AS_COL )
if( flags & PCA::DATA_AS_COL )
{
len = data.rows;
in_count = data.cols;
@ -247,8 +247,8 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta
if( !(covar_flags & CV_COVAR_NORMAL) )
{
// CV_PCA_DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A
// CV_PCA_DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A'
// PCA::DATA_AS_ROW: cols(A)>rows(A). x=A'*y -> x'=y'*A
// PCA::DATA_AS_COL: rows(A)>cols(A). x=A''*y -> x'=y'*A'
Mat tmp_data, tmp_mean = repeat(mean, data.rows/mean.rows, data.cols/mean.cols);
if( data.type() != ctype || tmp_mean.data == mean.data )
{
@ -263,7 +263,7 @@ PCA& PCA::operator()(InputArray _data, InputArray __mean, int flags, double reta
Mat evects1(count, len, ctype);
gemm( eigenvectors, tmp_data, 1, Mat(), 0, evects1,
(flags & CV_PCA_DATA_AS_COL) ? CV_GEMM_B_T : 0);
(flags & PCA::DATA_AS_COL) ? CV_GEMM_B_T : 0);
eigenvectors = evects1;
// normalize all eigenvectors

@ -670,7 +670,7 @@ void RNG::fill( InputOutputArray _mat, int disttype,
}
CV_Assert( func != 0 );
}
else if( disttype == CV_RAND_NORMAL )
else if( disttype == RNG::NORMAL )
{
_parambuf.allocate(MAX(n1, cn) + MAX(n2, cn));
double* parambuf = _parambuf.data();
@ -708,7 +708,7 @@ void RNG::fill( InputOutputArray _mat, int disttype,
CV_Assert( scaleFunc != 0 );
}
else
CV_Error( CV_StsBadArg, "Unknown distribution type" );
CV_Error( cv::Error::StsBadArg, "Unknown distribution type" );
const Mat* arrays[] = {&mat, 0};
uchar* ptr = 0;

@ -1325,38 +1325,42 @@ CV_IMPL const char* cvErrorStr( int status )
switch (status)
{
case CV_StsOk : return "No Error";
case CV_StsBackTrace : return "Backtrace";
case CV_StsError : return "Unspecified error";
case CV_StsInternal : return "Internal error";
case CV_StsNoMem : return "Insufficient memory";
case CV_StsBadArg : return "Bad argument";
case CV_StsNoConv : return "Iterations do not converge";
case CV_StsAutoTrace : return "Autotrace call";
case CV_StsBadSize : return "Incorrect size of input array";
case CV_StsNullPtr : return "Null pointer";
case CV_StsDivByZero : return "Division by zero occurred";
case CV_BadStep : return "Image step is wrong";
case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
case CV_StsObjectNotFound : return "Requested object was not found";
case CV_BadDepth : return "Input image depth is not supported by function";
case CV_StsUnmatchedFormats : return "Formats of input arguments do not match";
case CV_StsUnmatchedSizes : return "Sizes of input arguments do not match";
case CV_StsOutOfRange : return "One of the arguments\' values is out of range";
case CV_StsUnsupportedFormat : return "Unsupported format or combination of formats";
case CV_BadCOI : return "Input COI is not supported";
case CV_BadNumChannels : return "Bad number of channels";
case CV_StsBadFlag : return "Bad flag (parameter or structure field)";
case CV_StsBadPoint : return "Bad parameter of type CvPoint";
case CV_StsBadMask : return "Bad type of mask argument";
case CV_StsParseError : return "Parsing error";
case CV_StsNotImplemented : return "The function/feature is not implemented";
case CV_StsBadMemBlock : return "Memory block has been corrupted";
case CV_StsAssert : return "Assertion failed";
case CV_GpuNotSupported : return "No CUDA support";
case CV_GpuApiCallError : return "Gpu API call";
case CV_OpenGlNotSupported : return "No OpenGL support";
case CV_OpenGlApiCallError : return "OpenGL API call";
case cv::Error::StsOk : return "No Error";
case cv::Error::StsBackTrace : return "Backtrace";
case cv::Error::StsError : return "Unspecified error";
case cv::Error::StsInternal : return "Internal error";
case cv::Error::StsNoMem : return "Insufficient memory";
case cv::Error::StsBadArg : return "Bad argument";
case cv::Error::StsNoConv : return "Iterations do not converge";
case cv::Error::StsAutoTrace : return "Autotrace call";
case cv::Error::StsBadSize : return "Incorrect size of input array";
case cv::Error::StsNullPtr : return "Null pointer";
case cv::Error::StsDivByZero : return "Division by zero occurred";
case cv::Error::BadStep : return "Image step is wrong";
case cv::Error::StsInplaceNotSupported : return "Inplace operation is not supported";
case cv::Error::StsObjectNotFound : return "Requested object was not found";
case cv::Error::BadDepth : return "Input image depth is not supported by function";
case cv::Error::StsUnmatchedFormats : return "Formats of input arguments do not match";
case cv::Error::StsUnmatchedSizes : return "Sizes of input arguments do not match";
case cv::Error::StsOutOfRange : return "One of the arguments\' values is out of range";
case cv::Error::StsUnsupportedFormat : return "Unsupported format or combination of formats";
case cv::Error::BadCOI : return "Input COI is not supported";
case cv::Error::BadNumChannels : return "Bad number of channels";
case cv::Error::StsBadFlag : return "Bad flag (parameter or structure field)";
case cv::Error::StsBadPoint : return "Bad parameter of type CvPoint";
case cv::Error::StsBadMask : return "Bad type of mask argument";
case cv::Error::StsParseError : return "Parsing error";
case cv::Error::StsNotImplemented : return "The function/feature is not implemented";
case cv::Error::StsBadMemBlock : return "Memory block has been corrupted";
case cv::Error::StsAssert : return "Assertion failed";
case cv::Error::GpuNotSupported : return "No CUDA support";
case cv::Error::GpuApiCallError : return "Gpu API call";
case cv::Error::OpenGlNotSupported : return "No OpenGL support";
case cv::Error::OpenGlApiCallError : return "OpenGL API call";
case cv::Error::OpenCLApiCallError : return "OpenCL API call error";
case cv::Error::OpenCLDoubleNotSupported:return "OpenCL device does not support double";
case cv::Error::OpenCLInitError : return "OpenCL initialization error";
case cv::Error::OpenCLNoAMDBlasFft : return "Missing OpenCL AMD BLAS FFT";
};
snprintf(buf, sizeof(buf), "Unknown %s code %d", status >= 0 ? "status":"error", status);
@ -1396,29 +1400,29 @@ cvErrorFromIppStatus( int status )
{
switch (status)
{
case CV_BADSIZE_ERR: return CV_StsBadSize;
case CV_BADMEMBLOCK_ERR: return CV_StsBadMemBlock;
case CV_NULLPTR_ERR: return CV_StsNullPtr;
case CV_DIV_BY_ZERO_ERR: return CV_StsDivByZero;
case CV_BADSTEP_ERR: return CV_BadStep;
case CV_OUTOFMEM_ERR: return CV_StsNoMem;
case CV_BADARG_ERR: return CV_StsBadArg;
case CV_NOTDEFINED_ERR: return CV_StsError;
case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
case CV_NOTFOUND_ERR: return CV_StsObjectNotFound;
case CV_BADCONVERGENCE_ERR: return CV_StsNoConv;
case CV_BADDEPTH_ERR: return CV_BadDepth;
case CV_UNMATCHED_FORMATS_ERR: return CV_StsUnmatchedFormats;
case CV_UNSUPPORTED_COI_ERR: return CV_BadCOI;
case CV_UNSUPPORTED_CHANNELS_ERR: return CV_BadNumChannels;
case CV_BADFLAG_ERR: return CV_StsBadFlag;
case CV_BADRANGE_ERR: return CV_StsBadArg;
case CV_BADCOEF_ERR: return CV_StsBadArg;
case CV_BADFACTOR_ERR: return CV_StsBadArg;
case CV_BADPOINT_ERR: return CV_StsBadPoint;
case CV_BADSIZE_ERR: return cv::Error::StsBadSize;
case CV_BADMEMBLOCK_ERR: return cv::Error::StsBadMemBlock;
case CV_NULLPTR_ERR: return cv::Error::StsNullPtr;
case CV_DIV_BY_ZERO_ERR: return cv::Error::StsDivByZero;
case CV_BADSTEP_ERR: return cv::Error::BadStep;
case CV_OUTOFMEM_ERR: return cv::Error::StsNoMem;
case CV_BADARG_ERR: return cv::Error::StsBadArg;
case CV_NOTDEFINED_ERR: return cv::Error::StsError;
case CV_INPLACE_NOT_SUPPORTED_ERR: return cv::Error::StsInplaceNotSupported;
case CV_NOTFOUND_ERR: return cv::Error::StsObjectNotFound;
case CV_BADCONVERGENCE_ERR: return cv::Error::StsNoConv;
case CV_BADDEPTH_ERR: return cv::Error::BadDepth;
case CV_UNMATCHED_FORMATS_ERR: return cv::Error::StsUnmatchedFormats;
case CV_UNSUPPORTED_COI_ERR: return cv::Error::BadCOI;
case CV_UNSUPPORTED_CHANNELS_ERR: return cv::Error::BadNumChannels;
case CV_BADFLAG_ERR: return cv::Error::StsBadFlag;
case CV_BADRANGE_ERR: return cv::Error::StsBadArg;
case CV_BADCOEF_ERR: return cv::Error::StsBadArg;
case CV_BADFACTOR_ERR: return cv::Error::StsBadArg;
case CV_BADPOINT_ERR: return cv::Error::StsBadPoint;
default:
return CV_StsError;
return cv::Error::StsError;
}
}

@ -83,7 +83,7 @@ void KeyPoint::convert(const std::vector<KeyPoint>& keypoints, std::vector<Point
points2f[i] = keypoints[idx].pt;
else
{
CV_Error( CV_StsBadArg, "keypointIndexes has element < 0. TODO: process this case" );
CV_Error( cv::Error::StsBadArg, "keypointIndexes has element < 0. TODO: process this case" );
//points2f[i] = Point2f(-1, -1);
}
}

@ -559,7 +559,7 @@ void setSize( UMat& m, int _dims, const int* _sz,
m.step.p[i] = total;
int64 total1 = (int64)total*s;
if( (uint64)total1 != (size_t)total1 )
CV_Error( CV_StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
CV_Error( cv::Error::StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
total = (size_t)total1;
}
}
@ -995,16 +995,16 @@ UMat UMat::reshape(int new_cn, int new_rows) const
{
int total_size = total_width * rows;
if( !isContinuous() )
CV_Error( CV_BadStep,
CV_Error( cv::Error::BadStep,
"The matrix is not continuous, thus its number of rows can not be changed" );
if( (unsigned)new_rows > (unsigned)total_size )
CV_Error( CV_StsOutOfRange, "Bad new number of rows" );
CV_Error( cv::Error::StsOutOfRange, "Bad new number of rows" );
total_width = total_size / new_rows;
if( total_width * new_rows != total_size )
CV_Error( CV_StsBadArg, "The total number of matrix elements "
CV_Error( cv::Error::StsBadArg, "The total number of matrix elements "
"is not divisible by the new number of rows" );
hdr.rows = new_rows;
@ -1014,7 +1014,7 @@ UMat UMat::reshape(int new_cn, int new_rows) const
int new_width = total_width / new_cn;
if( new_width * new_cn != total_width )
CV_Error( CV_BadNumChannels,
CV_Error( cv::Error::BadNumChannels,
"The total width is not divisible by the new number of channels" );
hdr.dims = 2;
@ -1083,13 +1083,13 @@ UMat UMat::reshape(int _cn, int _newndims, const int* _newsz) const
else if (i < dims)
newsz_buf[i] = this->size[i];
else
CV_Error(CV_StsOutOfRange, "Copy dimension (which has zero size) is not present in source matrix");
CV_Error(cv::Error::StsOutOfRange, "Copy dimension (which has zero size) is not present in source matrix");
total_elem1 *= (size_t)newsz_buf[i];
}
if (total_elem1 != total_elem1_ref)
CV_Error(CV_StsUnmatchedSizes, "Requested and source matrices have different count of elements");
CV_Error(cv::Error::StsUnmatchedSizes, "Requested and source matrices have different count of elements");
UMat hdr = *this;
hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((_cn-1) << CV_CN_SHIFT);
@ -1098,7 +1098,7 @@ UMat UMat::reshape(int _cn, int _newndims, const int* _newsz) const
return hdr;
}
CV_Error(CV_StsNotImplemented, "Reshaping of n-dimensional non-continuous matrices is not supported yet");
CV_Error(cv::Error::StsNotImplemented, "Reshaping of n-dimensional non-continuous matrices is not supported yet");
}
Mat UMat::getMat(AccessFlag accessFlags) const

@ -1461,7 +1461,7 @@ typedef ArithmTestBase Normalize;
OCL_TEST_P(Normalize, Mat)
{
static int modes[] = { CV_MINMAX, CV_L2, CV_L1, CV_C };
static int modes[] = { NORM_MINMAX, NORM_L2, NORM_L1, NORM_INF };
for (int j = 0; j < test_loop_times; j++)
{

@ -3,6 +3,8 @@
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
#include "ref_reduce_arg.impl.hpp"
#include "opencv2/core/core_c.h"
#include <algorithm>
namespace opencv_test { namespace {
@ -634,7 +636,7 @@ static void inRange(const Mat& src, const Mat& lb, const Mat& rb, Mat& dst)
(const cv::bfloat16_t*)bptr, dptr, total, cn);
break;
default:
CV_Error(CV_StsUnsupportedFormat, "");
CV_Error(cv::Error::StsUnsupportedFormat, "");
}
}
}
@ -699,7 +701,7 @@ static void inRangeS(const Mat& src, const Scalar& lb, const Scalar& rb, Mat& ds
inRangeS_((const cv::bfloat16_t*)sptr, lbuf.f, rbuf.f, dptr, total, cn);
break;
default:
CV_Error(CV_StsUnsupportedFormat, "");
CV_Error(cv::Error::StsUnsupportedFormat, "");
}
}
}
@ -1781,7 +1783,7 @@ TEST(Core_ArithmMask, uninitialized)
}
Mat d1;
d.convertTo(d1, depth);
EXPECT_LE(cvtest::norm(c, d1, CV_C), DBL_EPSILON);
EXPECT_LE(cvtest::norm(c, d1, NORM_INF), DBL_EPSILON);
}
Mat_<uchar> tmpSrc(100,100);

@ -2,6 +2,7 @@
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
#include "opencv2/core/core_c.h"
namespace opencv_test { namespace {
@ -2114,8 +2115,8 @@ void Core_GraphScanTest::run( int )
cvReleaseGraphScanner( &scanner );
CV_TS_SEQ_CHECK_CONDITION( cvtest::norm(Mat(vtx_mask),CV_L1) == graph->active_count &&
cvtest::norm(Mat(edge_mask),CV_L1) == graph->edges->active_count,
CV_TS_SEQ_CHECK_CONDITION( cvtest::norm(Mat(vtx_mask),NORM_L1) == graph->active_count &&
cvtest::norm(Mat(edge_mask),NORM_L1) == graph->edges->active_count,
"Some vertices or edges have not been visited" );
update_progressbar();
}

@ -2,6 +2,7 @@
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
#include "opencv2/core/core_c.h"
namespace opencv_test { namespace {
@ -97,7 +98,7 @@ static void DFT_1D( const Mat& _src, Mat& _dst, int flags, const Mat& _wave=Mat(
}
}
else
CV_Error(CV_StsUnsupportedFormat, "");
CV_Error(cv::Error::StsUnsupportedFormat, "");
}
@ -878,7 +879,7 @@ protected:
{
cout << "actual:\n" << dst << endl << endl;
cout << "reference:\n" << dstz << endl << endl;
CV_Error(CV_StsError, "");
CV_Error(cv::Error::StsError, "");
}
}
}

@ -2,7 +2,7 @@
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
#include "opencv2/core/core_c.h"
#include <fstream>
namespace opencv_test { namespace {
@ -118,12 +118,12 @@ protected:
int cn = cvtest::randInt(rng) % 4 + 1;
Mat test_mat(cvtest::randInt(rng)%30+1, cvtest::randInt(rng)%30+1, CV_MAKETYPE(depth, cn));
rng0.fill(test_mat, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
rng0.fill(test_mat, RNG::UNIFORM, 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));
rng0.fill(test_mat_scale, RNG::UNIFORM, Scalar::all(-1), Scalar::all(1));
cv::multiply(test_mat, test_mat_scale, test_mat);
}
@ -136,12 +136,12 @@ protected:
};
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]));
rng0.fill(test_mat_nd, RNG::UNIFORM, 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));
rng0.fill(test_mat_scale, RNG::UNIFORM, Scalar::all(-1), Scalar::all(1));
cv::multiply(test_mat_nd, test_mat_scale, test_mat_nd);
}
@ -421,9 +421,9 @@ protected:
fs["g1"] >> og1;
CV_Assert( mi2.empty() );
CV_Assert( mv2.empty() );
CV_Assert( cvtest::norm(Mat(mi3), Mat(mi4), CV_C) == 0 );
CV_Assert( cvtest::norm(Mat(mi3), Mat(mi4), NORM_INF) == 0 );
CV_Assert( mv4.size() == 1 );
double n = cvtest::norm(mv3[0], mv4[0], CV_C);
double n = cvtest::norm(mv3[0], mv4[0], NORM_INF);
CV_Assert( vudt2.empty() );
CV_Assert( vudt3 == vudt4 );
CV_Assert( n == 0 );

@ -11,6 +11,7 @@
#include "opencv2/core/cuda.hpp"
#include "opencv2/core/bindings_utils.hpp"
#include "opencv2/core/core_c.h"
namespace opencv_test { namespace {
@ -322,7 +323,7 @@ TEST(Core_PCA, accuracy)
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;
PCA rPCA( rPoints, Mat(), PCA::DATA_AS_ROW, maxComponents ), cPCA;
// 1. check C++ PCA & ROW
Mat rPrjTestPoints = rPCA.project( rTestPoints );
@ -362,7 +363,7 @@ TEST(Core_PCA, accuracy)
// check pca eigenvalues
evalEps = 1e-5, evecEps = 5e-3;
err = cvtest::norm(rPCA.eigenvalues, subEval, NORM_L2 | NORM_RELATIVE);
EXPECT_LE(err , evalEps) << "pca.eigenvalues is incorrect (CV_PCA_DATA_AS_ROW)";
EXPECT_LE(err , evalEps) << "pca.eigenvalues is incorrect (PCA::DATA_AS_ROW)";
// check pca eigenvectors
for(int i = 0; i < subEvec.rows; i++)
{
@ -379,7 +380,7 @@ TEST(Core_PCA, accuracy)
double mval = 0; Point mloc;
minMaxLoc(tmp, 0, &mval, 0, &mloc);
EXPECT_LE(err, evecEps) << "pca.eigenvectors is incorrect (CV_PCA_DATA_AS_ROW) at " << i << " "
EXPECT_LE(err, evecEps) << "pca.eigenvectors is incorrect (PCA::DATA_AS_ROW) at " << i << " "
<< cv::format("max diff is %g at (i=%d, j=%d) (%g vs %g)\n",
mval, mloc.y, mloc.x, rPCA.eigenvectors.at<float>(mloc.y, mloc.x),
subEvec.at<float>(mloc.y, mloc.x))
@ -399,7 +400,7 @@ TEST(Core_PCA, accuracy)
err = cvtest::norm(rPrjTestPoints.row(i), prj, NORM_L2 | NORM_RELATIVE);
if (err < prjEps)
{
EXPECT_LE(err, prjEps) << "bad accuracy of project() (CV_PCA_DATA_AS_ROW)";
EXPECT_LE(err, prjEps) << "bad accuracy of project() (PCA::DATA_AS_ROW)";
continue;
}
// check pca backProject
@ -407,22 +408,22 @@ TEST(Core_PCA, accuracy)
err = cvtest::norm(rBackPrjTestPoints.row(i), backPrj, NORM_L2 | NORM_RELATIVE);
if (err > backPrjEps)
{
EXPECT_LE(err, backPrjEps) << "bad accuracy of backProject() (CV_PCA_DATA_AS_ROW)";
EXPECT_LE(err, backPrjEps) << "bad accuracy of backProject() (PCA::DATA_AS_ROW)";
continue;
}
}
// 2. check C++ PCA & COL
cPCA( rPoints.t(), Mat(), CV_PCA_DATA_AS_COL, maxComponents );
cPCA( rPoints.t(), Mat(), PCA::DATA_AS_COL, maxComponents );
diffPrjEps = 1, diffBackPrjEps = 1;
Mat ocvPrjTestPoints = cPCA.project(rTestPoints.t());
err = cvtest::norm(cv::abs(ocvPrjTestPoints), cv::abs(rPrjTestPoints.t()), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffPrjEps) << "bad accuracy of project() (CV_PCA_DATA_AS_COL)";
ASSERT_LE(err, diffPrjEps) << "bad accuracy of project() (PCA::DATA_AS_COL)";
err = cvtest::norm(cPCA.backProject(ocvPrjTestPoints), rBackPrjTestPoints.t(), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of backProject() (CV_PCA_DATA_AS_COL)";
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of backProject() (PCA::DATA_AS_COL)";
// 3. check C++ PCA w/retainedVariance
cPCA( rPoints.t(), Mat(), CV_PCA_DATA_AS_COL, retainedVariance );
cPCA( rPoints.t(), Mat(), PCA::DATA_AS_COL, retainedVariance );
diffPrjEps = 1, diffBackPrjEps = 1;
Mat rvPrjTestPoints = cPCA.project(rTestPoints.t());
@ -431,9 +432,9 @@ TEST(Core_PCA, accuracy)
else
err = cvtest::norm(cv::abs(rvPrjTestPoints), cv::abs(rPrjTestPoints.colRange(0,cPCA.eigenvectors.rows).t()), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffPrjEps) << "bad accuracy of project() (CV_PCA_DATA_AS_COL); retainedVariance=" << retainedVariance;
ASSERT_LE(err, diffPrjEps) << "bad accuracy of project() (PCA::DATA_AS_COL); retainedVariance=" << retainedVariance;
err = cvtest::norm(cPCA.backProject(rvPrjTestPoints), rBackPrjTestPoints.t(), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of backProject() (CV_PCA_DATA_AS_COL); retainedVariance=" << retainedVariance;
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of backProject() (PCA::DATA_AS_COL); retainedVariance=" << retainedVariance;
#ifdef CHECK_C
// 4. check C PCA & ROW
@ -447,14 +448,14 @@ TEST(Core_PCA, accuracy)
_prjTestPoints = cvMat(prjTestPoints);
_backPrjTestPoints = cvMat(backPrjTestPoints);
cvCalcPCA( &_points, &_avg, &_eval, &_evec, CV_PCA_DATA_AS_ROW );
cvCalcPCA( &_points, &_avg, &_eval, &_evec, PCA::DATA_AS_ROW );
cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints );
cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints );
err = cvtest::norm(prjTestPoints, rPrjTestPoints, NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffPrjEps) << "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_ROW)";
ASSERT_LE(err, diffPrjEps) << "bad accuracy of cvProjectPCA() (PCA::DATA_AS_ROW)";
err = cvtest::norm(backPrjTestPoints, rBackPrjTestPoints, NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_ROW)";
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of cvBackProjectPCA() (PCA::DATA_AS_ROW)";
// 5. check C PCA & COL
_points = cvMat(cPoints);
@ -465,14 +466,14 @@ TEST(Core_PCA, accuracy)
prjTestPoints = prjTestPoints.t(); _prjTestPoints = cvMat(prjTestPoints);
backPrjTestPoints = backPrjTestPoints.t(); _backPrjTestPoints = cvMat(backPrjTestPoints);
cvCalcPCA( &_points, &_avg, &_eval, &_evec, CV_PCA_DATA_AS_COL );
cvCalcPCA( &_points, &_avg, &_eval, &_evec, PCA::DATA_AS_COL );
cvProjectPCA( &_testPoints, &_avg, &_evec, &_prjTestPoints );
cvBackProjectPCA( &_prjTestPoints, &_avg, &_evec, &_backPrjTestPoints );
err = cvtest::norm(cv::abs(prjTestPoints), cv::abs(rPrjTestPoints.t()), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffPrjEps) << "bad accuracy of cvProjectPCA() (CV_PCA_DATA_AS_COL)";
ASSERT_LE(err, diffPrjEps) << "bad accuracy of cvProjectPCA() (PCA::DATA_AS_COL)";
err = cvtest::norm(backPrjTestPoints, rBackPrjTestPoints.t(), NORM_L2 | NORM_RELATIVE);
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of cvBackProjectPCA() (CV_PCA_DATA_AS_COL)";
ASSERT_LE(err, diffBackPrjEps) << "bad accuracy of cvBackProjectPCA() (PCA::DATA_AS_COL)";
#endif
// Test read and write
const std::string filename = cv::tempfile("PCA_store.yml");
@ -599,7 +600,7 @@ static void setValue(SparseMat& M, const int* idx, double value, RNG& rng)
else if( M.type() == CV_64F )
*(double*)ptr = value;
else
CV_Error(CV_StsUnsupportedFormat, "");
CV_Error(cv::Error::StsUnsupportedFormat, "");
}
#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12 || __GNUC__ == 13)
@ -651,8 +652,8 @@ void Core_ArrayOpTest::run( int /* start_from */)
MatND A(3, sz3, CV_32F), B(3, sz3, CV_16SC4);
CvMatND matA = cvMatND(A), matB = cvMatND(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));
rng.fill(A, RNG::UNIFORM, Scalar::all(-10), Scalar::all(10));
rng.fill(B, RNG::UNIFORM, Scalar::all(-10), Scalar::all(10));
int idx0[] = {3,4,5}, idx1[] = {0, 9, 7};
float val0 = 130;
@ -808,7 +809,7 @@ void Core_ArrayOpTest::run( int /* start_from */)
all_vals.resize(nz0);
all_vals2.resize(nz0);
Mat_<double> _all_vals(all_vals), _all_vals2(all_vals2);
rng.fill(_all_vals, CV_RAND_UNI, Scalar(-1000), Scalar(1000));
rng.fill(_all_vals, RNG::UNIFORM, Scalar(-1000), Scalar(1000));
if( depth == CV_32F )
{
Mat _all_vals_f;
@ -824,9 +825,9 @@ void Core_ArrayOpTest::run( int /* start_from */)
}
minMaxLoc(_all_vals, &min_val, &max_val);
double _norm0 = cv/*test*/::norm(_all_vals, CV_C);
double _norm1 = cv/*test*/::norm(_all_vals, CV_L1);
double _norm2 = cv/*test*/::norm(_all_vals, CV_L2);
double _norm0 = cv/*test*/::norm(_all_vals, NORM_INF);
double _norm1 = cv/*test*/::norm(_all_vals, NORM_L1);
double _norm2 = cv/*test*/::norm(_all_vals, NORM_L2);
for( i = 0; i < nz0; i++ )
{
@ -861,9 +862,9 @@ void Core_ArrayOpTest::run( int /* start_from */)
SparseMat M3; SparseMat(Md).convertTo(M3, Md.type(), 2);
int nz1 = (int)M.nzcount(), nz2 = (int)M3.nzcount();
double norm0 = cv/*test*/::norm(M, CV_C);
double norm1 = cv/*test*/::norm(M, CV_L1);
double norm2 = cv/*test*/::norm(M, CV_L2);
double norm0 = cv/*test*/::norm(M, NORM_INF);
double norm1 = cv/*test*/::norm(M, NORM_L1);
double norm2 = cv/*test*/::norm(M, NORM_L2);
double eps = depth == CV_32F ? FLT_EPSILON*100 : DBL_EPSILON*1000;
if( nz1 != nz0 || nz2 != nz0)

@ -10,6 +10,7 @@
#include <float.h>
#include <math.h>
#include "opencv2/core/softfloat.hpp"
#include "opencv2/core/core_c.h"
namespace opencv_test { namespace {
@ -2737,11 +2738,11 @@ TEST(Core_Invert, small)
cv::Mat b = a.t()*a;
cv::Mat c, i = Mat_<float>::eye(3, 3);
cv::invert(b, c, cv::DECOMP_LU); //std::cout << b*c << std::endl;
ASSERT_LT( cvtest::norm(b*c, i, CV_C), 0.1 );
ASSERT_LT( cvtest::norm(b*c, i, NORM_INF), 0.1 );
cv::invert(b, c, cv::DECOMP_SVD); //std::cout << b*c << std::endl;
ASSERT_LT( cvtest::norm(b*c, i, CV_C), 0.1 );
ASSERT_LT( cvtest::norm(b*c, i, NORM_INF), 0.1 );
cv::invert(b, c, cv::DECOMP_CHOLESKY); //std::cout << b*c << std::endl;
ASSERT_LT( cvtest::norm(b*c, i, CV_C), 0.1 );
ASSERT_LT( cvtest::norm(b*c, i, NORM_INF), 0.1 );
}
/////////////////////////////////////////////////////////////////////////////////////////////////////

@ -42,6 +42,7 @@
#include "test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp" // T-API like tests
#include "opencv2/core/core_c.h"
namespace opencv_test {
namespace {
@ -773,14 +774,14 @@ bool CV_OperationsTest::TestTemplateMat()
mvf.push_back(Mat_<float>::zeros(4, 3));
merge(mvf, mf2);
split(mf2, mvf2);
CV_Assert( cvtest::norm(mvf2[0], mvf[0], CV_C) == 0 &&
cvtest::norm(mvf2[1], mvf[1], CV_C) == 0 );
CV_Assert( cvtest::norm(mvf2[0], mvf[0], NORM_INF) == 0 &&
cvtest::norm(mvf2[1], mvf[1], NORM_INF) == 0 );
{
Mat a(2,2,CV_32F,1.f);
Mat b(1,2,CV_32F,1.f);
Mat c = (a*b.t()).t();
CV_Assert( cvtest::norm(c, CV_L1) == 4. );
CV_Assert( cvtest::norm(c, NORM_L1) == 4. );
}
bool badarg_catched = false;
@ -1130,13 +1131,13 @@ bool CV_OperationsTest::operations1()
Matx33f b(1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f);
Mat c;
cv::add(Mat::zeros(3, 3, CV_32F), b, c);
CV_Assert( cvtest::norm(b, c, CV_C) == 0 );
CV_Assert( cvtest::norm(b, c, NORM_INF) == 0 );
cv::add(Mat::zeros(3, 3, CV_64F), b, c, noArray(), c.type());
CV_Assert( cvtest::norm(b, c, CV_C) == 0 );
CV_Assert( cvtest::norm(b, c, NORM_INF) == 0 );
cv::add(Mat::zeros(6, 1, CV_64F), 1, c, noArray(), c.type());
CV_Assert( cvtest::norm(Matx61f(1.f, 1.f, 1.f, 1.f, 1.f, 1.f), c, CV_C) == 0 );
CV_Assert( cvtest::norm(Matx61f(1.f, 1.f, 1.f, 1.f, 1.f, 1.f), c, NORM_INF) == 0 );
vector<Point2f> pt2d(3);
vector<Point3d> pt3d(2);
@ -1182,11 +1183,11 @@ bool CV_OperationsTest::TestSVD()
Mat A = (Mat_<double>(3,4) << 1, 2, -1, 4, 2, 4, 3, 5, -1, -2, 6, 7);
Mat x;
SVD::solveZ(A,x);
if( cvtest::norm(A*x, CV_C) > FLT_EPSILON )
if( cvtest::norm(A*x, NORM_INF) > FLT_EPSILON )
throw test_excep();
SVD svd(A, SVD::FULL_UV);
if( cvtest::norm(A*svd.vt.row(3).t(), CV_C) > FLT_EPSILON )
if( cvtest::norm(A*svd.vt.row(3).t(), NORM_INF) > FLT_EPSILON )
throw test_excep();
Mat Dp(3,3,CV_32FC1);
@ -1210,11 +1211,11 @@ bool CV_OperationsTest::TestSVD()
W=decomp.w;
Mat I = Mat::eye(3, 3, CV_32F);
if( cvtest::norm(U*U.t(), I, CV_C) > FLT_EPSILON ||
cvtest::norm(Vt*Vt.t(), I, CV_C) > FLT_EPSILON ||
if( cvtest::norm(U*U.t(), I, NORM_INF) > FLT_EPSILON ||
cvtest::norm(Vt*Vt.t(), I, NORM_INF) > FLT_EPSILON ||
W.at<float>(2) < 0 || W.at<float>(1) < W.at<float>(2) ||
W.at<float>(0) < W.at<float>(1) ||
cvtest::norm(U*Mat::diag(W)*Vt, Q, CV_C) > FLT_EPSILON )
cvtest::norm(U*Mat::diag(W)*Vt, Q, NORM_INF) > FLT_EPSILON )
throw test_excep();
}
catch(const test_excep&)

@ -48,7 +48,7 @@ bool Core_RandTest::check_pdf(const Mat& hist, double scale,
sum += H[i];
CV_Assert( fabs(1./sum - scale) < FLT_EPSILON );
if( dist_type == CV_RAND_UNI )
if( dist_type == RNG::UNIFORM )
{
float scale0 = (float)(1./hsz);
for( i = 0; i < hsz; i++ )
@ -79,7 +79,7 @@ bool Core_RandTest::check_pdf(const Mat& hist, double scale,
}
realval = chi2;
double chi2_pval = chi2_p95(hsz - 1 - (dist_type == CV_RAND_NORMAL ? 2 : 0));
double chi2_pval = chi2_p95(hsz - 1 - (dist_type == RNG::NORMAL ? 2 : 0));
refval = chi2_pval*0.01;
return realval <= refval;
}
@ -108,7 +108,7 @@ void Core_RandTest::run( int )
int depth = cvtest::randInt(rng) % (CV_64F+1);
int c, cn = (cvtest::randInt(rng) % 4) + 1;
int type = CV_MAKETYPE(depth, cn);
int dist_type = cvtest::randInt(rng) % (CV_RAND_NORMAL+1);
int dist_type = cvtest::randInt(rng) % (RNG::NORMAL+1);
int i, k, SZ = N/cn;
Scalar A, B;
@ -116,18 +116,18 @@ void Core_RandTest::run( int )
if (depth == CV_64F)
eps = 1.e-7;
bool do_sphere_test = dist_type == CV_RAND_UNI;
bool do_sphere_test = dist_type == RNG::UNIFORM;
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;
bool fast_algo = dist_type == RNG::UNIFORM && depth < CV_32F;
for( c = 0; c < cn; c++ )
{
int a, b, hsz;
if( dist_type == CV_RAND_UNI )
if( dist_type == RNG::UNIFORM )
{
a = (int)(cvtest::randInt(rng) % (_ranges[depth][1] -
_ranges[depth][0])) + _ranges[depth][0];
@ -188,8 +188,8 @@ void Core_RandTest::run( int )
const uchar* data = arr[0].ptr();
int* H = hist[c].ptr<int>();
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 minVal = dist_type == RNG::UNIFORM ? A[c] : A[c] - B[c]*4;
double maxVal = dist_type == RNG::UNIFORM ? B[c] : A[c] + B[c]*4;
double scale = HSZ/(maxVal - minVal);
double delta = -minVal*scale;
@ -210,7 +210,7 @@ void Core_RandTest::run( int )
H[ival]++;
W[c]++;
}
else if( dist_type == CV_RAND_UNI )
else if( dist_type == RNG::UNIFORM )
{
if( (minVal <= val && val < maxVal) || (depth >= CV_32F && val == maxVal) )
{
@ -224,14 +224,14 @@ void Core_RandTest::run( int )
}
}
if( dist_type == CV_RAND_UNI && W[c] != SZ )
if( dist_type == RNG::UNIFORM && W[c] != SZ )
{
ts->printf( cvtest::TS::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( cvtest::TS::FAIL_INVALID_OUTPUT );
return;
}
if( dist_type == CV_RAND_NORMAL && W[c] < SZ*.90)
if( dist_type == RNG::NORMAL && W[c] < SZ*.90)
{
ts->printf( cvtest::TS::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);

@ -41,6 +41,7 @@
#include "test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp"
#include "opencv2/core/core_c.h"
using namespace opencv_test;
using namespace testing;

@ -438,7 +438,7 @@ void Image2BlobParams::blobRectsToImageRects(const std::vector<Rect> &rBlob, std
}
}
else
CV_Error(CV_StsBadArg, "Unknown padding mode");
CV_Error(cv::Error::StsBadArg, "Unknown padding mode");
}
}

@ -548,7 +548,7 @@ public:
{
// for Conv1d
if (group != 1)
CV_Error( CV_StsNotImplemented, " Grouped Conv1d or Depth-Wise Conv1d are not supported by "
CV_Error( cv::Error::StsNotImplemented, " Grouped Conv1d or Depth-Wise Conv1d are not supported by "
"TimVX Backend. Please try OpenCV Backend.");
tvConv = graph->CreateOperation<tim::vx::ops::Conv1d>(
tvConvWeightShape[2], tvPadType, (uint32_t)kernel_size[0],

@ -450,7 +450,7 @@ Ptr<FastConv> initFastConv(
}
}
else
CV_Error(CV_StsUnsupportedFormat, "Unknown convolution type.");
CV_Error(cv::Error::StsUnsupportedFormat, "Unknown convolution type.");
// store bias; append some zero's to make sure that
// we can always read MR elements starting from any valid index

@ -225,7 +225,7 @@ void Context::createInstance()
if (result != VK_SUCCESS)
{
CV_Error(CV_StsError, "Vulkan: vkEnumerateInstanceLayerProperties failed!");
CV_Error(cv::Error::StsError, "Vulkan: vkEnumerateInstanceLayerProperties failed!");
return;
}
@ -234,7 +234,7 @@ void Context::createInstance()
if (result != VK_SUCCESS)
{
CV_Error(CV_StsError, "Vulkan: vkEnumerateInstanceLayerProperties failed!");
CV_Error(cv::Error::StsError, "Vulkan: vkEnumerateInstanceLayerProperties failed!");
return;
}
@ -388,7 +388,7 @@ Context::Context()
vkEnumeratePhysicalDevices(kInstance, &deviceCount, NULL);
if (deviceCount == 0)
{
CV_Error(CV_StsError, "Vulkan Backend: could not find a device with vulkan support!");
CV_Error(cv::Error::StsError, "Vulkan Backend: could not find a device with vulkan support!");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
@ -442,7 +442,7 @@ Context::Context()
if (!cmdPoolPtr)
cmdPoolPtr = CommandPool::create(kQueue, kQueueFamilyIndex);
else
CV_Error(CV_StsError, "cmdPoolPtr has been created before!!");
CV_Error(cv::Error::StsError, "cmdPoolPtr has been created before!!");
pipelineFactoryPtr = PipelineFactory::create();
}
@ -884,4 +884,4 @@ bool isAvailable()
#endif // HAVE_VULKAN
}}} // namespace cv::dnn::vkcom
}}} // namespace cv::dnn::vkcom

@ -244,7 +244,7 @@ bool OpConv::computeGroupCount()
group_z_ = 1;
}
else
CV_Error(CV_StsNotImplemented, "shader type is not supported at compute GroupCount.");
CV_Error(cv::Error::StsNotImplemented, "shader type is not supported at compute GroupCount.");
CV_Assert(group_x_ <= MAX_GROUP_COUNT_X);
CV_Assert(group_y_ <= MAX_GROUP_COUNT_Y);

@ -182,7 +182,7 @@ bool OpNary::computeGroupCount()
}
else
{
CV_Error(CV_StsNotImplemented, "shader type is not supported at compute GroupCount.");
CV_Error(cv::Error::StsNotImplemented, "shader type is not supported at compute GroupCount.");
}
CV_Assert(group_x_ <= MAX_GROUP_COUNT_X);

@ -279,7 +279,7 @@ Ptr<Pipeline> PipelineFactory::getPipeline(const std::string& key, const std::ve
// retrieve spv from SPVMaps with given key
auto iterSPV = SPVMaps.find(key);
if (iterSPV == SPVMaps.end())
CV_Error(CV_StsError, "Can not create SPV with the given name:"+key+"!");
CV_Error(cv::Error::StsError, "Can not create SPV with the given name:"+key+"!");
const uint32_t* spv = iterSPV->second.first;
size_t length = iterSPV->second.second;
@ -292,7 +292,7 @@ Ptr<Pipeline> PipelineFactory::getPipeline(const std::string& key, const std::ve
}
else
{
CV_Error(CV_StsError, "Can not Created the VkPipeline "+key);
CV_Error(cv::Error::StsError, "Can not Created the VkPipeline "+key);
}
return pipeline;

@ -209,7 +209,7 @@ public class FlannBasedDescriptorMatcherTest extends OpenCVTestCase {
try {
matcher.clone();
fail("Expected CvException (CV_StsNotImplemented)");
fail("Expected CvException (cv::Error::StsNotImplemented)");
} catch (CvException cverr) {
// expected
}

@ -44,9 +44,9 @@
*/
#include "precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include <limits>
#include "../3rdparty/mscr/chi_table.h"
#include "opencv2/core/core_c.h"
namespace cv
{

@ -10,7 +10,6 @@
#include <opencv2/gapi/own/assert.hpp>
#include <opencv2/core/traits.hpp>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/gapi/core.hpp>
#include <opencv2/gapi/imgproc.hpp>

@ -57,7 +57,7 @@
#endif
#include "opencv2/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/core/core_c.h"
#include <stdlib.h>
#include <stdio.h>

@ -1088,17 +1088,17 @@ void cv::imshow(const String& winname, const ogl::Texture2D& _tex)
void setOpenGLDrawCallbackImpl(const char*, CvOpenGlDrawCallback, void*)
{
CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support");
CV_Error(cv::Error::OpenGlNotSupported, "The library is compiled without OpenGL support");
}
void setOpenGLContextImpl(const char*)
{
CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support");
CV_Error(cv::Error::OpenGlNotSupported, "The library is compiled without OpenGL support");
}
void updateWindowImpl(const char*)
{
CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support");
CV_Error(cv::Error::OpenGlNotSupported, "The library is compiled without OpenGL support");
}
#endif // !HAVE_OPENGL
@ -1112,52 +1112,52 @@ static const char* NO_QT_ERR_MSG = "The library is compiled without QT support";
cv::QtFont cv::fontQt(const String&, int, Scalar, int, int, int)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::addText( const Mat&, const String&, Point, const QtFont&)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::addText(const Mat&, const String&, Point, const String&, int, Scalar, int, int, int)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::displayStatusBar(const String&, const String&, int)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::displayOverlay(const String&, const String&, int )
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
int cv::startLoop(int (*)(int argc, char *argv[]), int , char**)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::stopLoop()
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::saveWindowParameters(const String&)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
void cv::loadWindowParameters(const String&)
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
int cv::createButton(const String&, ButtonCallback, void*, int , bool )
{
CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG);
CV_Error(cv::Error::StsNotImplemented, NO_QT_ERR_MSG);
}
#endif // !HAVE_QT

@ -136,7 +136,7 @@ void cv::addText( const Mat& img, const String& text, Point org, const QtFont& f
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
CvMat _img = cvMat(img);
QMetaObject::invokeMethod(
@ -160,7 +160,7 @@ void cv::addText( const Mat& img, const String& text, Point org, const String& n
void cv::displayStatusBar(const String& name, const String& text, int delayms)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"displayStatusBar",
@ -174,7 +174,7 @@ void cv::displayStatusBar(const String& name, const String& text, int delayms)
void cv::displayOverlay(const String& name, const String& text, int delayms)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"displayInfo",
@ -202,7 +202,7 @@ void cv::stopLoop()
void cv::saveWindowParameters(const String& windowName)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"saveWindowParameters",
@ -213,7 +213,7 @@ void cv::saveWindowParameters(const String& windowName)
void cv::loadWindowParameters(const String& windowName)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"loadWindowParameters",
@ -225,7 +225,7 @@ void cv::loadWindowParameters(const String& windowName)
int cv::createButton(const String& button_name, ButtonCallback on_change, void* userdata, int button_type , bool initial_button_state )
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"addButton",
@ -242,7 +242,7 @@ int cv::createButton(const String& button_name, ButtonCallback on_change, void*
double cvGetRatioWindow_QT(const char* name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
double result = -1;
QMetaObject::invokeMethod(guiMainThread,
@ -256,7 +256,7 @@ double cvGetRatioWindow_QT(const char* name)
double cvGetPropVisible_QT(const char* name) {
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
double result = 0;
@ -273,7 +273,7 @@ void cvSetRatioWindow_QT(const char* name,double prop_value)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"setRatioWindow",
@ -285,7 +285,7 @@ void cvSetRatioWindow_QT(const char* name,double prop_value)
double cvGetPropWindow_QT(const char* name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
double result = -1;
QMetaObject::invokeMethod(guiMainThread,
@ -301,7 +301,7 @@ double cvGetPropWindow_QT(const char* name)
void cvSetPropWindow_QT(const char* name,double prop_value)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"setPropWindow",
@ -326,7 +326,7 @@ void setWindowTitle_QT(const String& winname, const String& title)
void cvSetModeWindow_QT(const char* name, double prop_value)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"toggleFullScreen",
@ -338,7 +338,7 @@ void cvSetModeWindow_QT(const char* name, double prop_value)
CvRect cvGetWindowRect_QT(const char* name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
CvRect result = cvRect(-1, -1, -1, -1);
@ -354,7 +354,7 @@ CvRect cvGetWindowRect_QT(const char* name)
double cvGetModeWindow_QT(const char* name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
double result = -1;
@ -501,7 +501,7 @@ static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char*
QPointer<CvWindow> w = icvFindWindowByName(nameWinQt);
if (!w)
CV_Error(CV_StsNullPtr, "NULL window handler");
CV_Error(cv::Error::StsNullPtr, "NULL window handler");
if (w->param_gui_mode == cv::WINDOW_GUI_NORMAL)
return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
@ -576,7 +576,7 @@ int namedWindowImpl(const char* name, int flags)
void destroyWindowImpl(const char* name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"destroyWindow",
@ -599,7 +599,7 @@ void destroyAllWindowsImpl()
void moveWindowImpl(const char* name, int x, int y)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"moveWindow",
autoBlockingConnection(),
@ -611,7 +611,7 @@ void moveWindowImpl(const char* name, int x, int y)
void resizeWindowImpl(const char* name, int width, int height)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"resizeWindow",
autoBlockingConnection(),
@ -624,7 +624,7 @@ void resizeWindowImpl(const char* name, int width, int height)
int createTrackbar2Impl(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"addSlider2",
@ -687,7 +687,7 @@ void setMouseCallbackImpl(const char* window_name, CvMouseCallback on_mouse, voi
QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
if (!w)
CV_Error(CV_StsNullPtr, "NULL window handler");
CV_Error(cv::Error::StsNullPtr, "NULL window handler");
w->setMouseCallBack(on_mouse, param);
@ -717,7 +717,7 @@ void showImageImpl(const char* name, const CvArr* arr)
void setOpenGLDrawCallbackImpl(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"setOpenGlDrawCallback",
@ -731,7 +731,7 @@ void setOpenGLDrawCallbackImpl(const char* window_name, CvOpenGlDrawCallback cal
void setOpenGLContextImpl(const char* window_name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"setOpenGlContext",
@ -743,7 +743,7 @@ void setOpenGLContextImpl(const char* window_name)
void updateWindowImpl(const char* window_name)
{
if (!guiMainThread)
CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
CV_Error( cv::Error::StsNullPtr, "NULL guiReceiver (please create a window)" );
QMetaObject::invokeMethod(guiMainThread,
"updateWindow",
@ -973,7 +973,7 @@ void GuiReceiver::toggleFullScreen(QString name, double arg2)
void GuiReceiver::createWindow(QString name, int flags)
{
if (!qApp)
CV_Error(CV_StsNullPtr, "NULL session handler" );
CV_Error(cv::Error::StsNullPtr, "NULL session handler" );
// Check the name in the storage
if (icvFindWindowByName(name.toLatin1().data()))
@ -1064,7 +1064,7 @@ void GuiReceiver::destroyWindow(QString name)
void GuiReceiver::destroyAllWindow()
{
if (!qApp)
CV_Error(CV_StsNullPtr, "NULL session handler" );
CV_Error(cv::Error::StsNullPtr, "NULL session handler" );
if (multiThreads)
{
@ -1193,7 +1193,7 @@ void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value,
return;
if (count <= 0) //count is the max value of the slider, so must be bigger than 0
CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
CV_Error(cv::Error::StsNullPtr, "Max value of the slider must be bigger than 0" );
CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
}
@ -1223,10 +1223,10 @@ void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value,
return;
if (!value)
CV_Error(CV_StsNullPtr, "NULL value pointer" );
CV_Error(cv::Error::StsNullPtr, "NULL value pointer" );
if (count <= 0) //count is the max value of the slider, so must be bigger than 0
CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
CV_Error(cv::Error::StsNullPtr, "Max value of the slider must be bigger than 0" );
CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
}
@ -1640,7 +1640,7 @@ CvWindow::CvWindow(QString name, int arg2)
//3: my view
#ifndef HAVE_QT_OPENGL
if (arg2 & cv::WINDOW_OPENGL)
CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
CV_Error( cv::Error::OpenGlNotSupported, "Library was built without OpenGL support" );
mode_display = CV_MODE_NORMAL;
#else
mode_display = arg2 & cv::WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
@ -2599,19 +2599,19 @@ void DefaultViewPort::startDisplayInfo(QString text, int delayms)
void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
{
CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
CV_Error(cv::Error::OpenGlNotSupported, "Window doesn't support OpenGL");
}
void DefaultViewPort::makeCurrentOpenGlContext()
{
CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
CV_Error(cv::Error::OpenGlNotSupported, "Window doesn't support OpenGL");
}
void DefaultViewPort::updateGl()
{
CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
CV_Error(cv::Error::OpenGlNotSupported, "Window doesn't support OpenGL");
}
@ -2714,7 +2714,7 @@ void DefaultViewPort::saveView()
return;
}
CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
CV_Error(cv::Error::StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
}
}

@ -284,14 +284,11 @@ void resizeWindowImpl( const char* name, int width, int height)
void moveWindowImpl( const char* name, int x, int y)
{
CV_FUNCNAME("moveWindowImpl");
__BEGIN__;
NSAutoreleasePool* localpool1 = [[NSAutoreleasePool alloc] init];
CVWindow *window = nil;
if(name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL window name" );
CV_Error( cv::Error::StsNullPtr, "NULL window name" );
//cout << "moveWindowImpl"<< endl;
window = cvGetWindow(name);
if(window) {
@ -305,8 +302,6 @@ void moveWindowImpl( const char* name, int x, int y)
}
}
[localpool1 drain];
__END__;
}
static int cocoa_CreateTrackbar (const char* trackbar_name,
@ -314,19 +309,17 @@ static int cocoa_CreateTrackbar (const char* trackbar_name,
int* val, int count,
CvTrackbarCallback on_notify)
{
CV_FUNCNAME("cocoa_CreateTrackbar");
int result = 0;
CVWindow *window = nil;
NSAutoreleasePool* localpool2 = nil;
__BEGIN__;
if (localpool2 != nil) [localpool2 drain];
localpool2 = [[NSAutoreleasePool alloc] init];
if(window_name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL window name" );
CV_Error( cv::Error::StsNullPtr, "NULL window name" );
//cout << "cocoa_CreateTrackbar" << endl ;
window = cvGetWindow(window_name);
@ -338,7 +331,6 @@ static int cocoa_CreateTrackbar (const char* trackbar_name,
result = 1;
}
[localpool2 drain];
__END__;
return result;
}
@ -367,18 +359,15 @@ int createTrackbar2Impl(const char* trackbar_name,
void setMouseCallbackImpl( const char* name, CvMouseCallback function, void* info)
{
CV_FUNCNAME("setMouseCallbackImpl");
CVWindow *window = nil;
NSAutoreleasePool* localpool3 = nil;
__BEGIN__;
//cout << "setMouseCallbackImpl" << endl;
if (localpool3 != nil) [localpool3 drain];
localpool3 = [[NSAutoreleasePool alloc] init];
if(name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL window name" );
CV_Error( cv::Error::StsNullPtr, "NULL window name" );
window = cvGetWindow(name);
if(window) {
@ -386,22 +375,16 @@ void setMouseCallbackImpl( const char* name, CvMouseCallback function, void* inf
[window setMouseParam:info];
}
[localpool3 drain];
__END__;
}
int getTrackbarPosImpl( const char* trackbar_name, const char* window_name )
{
CV_FUNCNAME("getTrackbarPosImpl");
CVWindow *window = nil;
int pos = -1;
NSAutoreleasePool* localpool4 = nil;
__BEGIN__;
//cout << "getTrackbarPosImpl" << endl;
if(trackbar_name == NULL || window_name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
CV_Error( cv::Error::StsNullPtr, "NULL trackbar or window name" );
if (localpool4 != nil) [localpool4 drain];
localpool4 = [[NSAutoreleasePool alloc] init];
@ -414,25 +397,21 @@ void setMouseCallbackImpl( const char* name, CvMouseCallback function, void* inf
}
}
[localpool4 drain];
__END__;
return pos;
}
void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int pos)
{
CV_FUNCNAME("setTrackbarPosImpl");
CVWindow *window = nil;
CVSlider *slider = nil;
NSAutoreleasePool* localpool5 = nil;
__BEGIN__;
//cout << "setTrackbarPosImpl" << endl;
if(trackbar_name == NULL || window_name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
CV_Error( cv::Error::StsNullPtr, "NULL trackbar or window name" );
if(pos < 0)
CV_ERROR( CV_StsOutOfRange, "Bad trackbar maximal value" );
CV_Error( cv::Error::StsOutOfRange, "Bad trackbar maximal value" );
if (localpool5 != nil) [localpool5 drain];
localpool5 = [[NSAutoreleasePool alloc] init];
@ -448,22 +427,17 @@ void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int
}
}
[localpool5 drain];
__END__;
}
void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval)
{
CV_FUNCNAME("setTrackbarMaxImpl");
CVWindow *window = nil;
CVSlider *slider = nil;
NSAutoreleasePool* localpool5 = nil;
__BEGIN__;
//cout << "setTrackbarPosImpl" << endl;
if(trackbar_name == NULL || window_name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
CV_Error( cv::Error::StsNullPtr, "NULL trackbar or window name" );
if (localpool5 != nil) [localpool5 drain];
localpool5 = [[NSAutoreleasePool alloc] init];
@ -480,21 +454,16 @@ void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int
}
}
[localpool5 drain];
__END__;
}
void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval)
{
CV_FUNCNAME("setTrackbarMinImpl");
CVWindow *window = nil;
CVSlider *slider = nil;
NSAutoreleasePool* localpool5 = nil;
__BEGIN__;
if(trackbar_name == NULL || window_name == NULL)
CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" );
CV_Error( cv::Error::StsNullPtr, "NULL trackbar or window name" );
if (localpool5 != nil) [localpool5 drain];
localpool5 = [[NSAutoreleasePool alloc] init];
@ -511,8 +480,6 @@ void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int
}
}
[localpool5 drain];
__END__;
}
int namedWindowImpl( const char* name, int flags )
@ -616,18 +583,15 @@ CvRect cvGetWindowRect_COCOA( const char* name )
CvRect result = cvRect(-1, -1, -1, -1);
CVWindow *window = nil;
CV_FUNCNAME( "cvGetWindowRect_COCOA" );
__BEGIN__;
if( name == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL name string" );
CV_Error( cv::Error::StsNullPtr, "NULL name string" );
}
window = cvGetWindow( name );
if ( window == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
} else {
NSRect rect = [window frame];
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_6
@ -638,8 +602,6 @@ CvRect cvGetWindowRect_COCOA( const char* name )
NSSize sz = [[[window contentView] image] size];
result = cvRect(pt.x, pt.y, sz.width, sz.height);
}
__END__;
return result;
}
@ -648,23 +610,18 @@ double cvGetModeWindow_COCOA( const char* name )
double result = -1;
CVWindow *window = nil;
CV_FUNCNAME( "cvGetModeWindow_COCOA" );
__BEGIN__;
if( name == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL name string" );
CV_Error( cv::Error::StsNullPtr, "NULL name string" );
}
window = cvGetWindow( name );
if ( window == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
}
result = window.status;
__END__;
return result;
}
@ -678,18 +635,15 @@ void cvSetModeWindow_COCOA( const char* name, double prop_value )
NSAutoreleasePool* localpool = nil;
CV_FUNCNAME( "cvSetModeWindow_COCOA" );
__BEGIN__;
if( name == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL name string" );
CV_Error( cv::Error::StsNullPtr, "NULL name string" );
}
window = cvGetWindow(name);
if ( window == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
}
if ( [window autosize] )
@ -737,8 +691,6 @@ void cvSetModeWindow_COCOA( const char* name, double prop_value )
}
#endif
[localpool drain];
__END__;
}
double cvGetPropVisible_COCOA(const char* name)
@ -746,23 +698,19 @@ double cvGetPropVisible_COCOA(const char* name)
double result = -1;
CVWindow* window = nil;
CV_FUNCNAME("cvGetPropVisible_COCOA");
__BEGIN__;
if (name == NULL)
{
CV_ERROR(CV_StsNullPtr, "NULL name string");
CV_Error(cv::Error::StsNullPtr, "NULL name string");
}
window = cvGetWindow(name);
if (window == NULL)
{
CV_ERROR(CV_StsNullPtr, "NULL window");
CV_Error(cv::Error::StsNullPtr, "NULL window");
}
result = window.isVisible ? 1 : 0;
__END__;
return result;
}
@ -771,23 +719,18 @@ double cvGetPropTopmost_COCOA(const char* name)
double result = -1;
CVWindow* window = nil;
CV_FUNCNAME("cvGetPropTopmost_COCOA");
__BEGIN__;
if (name == NULL)
{
CV_ERROR(CV_StsNullPtr, "NULL name string");
CV_Error(cv::Error::StsNullPtr, "NULL name string");
}
window = cvGetWindow(name);
if (window == NULL)
{
CV_ERROR(CV_StsNullPtr, "NULL window");
CV_Error(cv::Error::StsNullPtr, "NULL window");
}
result = (window.level == NSStatusWindowLevel) ? 1 : 0;
__END__;
return result;
}
@ -795,23 +738,21 @@ void cvSetPropTopmost_COCOA( const char* name, const bool topmost )
{
CVWindow *window = nil;
NSAutoreleasePool* localpool = nil;
CV_FUNCNAME( "cvSetPropTopmost_COCOA" );
__BEGIN__;
if( name == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL name string" );
CV_Error( cv::Error::StsNullPtr, "NULL name string" );
}
window = cvGetWindow(name);
if ( window == NULL )
{
CV_ERROR( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
}
if (([window styleMask] & NSFullScreenWindowMask))
{
EXIT;
return;
}
localpool = [[NSAutoreleasePool alloc] init];
@ -825,7 +766,6 @@ void cvSetPropTopmost_COCOA( const char* name, const bool topmost )
[window makeKeyAndOrderFront:nil];
}
[localpool drain];
__END__;
}
void setWindowTitle_COCOA(const cv::String& winname, const cv::String& title)

@ -737,7 +737,7 @@ CvRect cvGetWindowRect_GTK(const char* name)
CV_LOCK_MUTEX();
const auto window = icvFindWindowByName(name);
if (!window)
CV_Error( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
return cvRect(getImageRect_(window));
}
@ -779,7 +779,7 @@ double cvGetModeWindow_GTK(const char* name)//YV
CV_LOCK_MUTEX();
const auto window = icvFindWindowByName(name);
if (!window)
CV_Error( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
double result = window->status;
return result;
@ -794,7 +794,7 @@ void cvSetModeWindow_GTK( const char* name, double prop_value)//Yannick Verdie
const auto window = icvFindWindowByName(name);
if (!window)
CV_Error( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
setModeWindow_(window, (int)prop_value);
}
@ -910,11 +910,11 @@ namespace
// Try double-buffered visual
glconfig = gdk_gl_config_new_by_mode((GdkGLConfigMode)(GDK_GL_MODE_RGB | GDK_GL_MODE_DEPTH | GDK_GL_MODE_DOUBLE));
if (!glconfig)
CV_Error( CV_OpenGlApiCallError, "Can't Create A GL Device Context" );
CV_Error( cv::Error::OpenGlApiCallError, "Can't Create A GL Device Context" );
// Set OpenGL-capability to the widget
if (!gtk_widget_set_gl_capability(window->widget, glconfig, NULL, TRUE, GDK_GL_RGBA_TYPE))
CV_Error( CV_OpenGlApiCallError, "Can't Create A GL Device Context" );
CV_Error( cv::Error::OpenGlApiCallError, "Can't Create A GL Device Context" );
window->useGl = true;
}
@ -925,7 +925,7 @@ namespace
GdkGLDrawable* gldrawable = gtk_widget_get_gl_drawable(window->widget);
if (!gdk_gl_drawable_gl_begin (gldrawable, glcontext))
CV_Error( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
CV_Error( cv::Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
glViewport(0, 0, gtk_widget_get_allocated_width(window->widget), gtk_widget_get_allocated_height(window->widget));
@ -1044,7 +1044,7 @@ static std::shared_ptr<CvWindow> namedWindow_(const std::string& name, int flags
#ifndef HAVE_OPENGL
if (flags & cv::WINDOW_OPENGL)
CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
CV_Error( cv::Error::OpenGlNotSupported, "Library was built without OpenGL support" );
#else
if (flags & cv::WINDOW_OPENGL)
createGlContext(window);
@ -1125,16 +1125,16 @@ void setOpenGLContextImpl(const char* name)
auto window = icvFindWindowByName(name);
if (!window)
CV_Error( CV_StsNullPtr, "NULL window" );
CV_Error( cv::Error::StsNullPtr, "NULL window" );
if (!window->useGl)
CV_Error( CV_OpenGlNotSupported, "Window doesn't support OpenGL" );
CV_Error( cv::Error::OpenGlNotSupported, "Window doesn't support OpenGL" );
glcontext = gtk_widget_get_gl_context(window->widget);
gldrawable = gtk_widget_get_gl_drawable(window->widget);
if (!gdk_gl_drawable_make_current(gldrawable, glcontext))
CV_Error( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
CV_Error( cv::Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context" );
}
void updateWindowImpl(const char* name)
@ -1162,7 +1162,7 @@ void setOpenGLDrawCallbackImpl(const char* name, CvOpenGlDrawCallback callback,
return;
if (!window->useGl)
CV_Error( CV_OpenGlNotSupported, "Window was created without OpenGL context" );
CV_Error( cv::Error::OpenGlNotSupported, "Window was created without OpenGL context" );
window->glDrawCallback = callback;
window->glDrawData = userdata;
@ -1376,7 +1376,7 @@ icvCreateTrackbar( const char* trackbar_name, const char* window_name,
CV_Assert(trackbar_name && "NULL trackbar name");
if( count <= 0 )
CV_Error( CV_StsOutOfRange, "Bad trackbar maximal value" );
CV_Error( cv::Error::StsOutOfRange, "Bad trackbar maximal value" );
CV_LOCK_MUTEX();
@ -1539,7 +1539,7 @@ void setTrackbarPosImpl( const char* trackbar_name, const char* window_name, int
const auto trackbar = icvFindTrackbarByName(window, trackbar_name);
if (!trackbar)
{
CV_Error( CV_StsNullPtr, "No trackbar found" );
CV_Error( cv::Error::StsNullPtr, "No trackbar found" );
}
return setTrackbarPos_(trackbar, pos);

@ -36,12 +36,12 @@
#define CV_WINRT_NO_GUI_ERROR( funcname ) \
{ \
cvError( CV_StsNotImplemented, funcname, \
cvError( cv::Error::StsNotImplemented, funcname, \
"The function is not implemented. ", \
__FILE__, __LINE__ ); \
}
#define CV_ERROR( Code, Msg ) \
#define CV_Error( Code, Msg ) \
{ \
cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \
};
@ -65,7 +65,7 @@ void showImageImpl(const char* name, const CvArr* arr)
CvMat stub, *image;
if (!name)
CV_ERROR(CV_StsNullPtr, "NULL name");
CV_Error(cv::Error::StsNullPtr, "NULL name");
CvWindow* window = HighguiBridge::getInstance().namedWindow(name);
@ -89,7 +89,7 @@ int namedWindowImpl(const char* name, int flags)
CV_FUNCNAME("namedWindowImpl");
if (!name)
CV_ERROR(CV_StsNullPtr, "NULL name");
CV_Error(cv::Error::StsNullPtr, "NULL name");
HighguiBridge::getInstance().namedWindow(name);
@ -101,7 +101,7 @@ void destroyWindowImpl(const char* name)
CV_FUNCNAME("destroyWindowImpl");
if (!name)
CV_ERROR(CV_StsNullPtr, "NULL name string");
CV_Error(cv::Error::StsNullPtr, "NULL name string");
HighguiBridge::getInstance().destroyWindow(name);
}
@ -119,16 +119,16 @@ int createTrackbar2Impl(const char* trackbar_name, const char* window_name,
int pos = 0;
if (!window_name || !trackbar_name)
CV_ERROR(CV_StsNullPtr, "NULL window or trackbar name");
CV_Error(cv::Error::StsNullPtr, "NULL window or trackbar name");
if (count < 0)
CV_ERROR(CV_StsOutOfRange, "Bad trackbar max value");
CV_Error(cv::Error::StsOutOfRange, "Bad trackbar max value");
CvWindow* window = HighguiBridge::getInstance().namedWindow(window_name);
if (!window)
{
CV_ERROR(CV_StsNullPtr, "NULL window");
CV_Error(cv::Error::StsNullPtr, "NULL window");
}
window->createSlider(trackbar_name, val, count, on_notify, userdata);
@ -143,7 +143,7 @@ void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int
CvTrackbar* trackbar = 0;
if (trackbar_name == 0 || window_name == 0)
CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
CV_Error(cv::Error::StsNullPtr, "NULL trackbar or window name");
CvWindow* window = HighguiBridge::getInstance().findWindowByName(window_name);
if (window)
@ -160,7 +160,7 @@ void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int
if (maxval >= 0)
{
if (trackbar_name == 0 || window_name == 0)
CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
CV_Error(cv::Error::StsNullPtr, "NULL trackbar or window name");
CvTrackbar* trackbar = HighguiBridge::getInstance().findTrackbarByName(trackbar_name, window_name);
@ -176,7 +176,7 @@ void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int
if (minval >= 0)
{
if (trackbar_name == 0 || window_name == 0)
CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
CV_Error(cv::Error::StsNullPtr, "NULL trackbar or window name");
CvTrackbar* trackbar = HighguiBridge::getInstance().findTrackbarByName(trackbar_name, window_name);
@ -192,7 +192,7 @@ int getTrackbarPosImpl(const char* trackbar_name, const char* window_name)
CV_FUNCNAME("getTrackbarPosImpl");
if (trackbar_name == 0 || window_name == 0)
CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name");
CV_Error(cv::Error::StsNullPtr, "NULL trackbar or window name");
CvTrackbar* trackbar = HighguiBridge::getInstance().findTrackbarByName(trackbar_name, window_name);
@ -229,7 +229,7 @@ void setMouseCallbackImpl(const char* window_name, CvMouseCallback on_mouse, voi
CV_FUNCNAME("setMouseCallbackImpl");
if (!window_name)
CV_ERROR(CV_StsNullPtr, "NULL window name");
CV_Error(cv::Error::StsNullPtr, "NULL window name");
CvWindow* window = HighguiBridge::getInstance().findWindowByName(window_name);
if (!window)
@ -256,5 +256,5 @@ void cvSetModeWindow_WinRT(const char* name, double prop_value) {
double cvGetModeWindow_WinRT(const char* name) {
CV_WINRT_NO_GUI_ERROR("cvGetModeWindow");
return CV_StsNotImplemented;
return cv::Error::StsNotImplemented;
}

@ -6,7 +6,6 @@
#include "opencv2/ts.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc/imgproc_c.h"
namespace cv {

@ -1,48 +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_IMGPROC_IMGPROC_C_H
#define OPENCV_IMGPROC_IMGPROC_C_H
#include "opencv2/imgproc/types_c.h"
#endif

@ -1,48 +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_IMGPROC_TYPES_C_H
#define OPENCV_IMGPROC_TYPES_C_H
#include "opencv2/core/core_c.h"
#endif

@ -2,7 +2,6 @@
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "perf_precomp.hpp"
#include "opencv2/imgproc/types_c.h"
namespace opencv_test {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save