All tests writing temporary files are updated to use cv::tempfile() function

This commit is contained in:
Andrey Kamaev 2012-06-25 11:24:06 +00:00
parent ec3a7665b0
commit d9c74f63e1
26 changed files with 500 additions and 438 deletions

View File

@ -54,7 +54,7 @@ protected:
Mat intrinsic_matrix_; Mat intrinsic_matrix_;
Mat distortion_coeffs_; Mat distortion_coeffs_;
Size image_size_; Size image_size_;
void run(int); void run(int);
void generateIntrinsicParams(); void generateIntrinsicParams();
}; };
@ -66,14 +66,14 @@ int calcDistance(const vector<Point2f>& set1, const vector<Point2f>& set2, doubl
{ {
return 0; return 0;
} }
std::vector<int> indices; std::vector<int> indices;
double sum_dist = 0.0; double sum_dist = 0.0;
for(size_t i = 0; i < set1.size(); i++) for(size_t i = 0; i < set1.size(); i++)
{ {
double min_dist = std::numeric_limits<double>::max(); double min_dist = std::numeric_limits<double>::max();
int min_idx = -1; int min_idx = -1;
for(int j = 0; j < (int)set2.size(); j++) for(int j = 0; j < (int)set2.size(); j++)
{ {
double dist = norm(set1[i] - set2[j]); double dist = norm(set1[i] - set2[j]);
@ -83,33 +83,33 @@ int calcDistance(const vector<Point2f>& set1, const vector<Point2f>& set2, doubl
min_dist = dist; min_dist = dist;
} }
} }
// check validity of min_idx // check validity of min_idx
if(min_idx == -1) if(min_idx == -1)
{ {
return 0; return 0;
} }
std::vector<int>::iterator it = std::find(indices.begin(), indices.end(), min_idx); std::vector<int>::iterator it = std::find(indices.begin(), indices.end(), min_idx);
if(it != indices.end()) if(it != indices.end())
{ {
// there are two points in set1 corresponding to the same point in set2 // there are two points in set1 corresponding to the same point in set2
return 0; return 0;
} }
indices.push_back(min_idx); indices.push_back(min_idx);
// printf("dist %d = %f\n", (int)i, min_dist); // printf("dist %d = %f\n", (int)i, min_dist);
sum_dist += min_dist*min_dist; sum_dist += min_dist*min_dist;
} }
mean_dist = sqrt(sum_dist/set1.size()); mean_dist = sqrt(sum_dist/set1.size());
// printf("sum_dist = %f, set1.size() = %d, mean_dist = %f\n", sum_dist, (int)set1.size(), mean_dist); // printf("sum_dist = %f, set1.size() = %d, mean_dist = %f\n", sum_dist, (int)set1.size(), mean_dist);
return 1; return 1;
} }
CV_ChessboardSubpixelTest::CV_ChessboardSubpixelTest() : CV_ChessboardSubpixelTest::CV_ChessboardSubpixelTest() :
intrinsic_matrix_(Size(3, 3), CV_64FC1), distortion_coeffs_(Size(1, 4), CV_64FC1), intrinsic_matrix_(Size(3, 3), CV_64FC1), distortion_coeffs_(Size(1, 4), CV_64FC1),
image_size_(640, 480) image_size_(640, 480)
{ {
} }
@ -121,13 +121,13 @@ void CV_ChessboardSubpixelTest::run( int )
int progress = 0; int progress = 0;
RNG& rng = ts->get_rng(); RNG& rng = ts->get_rng();
const int runs_count = 20; const int runs_count = 20;
const int max_pattern_size = 8; const int max_pattern_size = 8;
const int min_pattern_size = 5; const int min_pattern_size = 5;
Mat bg(image_size_, CV_8UC1); Mat bg(image_size_, CV_8UC1);
bg = Scalar(0); bg = Scalar(0);
double sum_dist = 0.0; double sum_dist = 0.0;
int count = 0; int count = 0;
for(int i = 0; i < runs_count; i++) for(int i = 0; i < runs_count; i++)
@ -144,13 +144,13 @@ void CV_ChessboardSubpixelTest::run( int )
pattern_size = Size(pattern_width, pattern_height); pattern_size = Size(pattern_width, pattern_height);
} }
ChessBoardGenerator gen_chessboard(Size(pattern_size.width + 1, pattern_size.height + 1)); ChessBoardGenerator gen_chessboard(Size(pattern_size.width + 1, pattern_size.height + 1));
// generates intrinsic camera and distortion matrices // generates intrinsic camera and distortion matrices
generateIntrinsicParams(); generateIntrinsicParams();
vector<Point2f> corners; vector<Point2f> corners;
Mat chessboard_image = gen_chessboard(bg, intrinsic_matrix_, distortion_coeffs_, corners); Mat chessboard_image = gen_chessboard(bg, intrinsic_matrix_, distortion_coeffs_, corners);
vector<Point2f> test_corners; vector<Point2f> test_corners;
bool result = findChessboardCorners(chessboard_image, pattern_size, test_corners, 15); bool result = findChessboardCorners(chessboard_image, pattern_size, test_corners, 15);
if(!result) if(!result)
@ -158,47 +158,47 @@ void CV_ChessboardSubpixelTest::run( int )
#if 0 #if 0
ts->printf(cvtest::TS::LOG, "Warning: chessboard was not detected! Writing image to test.jpg\n"); ts->printf(cvtest::TS::LOG, "Warning: chessboard was not detected! Writing image to test.jpg\n");
ts->printf(cvtest::TS::LOG, "Size = %d, %d\n", pattern_size.width, pattern_size.height); ts->printf(cvtest::TS::LOG, "Size = %d, %d\n", pattern_size.width, pattern_size.height);
ts->printf(cvtest::TS::LOG, "Intrinsic params: fx = %f, fy = %f, cx = %f, cy = %f\n", ts->printf(cvtest::TS::LOG, "Intrinsic params: fx = %f, fy = %f, cx = %f, cy = %f\n",
intrinsic_matrix_.at<double>(0, 0), intrinsic_matrix_.at<double>(1, 1), intrinsic_matrix_.at<double>(0, 0), intrinsic_matrix_.at<double>(1, 1),
intrinsic_matrix_.at<double>(0, 2), intrinsic_matrix_.at<double>(1, 2)); intrinsic_matrix_.at<double>(0, 2), intrinsic_matrix_.at<double>(1, 2));
ts->printf(cvtest::TS::LOG, "Distortion matrix: %f, %f, %f, %f, %f\n", ts->printf(cvtest::TS::LOG, "Distortion matrix: %f, %f, %f, %f, %f\n",
distortion_coeffs_.at<double>(0, 0), distortion_coeffs_.at<double>(0, 1), distortion_coeffs_.at<double>(0, 0), distortion_coeffs_.at<double>(0, 1),
distortion_coeffs_.at<double>(0, 2), distortion_coeffs_.at<double>(0, 3), distortion_coeffs_.at<double>(0, 2), distortion_coeffs_.at<double>(0, 3),
distortion_coeffs_.at<double>(0, 4)); distortion_coeffs_.at<double>(0, 4));
imwrite("test.jpg", chessboard_image); imwrite("test.jpg", chessboard_image);
#endif #endif
continue; continue;
} }
double dist1 = 0.0; double dist1 = 0.0;
int ret = calcDistance(corners, test_corners, dist1); int ret = calcDistance(corners, test_corners, dist1);
if(ret == 0) if(ret == 0)
{ {
ts->printf(cvtest::TS::LOG, "findChessboardCorners returns invalid corner coordinates!\n"); ts->printf(cvtest::TS::LOG, "findChessboardCorners returns invalid corner coordinates!\n");
code = cvtest::TS::FAIL_INVALID_OUTPUT; code = cvtest::TS::FAIL_INVALID_OUTPUT;
break; break;
} }
IplImage chessboard_image_header = chessboard_image; IplImage chessboard_image_header = chessboard_image;
cvFindCornerSubPix(&chessboard_image_header, (CvPoint2D32f*)&test_corners[0], cvFindCornerSubPix(&chessboard_image_header, (CvPoint2D32f*)&test_corners[0],
(int)test_corners.size(), cvSize(3, 3), cvSize(1, 1), cvTermCriteria(CV_TERMCRIT_EPS|CV_TERMCRIT_ITER,300,0.1)); (int)test_corners.size(), cvSize(3, 3), cvSize(1, 1), cvTermCriteria(CV_TERMCRIT_EPS|CV_TERMCRIT_ITER,300,0.1));
find4QuadCornerSubpix(chessboard_image, test_corners, Size(5, 5)); find4QuadCornerSubpix(chessboard_image, test_corners, Size(5, 5));
double dist2 = 0.0; double dist2 = 0.0;
ret = calcDistance(corners, test_corners, dist2); ret = calcDistance(corners, test_corners, dist2);
if(ret == 0) if(ret == 0)
{ {
ts->printf(cvtest::TS::LOG, "findCornerSubpix returns invalid corner coordinates!\n"); ts->printf(cvtest::TS::LOG, "findCornerSubpix returns invalid corner coordinates!\n");
code = cvtest::TS::FAIL_INVALID_OUTPUT; code = cvtest::TS::FAIL_INVALID_OUTPUT;
break; break;
} }
ts->printf(cvtest::TS::LOG, "Error after findChessboardCorners: %f, after findCornerSubPix: %f\n", ts->printf(cvtest::TS::LOG, "Error after findChessboardCorners: %f, after findCornerSubPix: %f\n",
dist1, dist2); dist1, dist2);
sum_dist += dist2; sum_dist += dist2;
count++; count++;
const double max_reduce_factor = 0.8; const double max_reduce_factor = 0.8;
if(dist1 < dist2*max_reduce_factor) if(dist1 < dist2*max_reduce_factor)
{ {
@ -206,33 +206,33 @@ void CV_ChessboardSubpixelTest::run( int )
code = cvtest::TS::FAIL_INVALID_OUTPUT; code = cvtest::TS::FAIL_INVALID_OUTPUT;
break; break;
} }
progress = update_progress( progress, i-1, runs_count, 0 ); progress = update_progress( progress, i-1, runs_count, 0 );
} }
sum_dist /= count; sum_dist /= count;
ts->printf(cvtest::TS::LOG, "Average error after findCornerSubpix: %f\n", sum_dist); ts->printf(cvtest::TS::LOG, "Average error after findCornerSubpix: %f\n", sum_dist);
if( code < 0 ) if( code < 0 )
ts->set_failed_test_info( code ); ts->set_failed_test_info( code );
} }
void CV_ChessboardSubpixelTest::generateIntrinsicParams() void CV_ChessboardSubpixelTest::generateIntrinsicParams()
{ {
RNG& rng = ts->get_rng(); RNG& rng = ts->get_rng();
const double max_focus_length = 1000.0; const double max_focus_length = 1000.0;
const double max_focus_diff = 5.0; const double max_focus_diff = 5.0;
double fx = cvtest::randReal(rng)*max_focus_length; double fx = cvtest::randReal(rng)*max_focus_length;
double fy = fx + cvtest::randReal(rng)*max_focus_diff; double fy = fx + cvtest::randReal(rng)*max_focus_diff;
double cx = image_size_.width/2; double cx = image_size_.width/2;
double cy = image_size_.height/2; double cy = image_size_.height/2;
double k1 = 0.5*cvtest::randReal(rng); double k1 = 0.5*cvtest::randReal(rng);
double k2 = 0.05*cvtest::randReal(rng); double k2 = 0.05*cvtest::randReal(rng);
double p1 = 0.05*cvtest::randReal(rng); double p1 = 0.05*cvtest::randReal(rng);
double p2 = 0.05*cvtest::randReal(rng); double p2 = 0.05*cvtest::randReal(rng);
double k3 = 0.0; double k3 = 0.0;
intrinsic_matrix_ = (Mat_<double>(3, 3) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0); intrinsic_matrix_ = (Mat_<double>(3, 3) << fx, 0.0, cx, 0.0, fy, cy, 0.0, 0.0, 1.0);
distortion_coeffs_ = (Mat_<double>(1, 5) << k1, k2, p1, p2, k3); distortion_coeffs_ = (Mat_<double>(1, 5) << k1, k2, p1, p2, k3);
} }

View File

@ -473,20 +473,59 @@ string format( const char* fmt, ... )
string tempfile( const char* suffix ) string tempfile( const char* suffix )
{ {
char buf[L_tmpnam]; #if defined WIN32 || defined _WIN32
char* name = 0; char temp_dir[MAX_PATH + 1] = { 0 };
#ifdef ANDROID char temp_file[MAX_PATH + 1] = { 0 };
strcpy(buf, "/sdcard/__opencv_temp_XXXXXX");
name = mktemp(buf); ::GetTempPathA(sizeof(temp_dir), temp_dir);
#else if(0 != ::GetTempFileNameA(temp_dir, "__opencv_temp.", 0, temp_file))
name = tmpnam(buf); return string();
#endif
if (*name == '\\') string name = temp_file;
++name; if(suffix)
string n(name); {
if (suffix != 0) if (suffix[0] != '.')
n += (n[n.size()-1] == '.' && suffix[0] == '.' ? suffix + 1 : suffix); return name + "." + suffix;
return n; else
return name + suffix;
}
else
return name;
# else
# ifdef ANDROID
//char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX";
char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX";
# else
char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX";
# endif
string fname;
const char *temp_dir = getenv("OPENCV_TEMP_PATH");
if(temp_dir == 0 || temp_dir[0] == 0)
fname = defaultTemplate;
else
{
fname = temp_dir;
char ech = fname[fname.size() - 1];
if(ech != '/' && ech != '\\')
fname += "/";
fname += "__opencv_temp.XXXXXX";
}
const int fd = mkstemp((char*)fname.c_str());
if(fd == -1) return "";
close(fd);
remove(fname.c_str());
if(suffix)
{
if (suffix[0] != '.')
fname = fname + "." + suffix;
else
fname += suffix;
}
return fname;
# endif
} }
static CvErrorCallback customErrorCallback = 0; static CvErrorCallback customErrorCallback = 0;

View File

@ -27,23 +27,23 @@ struct BaseElemWiseOp
minval = depth < CV_32S ? cvtest::getMinVal(depth) : depth == CV_32S ? -1000000 : -1000.; minval = depth < CV_32S ? cvtest::getMinVal(depth) : depth == CV_32S ? -1000000 : -1000.;
maxval = depth < CV_32S ? cvtest::getMaxVal(depth) : depth == CV_32S ? 1000000 : 1000.; maxval = depth < CV_32S ? cvtest::getMaxVal(depth) : depth == CV_32S ? 1000000 : 1000.;
} }
virtual void getRandomSize(RNG& rng, vector<int>& size) virtual void getRandomSize(RNG& rng, vector<int>& size)
{ {
cvtest::randomSize(rng, 2, ARITHM_MAX_NDIMS, cvtest::ARITHM_MAX_SIZE_LOG, size); cvtest::randomSize(rng, 2, ARITHM_MAX_NDIMS, cvtest::ARITHM_MAX_SIZE_LOG, size);
} }
virtual int getRandomType(RNG& rng) virtual int getRandomType(RNG& rng)
{ {
return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1,
ninputs > 1 ? ARITHM_MAX_CHANNELS : 4); ninputs > 1 ? ARITHM_MAX_CHANNELS : 4);
} }
virtual double getMaxErr(int depth) { return depth < CV_32F ? 1 : depth == CV_32F ? 1e-5 : 1e-12; } virtual double getMaxErr(int depth) { return depth < CV_32F ? 1 : depth == CV_32F ? 1e-5 : 1e-12; }
virtual void generateScalars(int depth, RNG& rng) virtual void generateScalars(int depth, RNG& rng)
{ {
const double m = 3.; const double m = 3.;
if( !(flags & FIX_ALPHA) ) if( !(flags & FIX_ALPHA) )
{ {
alpha = exp(rng.uniform(-0.5, 0.1)*m*2*CV_LOG2); alpha = exp(rng.uniform(-0.5, 0.1)*m*2*CV_LOG2);
@ -54,7 +54,7 @@ struct BaseElemWiseOp
beta = exp(rng.uniform(-0.5, 0.1)*m*2*CV_LOG2); beta = exp(rng.uniform(-0.5, 0.1)*m*2*CV_LOG2);
beta *= rng.uniform(0, 2) ? 1 : -1; beta *= rng.uniform(0, 2) ? 1 : -1;
} }
if( !(flags & FIX_GAMMA) ) if( !(flags & FIX_GAMMA) )
{ {
for( int i = 0; i < 4; i++ ) for( int i = 0; i < 4; i++ )
@ -65,25 +65,25 @@ struct BaseElemWiseOp
if( flags & REAL_GAMMA ) if( flags & REAL_GAMMA )
gamma = Scalar::all(gamma[0]); gamma = Scalar::all(gamma[0]);
} }
if( depth == CV_32F ) if( depth == CV_32F )
{ {
Mat fl, db; Mat fl, db;
db = Mat(1, 1, CV_64F, &alpha); db = Mat(1, 1, CV_64F, &alpha);
db.convertTo(fl, CV_32F); db.convertTo(fl, CV_32F);
fl.convertTo(db, CV_64F); fl.convertTo(db, CV_64F);
db = Mat(1, 1, CV_64F, &beta); db = Mat(1, 1, CV_64F, &beta);
db.convertTo(fl, CV_32F); db.convertTo(fl, CV_32F);
fl.convertTo(db, CV_64F); fl.convertTo(db, CV_64F);
db = Mat(1, 4, CV_64F, &gamma[0]); db = Mat(1, 4, CV_64F, &gamma[0]);
db.convertTo(fl, CV_32F); db.convertTo(fl, CV_32F);
fl.convertTo(db, CV_64F); fl.convertTo(db, CV_64F);
} }
} }
int ninputs; int ninputs;
int flags; int flags;
double alpha; double alpha;
@ -98,7 +98,7 @@ struct BaseAddOp : public BaseElemWiseOp
{ {
BaseAddOp(int _ninputs, int _flags, double _alpha, double _beta, Scalar _gamma=Scalar::all(0)) BaseAddOp(int _ninputs, int _flags, double _alpha, double _beta, Scalar _gamma=Scalar::all(0))
: BaseElemWiseOp(_ninputs, _flags, _alpha, _beta, _gamma) {} : BaseElemWiseOp(_ninputs, _flags, _alpha, _beta, _gamma) {}
void refop(const vector<Mat>& src, Mat& dst, const Mat& mask) void refop(const vector<Mat>& src, Mat& dst, const Mat& mask)
{ {
Mat temp; Mat temp;
@ -214,7 +214,7 @@ struct MulOp : public BaseElemWiseOp
{ {
return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12; return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12;
} }
}; };
struct DivOp : public BaseElemWiseOp struct DivOp : public BaseElemWiseOp
{ {
@ -231,7 +231,7 @@ struct DivOp : public BaseElemWiseOp
{ {
return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12; return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12;
} }
}; };
struct RecipOp : public BaseElemWiseOp struct RecipOp : public BaseElemWiseOp
{ {
@ -248,8 +248,8 @@ struct RecipOp : public BaseElemWiseOp
{ {
return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12; return depth <= CV_32S ? 2 : depth < CV_64F ? 1e-5 : 1e-12;
} }
}; };
struct AbsDiffOp : public BaseAddOp struct AbsDiffOp : public BaseAddOp
{ {
AbsDiffOp() : BaseAddOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, -1, Scalar::all(0)) {}; AbsDiffOp() : BaseAddOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, -1, Scalar::all(0)) {};
@ -354,7 +354,7 @@ struct MinOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct MaxOp : public BaseElemWiseOp struct MaxOp : public BaseElemWiseOp
{ {
@ -371,7 +371,7 @@ struct MaxOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct MinSOp : public BaseElemWiseOp struct MinSOp : public BaseElemWiseOp
{ {
@ -388,7 +388,7 @@ struct MinSOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct MaxSOp : public BaseElemWiseOp struct MaxSOp : public BaseElemWiseOp
{ {
@ -406,7 +406,7 @@ struct MaxSOp : public BaseElemWiseOp
return 0; return 0;
} }
}; };
struct CmpOp : public BaseElemWiseOp struct CmpOp : public BaseElemWiseOp
{ {
CmpOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; CmpOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
@ -427,7 +427,7 @@ struct CmpOp : public BaseElemWiseOp
{ {
return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 1); return cvtest::randomType(rng, DEPTH_MASK_ALL_BUT_8S, 1, 1);
} }
double getMaxErr(int) double getMaxErr(int)
{ {
return 0; return 0;
@ -462,9 +462,9 @@ struct CmpSOp : public BaseElemWiseOp
return 0; return 0;
} }
int cmpop; int cmpop;
}; };
struct CopyOp : public BaseElemWiseOp struct CopyOp : public BaseElemWiseOp
{ {
CopyOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK, 1, 1, Scalar::all(0)) {}; CopyOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK, 1, 1, Scalar::all(0)) {};
@ -487,7 +487,7 @@ struct CopyOp : public BaseElemWiseOp
int cmpop; int cmpop;
}; };
struct SetOp : public BaseElemWiseOp struct SetOp : public BaseElemWiseOp
{ {
SetOp() : BaseElemWiseOp(0, FIX_ALPHA+FIX_BETA+SUPPORT_MASK, 1, 1, Scalar::all(0)) {}; SetOp() : BaseElemWiseOp(0, FIX_ALPHA+FIX_BETA+SUPPORT_MASK, 1, 1, Scalar::all(0)) {};
@ -507,7 +507,7 @@ struct SetOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
template<typename _Tp, typename _WTp> static void template<typename _Tp, typename _WTp> static void
inRangeS_(const _Tp* src, const _WTp* a, const _WTp* b, uchar* dst, size_t total, int cn) inRangeS_(const _Tp* src, const _WTp* a, const _WTp* b, uchar* dst, size_t total, int cn)
@ -547,7 +547,7 @@ template<typename _Tp> static void inRange_(const _Tp* src, const _Tp* a, const
} }
} }
} }
static void inRange(const Mat& src, const Mat& lb, const Mat& rb, Mat& dst) static void inRange(const Mat& src, const Mat& lb, const Mat& rb, Mat& dst)
{ {
@ -556,19 +556,19 @@ static void inRange(const Mat& src, const Mat& lb, const Mat& rb, Mat& dst)
dst.create( src.dims, &src.size[0], CV_8U ); dst.create( src.dims, &src.size[0], CV_8U );
const Mat *arrays[]={&src, &lb, &rb, &dst, 0}; const Mat *arrays[]={&src, &lb, &rb, &dst, 0};
Mat planes[4]; Mat planes[4];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
size_t total = planes[0].total(); size_t total = planes[0].total();
size_t i, nplanes = it.nplanes; size_t i, nplanes = it.nplanes;
int depth = src.depth(), cn = src.channels(); int depth = src.depth(), cn = src.channels();
for( i = 0; i < nplanes; i++, ++it ) for( i = 0; i < nplanes; i++, ++it )
{ {
const uchar* sptr = planes[0].data; const uchar* sptr = planes[0].data;
const uchar* aptr = planes[1].data; const uchar* aptr = planes[1].data;
const uchar* bptr = planes[2].data; const uchar* bptr = planes[2].data;
uchar* dptr = planes[3].data; uchar* dptr = planes[3].data;
switch( depth ) switch( depth )
{ {
case CV_8U: case CV_8U:
@ -604,21 +604,21 @@ static void inRangeS(const Mat& src, const Scalar& lb, const Scalar& rb, Mat& ds
dst.create( src.dims, &src.size[0], CV_8U ); dst.create( src.dims, &src.size[0], CV_8U );
const Mat *arrays[]={&src, &dst, 0}; const Mat *arrays[]={&src, &dst, 0};
Mat planes[2]; Mat planes[2];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
size_t total = planes[0].total(); size_t total = planes[0].total();
size_t i, nplanes = it.nplanes; size_t i, nplanes = it.nplanes;
int depth = src.depth(), cn = src.channels(); int depth = src.depth(), cn = src.channels();
union { double d[4]; float f[4]; int i[4];} lbuf, rbuf; union { double d[4]; float f[4]; int i[4];} lbuf, rbuf;
int wtype = CV_MAKETYPE(depth <= CV_32S ? CV_32S : depth, cn); int wtype = CV_MAKETYPE(depth <= CV_32S ? CV_32S : depth, cn);
scalarToRawData(lb, lbuf.d, wtype, cn); scalarToRawData(lb, lbuf.d, wtype, cn);
scalarToRawData(rb, rbuf.d, wtype, cn); scalarToRawData(rb, rbuf.d, wtype, cn);
for( i = 0; i < nplanes; i++, ++it ) for( i = 0; i < nplanes; i++, ++it )
{ {
const uchar* sptr = planes[0].data; const uchar* sptr = planes[0].data;
uchar* dptr = planes[1].data; uchar* dptr = planes[1].data;
switch( depth ) switch( depth )
{ {
case CV_8U: case CV_8U:
@ -647,8 +647,8 @@ static void inRangeS(const Mat& src, const Scalar& lb, const Scalar& rb, Mat& ds
} }
} }
} }
struct InRangeSOp : public BaseElemWiseOp struct InRangeSOp : public BaseElemWiseOp
{ {
InRangeSOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA, 1, 1, Scalar::all(0)) {}; InRangeSOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA, 1, 1, Scalar::all(0)) {};
@ -676,9 +676,9 @@ struct InRangeSOp : public BaseElemWiseOp
} }
} }
Scalar gamma1; Scalar gamma1;
}; };
struct InRangeOp : public BaseElemWiseOp struct InRangeOp : public BaseElemWiseOp
{ {
InRangeOp() : BaseElemWiseOp(3, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; InRangeOp() : BaseElemWiseOp(3, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
@ -687,7 +687,7 @@ struct InRangeOp : public BaseElemWiseOp
Mat lb, rb; Mat lb, rb;
cvtest::min(src[1], src[2], lb); cvtest::min(src[1], src[2], lb);
cvtest::max(src[1], src[2], rb); cvtest::max(src[1], src[2], rb);
cv::inRange(src[0], lb, rb, dst); cv::inRange(src[0], lb, rb, dst);
} }
void refop(const vector<Mat>& src, Mat& dst, const Mat&) void refop(const vector<Mat>& src, Mat& dst, const Mat&)
@ -695,16 +695,16 @@ struct InRangeOp : public BaseElemWiseOp
Mat lb, rb; Mat lb, rb;
cvtest::min(src[1], src[2], lb); cvtest::min(src[1], src[2], lb);
cvtest::max(src[1], src[2], rb); cvtest::max(src[1], src[2], rb);
cvtest::inRange(src[0], lb, rb, dst); cvtest::inRange(src[0], lb, rb, dst);
} }
double getMaxErr(int) double getMaxErr(int)
{ {
return 0; return 0;
} }
}; };
struct ConvertScaleOp : public BaseElemWiseOp struct ConvertScaleOp : public BaseElemWiseOp
{ {
ConvertScaleOp() : BaseElemWiseOp(1, FIX_BETA+REAL_GAMMA, 1, 1, Scalar::all(0)), ddepth(0) { }; ConvertScaleOp() : BaseElemWiseOp(1, FIX_BETA+REAL_GAMMA, 1, 1, Scalar::all(0)), ddepth(0) { };
@ -739,7 +739,7 @@ struct ConvertScaleOp : public BaseElemWiseOp
int ddepth; int ddepth;
}; };
struct ConvertScaleAbsOp : public BaseElemWiseOp struct ConvertScaleAbsOp : public BaseElemWiseOp
{ {
ConvertScaleAbsOp() : BaseElemWiseOp(1, FIX_BETA+REAL_GAMMA, 1, 1, Scalar::all(0)) {}; ConvertScaleAbsOp() : BaseElemWiseOp(1, FIX_BETA+REAL_GAMMA, 1, 1, Scalar::all(0)) {};
@ -767,13 +767,13 @@ struct ConvertScaleAbsOp : public BaseElemWiseOp
} }
}; };
static void flip(const Mat& src, Mat& dst, int flipcode) static void flip(const Mat& src, Mat& dst, int flipcode)
{ {
CV_Assert(src.dims == 2); CV_Assert(src.dims == 2);
dst.create(src.size(), src.type()); dst.create(src.size(), src.type());
int i, j, k, esz = (int)src.elemSize(), width = src.cols*esz; int i, j, k, esz = (int)src.elemSize(), width = src.cols*esz;
for( i = 0; i < dst.rows; i++ ) for( i = 0; i < dst.rows; i++ )
{ {
const uchar* sptr = src.ptr(flipcode == 1 ? i : dst.rows - i - 1); const uchar* sptr = src.ptr(flipcode == 1 ? i : dst.rows - i - 1);
@ -796,7 +796,7 @@ static void setIdentity(Mat& dst, const Scalar& s)
double buf[4]; double buf[4];
scalarToRawData(s, buf, dst.type(), 0); scalarToRawData(s, buf, dst.type(), 0);
int i, k, esz = (int)dst.elemSize(), width = dst.cols*esz; int i, k, esz = (int)dst.elemSize(), width = dst.cols*esz;
for( i = 0; i < dst.rows; i++ ) for( i = 0; i < dst.rows; i++ )
{ {
uchar* dptr = dst.ptr(i); uchar* dptr = dst.ptr(i);
@ -807,7 +807,7 @@ static void setIdentity(Mat& dst, const Scalar& s)
} }
} }
struct FlipOp : public BaseElemWiseOp struct FlipOp : public BaseElemWiseOp
{ {
FlipOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; FlipOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
@ -853,8 +853,8 @@ struct TransposeOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct SetIdentityOp : public BaseElemWiseOp struct SetIdentityOp : public BaseElemWiseOp
{ {
SetIdentityOp() : BaseElemWiseOp(0, FIX_ALPHA+FIX_BETA, 1, 1, Scalar::all(0)) {}; SetIdentityOp() : BaseElemWiseOp(0, FIX_ALPHA+FIX_BETA, 1, 1, Scalar::all(0)) {};
@ -874,7 +874,7 @@ struct SetIdentityOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct SetZeroOp : public BaseElemWiseOp struct SetZeroOp : public BaseElemWiseOp
{ {
@ -893,23 +893,23 @@ struct SetZeroOp : public BaseElemWiseOp
} }
}; };
static void exp(const Mat& src, Mat& dst) static void exp(const Mat& src, Mat& dst)
{ {
dst.create( src.dims, &src.size[0], src.type() ); dst.create( src.dims, &src.size[0], src.type() );
const Mat *arrays[]={&src, &dst, 0}; const Mat *arrays[]={&src, &dst, 0};
Mat planes[2]; Mat planes[2];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
size_t j, total = planes[0].total()*src.channels(); size_t j, total = planes[0].total()*src.channels();
size_t i, nplanes = it.nplanes; size_t i, nplanes = it.nplanes;
int depth = src.depth(); int depth = src.depth();
for( i = 0; i < nplanes; i++, ++it ) for( i = 0; i < nplanes; i++, ++it )
{ {
const uchar* sptr = planes[0].data; const uchar* sptr = planes[0].data;
uchar* dptr = planes[1].data; uchar* dptr = planes[1].data;
if( depth == CV_32F ) if( depth == CV_32F )
{ {
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
@ -920,7 +920,7 @@ static void exp(const Mat& src, Mat& dst)
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
((double*)dptr)[j] = std::exp(((const double*)sptr)[j]); ((double*)dptr)[j] = std::exp(((const double*)sptr)[j]);
} }
} }
} }
static void log(const Mat& src, Mat& dst) static void log(const Mat& src, Mat& dst)
@ -928,17 +928,17 @@ static void log(const Mat& src, Mat& dst)
dst.create( src.dims, &src.size[0], src.type() ); dst.create( src.dims, &src.size[0], src.type() );
const Mat *arrays[]={&src, &dst, 0}; const Mat *arrays[]={&src, &dst, 0};
Mat planes[2]; Mat planes[2];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
size_t j, total = planes[0].total()*src.channels(); size_t j, total = planes[0].total()*src.channels();
size_t i, nplanes = it.nplanes; size_t i, nplanes = it.nplanes;
int depth = src.depth(); int depth = src.depth();
for( i = 0; i < nplanes; i++, ++it ) for( i = 0; i < nplanes; i++, ++it )
{ {
const uchar* sptr = planes[0].data; const uchar* sptr = planes[0].data;
uchar* dptr = planes[1].data; uchar* dptr = planes[1].data;
if( depth == CV_32F ) if( depth == CV_32F )
{ {
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
@ -949,9 +949,9 @@ static void log(const Mat& src, Mat& dst)
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
((double*)dptr)[j] = std::log(fabs(((const double*)sptr)[j])); ((double*)dptr)[j] = std::log(fabs(((const double*)sptr)[j]));
} }
} }
} }
struct ExpOp : public BaseElemWiseOp struct ExpOp : public BaseElemWiseOp
{ {
ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}; ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
@ -976,7 +976,7 @@ struct ExpOp : public BaseElemWiseOp
{ {
return depth == CV_32F ? 1e-5 : 1e-12; return depth == CV_32F ? 1e-5 : 1e-12;
} }
}; };
struct LogOp : public BaseElemWiseOp struct LogOp : public BaseElemWiseOp
@ -1018,13 +1018,13 @@ static void cartToPolar(const Mat& mx, const Mat& my, Mat& mmag, Mat& mangle, bo
mangle.create( mx.dims, &mx.size[0], mx.type() ); mangle.create( mx.dims, &mx.size[0], mx.type() );
const Mat *arrays[]={&mx, &my, &mmag, &mangle, 0}; const Mat *arrays[]={&mx, &my, &mmag, &mangle, 0};
Mat planes[4]; Mat planes[4];
NAryMatIterator it(arrays, planes); NAryMatIterator it(arrays, planes);
size_t j, total = planes[0].total(); size_t j, total = planes[0].total();
size_t i, nplanes = it.nplanes; size_t i, nplanes = it.nplanes;
int depth = mx.depth(); int depth = mx.depth();
double scale = angleInDegrees ? 180/CV_PI : 1; double scale = angleInDegrees ? 180/CV_PI : 1;
for( i = 0; i < nplanes; i++, ++it ) for( i = 0; i < nplanes; i++, ++it )
{ {
if( depth == CV_32F ) if( depth == CV_32F )
@ -1033,7 +1033,7 @@ static void cartToPolar(const Mat& mx, const Mat& my, Mat& mmag, Mat& mangle, bo
const float* yptr = (const float*)planes[1].data; const float* yptr = (const float*)planes[1].data;
float* mptr = (float*)planes[2].data; float* mptr = (float*)planes[2].data;
float* aptr = (float*)planes[3].data; float* aptr = (float*)planes[3].data;
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
{ {
mptr[j] = std::sqrt(xptr[j]*xptr[j] + yptr[j]*yptr[j]); mptr[j] = std::sqrt(xptr[j]*xptr[j] + yptr[j]*yptr[j]);
@ -1048,7 +1048,7 @@ static void cartToPolar(const Mat& mx, const Mat& my, Mat& mmag, Mat& mangle, bo
const double* yptr = (const double*)planes[1].data; const double* yptr = (const double*)planes[1].data;
double* mptr = (double*)planes[2].data; double* mptr = (double*)planes[2].data;
double* aptr = (double*)planes[3].data; double* aptr = (double*)planes[3].data;
for( j = 0; j < total; j++ ) for( j = 0; j < total; j++ )
{ {
mptr[j] = std::sqrt(xptr[j]*xptr[j] + yptr[j]*yptr[j]); mptr[j] = std::sqrt(xptr[j]*xptr[j] + yptr[j]*yptr[j]);
@ -1059,8 +1059,8 @@ static void cartToPolar(const Mat& mx, const Mat& my, Mat& mmag, Mat& mangle, bo
} }
} }
} }
struct CartToPolarToCartOp : public BaseElemWiseOp struct CartToPolarToCartOp : public BaseElemWiseOp
{ {
CartToPolarToCartOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) CartToPolarToCartOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0))
@ -1075,10 +1075,10 @@ struct CartToPolarToCartOp : public BaseElemWiseOp
void op(const vector<Mat>& src, Mat& dst, const Mat&) void op(const vector<Mat>& src, Mat& dst, const Mat&)
{ {
Mat mag, angle, x, y; Mat mag, angle, x, y;
cv::cartToPolar(src[0], src[1], mag, angle, angleInDegrees); cv::cartToPolar(src[0], src[1], mag, angle, angleInDegrees);
cv::polarToCart(mag, angle, x, y, angleInDegrees); cv::polarToCart(mag, angle, x, y, angleInDegrees);
Mat msrc[] = {mag, angle, x, y}; Mat msrc[] = {mag, angle, x, y};
int pairs[] = {0, 0, 1, 1, 2, 2, 3, 3}; int pairs[] = {0, 0, 1, 1, 2, 2, 3, 3};
dst.create(src[0].dims, src[0].size, CV_MAKETYPE(src[0].depth(), 4)); dst.create(src[0].dims, src[0].size, CV_MAKETYPE(src[0].depth(), 4));
@ -1103,8 +1103,8 @@ struct CartToPolarToCartOp : public BaseElemWiseOp
} }
bool angleInDegrees; bool angleInDegrees;
}; };
struct MeanOp : public BaseElemWiseOp struct MeanOp : public BaseElemWiseOp
{ {
MeanOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK+SCALAR_OUTPUT, 1, 1, Scalar::all(0)) MeanOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK+SCALAR_OUTPUT, 1, 1, Scalar::all(0))
@ -1125,7 +1125,7 @@ struct MeanOp : public BaseElemWiseOp
{ {
return 1e-6; return 1e-6;
} }
}; };
struct SumOp : public BaseElemWiseOp struct SumOp : public BaseElemWiseOp
@ -1148,9 +1148,9 @@ struct SumOp : public BaseElemWiseOp
{ {
return 1e-5; return 1e-5;
} }
}; };
struct CountNonZeroOp : public BaseElemWiseOp struct CountNonZeroOp : public BaseElemWiseOp
{ {
CountNonZeroOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SCALAR_OUTPUT+SUPPORT_MASK, 1, 1, Scalar::all(0)) CountNonZeroOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SCALAR_OUTPUT+SUPPORT_MASK, 1, 1, Scalar::all(0))
@ -1181,9 +1181,9 @@ struct CountNonZeroOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
struct MeanStdDevOp : public BaseElemWiseOp struct MeanStdDevOp : public BaseElemWiseOp
{ {
Scalar sqmeanRef; Scalar sqmeanRef;
@ -1206,13 +1206,13 @@ struct MeanStdDevOp : public BaseElemWiseOp
cvtest::multiply(temp, temp, temp); cvtest::multiply(temp, temp, temp);
Scalar mean = cvtest::mean(src[0], mask); Scalar mean = cvtest::mean(src[0], mask);
Scalar sqmean = cvtest::mean(temp, mask); Scalar sqmean = cvtest::mean(temp, mask);
sqmeanRef = sqmean; sqmeanRef = sqmean;
cn = temp.channels(); cn = temp.channels();
for( int c = 0; c < 4; c++ ) for( int c = 0; c < 4; c++ )
sqmean[c] = std::sqrt(std::max(sqmean[c] - mean[c]*mean[c], 0.)); sqmean[c] = std::sqrt(std::max(sqmean[c] - mean[c]*mean[c], 0.));
dst.create(1, 2, CV_64FC4); dst.create(1, 2, CV_64FC4);
dst.at<Scalar>(0,0) = mean; dst.at<Scalar>(0,0) = mean;
dst.at<Scalar>(0,1) = sqmean; dst.at<Scalar>(0,1) = sqmean;
@ -1225,9 +1225,9 @@ struct MeanStdDevOp : public BaseElemWiseOp
err = std::max(err, sqmeanRef[i]); err = std::max(err, sqmeanRef[i]);
return 3e-7 * err; return 3e-7 * err;
} }
}; };
struct NormOp : public BaseElemWiseOp struct NormOp : public BaseElemWiseOp
{ {
NormOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK+SCALAR_OUTPUT, 1, 1, Scalar::all(0)) NormOp() : BaseElemWiseOp(2, FIX_ALPHA+FIX_BETA+FIX_GAMMA+SUPPORT_MASK+SCALAR_OUTPUT, 1, 1, Scalar::all(0))
@ -1272,7 +1272,7 @@ struct NormOp : public BaseElemWiseOp
return 1e-6; return 1e-6;
} }
int normType; int normType;
}; };
struct MinMaxLocOp : public BaseElemWiseOp struct MinMaxLocOp : public BaseElemWiseOp
@ -1290,7 +1290,7 @@ struct MinMaxLocOp : public BaseElemWiseOp
{ {
int i, ndims = (int)minidx.size(); int i, ndims = (int)minidx.size();
dst.create(1, ndims*2 + 2, CV_64FC1); dst.create(1, ndims*2 + 2, CV_64FC1);
for( i = 0; i < ndims; i++ ) for( i = 0; i < ndims; i++ )
{ {
dst.at<double>(0,i) = minidx[i]; dst.at<double>(0,i) = minidx[i];
@ -1319,9 +1319,9 @@ struct MinMaxLocOp : public BaseElemWiseOp
{ {
return 0; return 0;
} }
}; };
} }
typedef Ptr<cvtest::BaseElemWiseOp> ElemWiseOpPtr; typedef Ptr<cvtest::BaseElemWiseOp> ElemWiseOpPtr;
@ -1330,7 +1330,7 @@ class ElemWiseTest : public ::testing::TestWithParam<ElemWiseOpPtr> {};
TEST_P(ElemWiseTest, accuracy) TEST_P(ElemWiseTest, accuracy)
{ {
ElemWiseOpPtr op = GetParam(); ElemWiseOpPtr op = GetParam();
int testIdx = 0; int testIdx = 0;
RNG rng((uint64)cvtest::ARITHM_RNG_SEED); RNG rng((uint64)cvtest::ARITHM_RNG_SEED);
for( testIdx = 0; testIdx < cvtest::ARITHM_NTESTS; testIdx++ ) for( testIdx = 0; testIdx < cvtest::ARITHM_NTESTS; testIdx++ )
@ -1340,7 +1340,7 @@ TEST_P(ElemWiseTest, accuracy)
int type = op->getRandomType(rng); int type = op->getRandomType(rng);
int depth = CV_MAT_DEPTH(type); int depth = CV_MAT_DEPTH(type);
bool haveMask = (op->flags & cvtest::BaseElemWiseOp::SUPPORT_MASK) != 0 && rng.uniform(0, 4) == 0; bool haveMask = (op->flags & cvtest::BaseElemWiseOp::SUPPORT_MASK) != 0 && rng.uniform(0, 4) == 0;
double minval=0, maxval=0; double minval=0, maxval=0;
op->getValueRange(depth, minval, maxval); op->getValueRange(depth, minval, maxval);
int i, ninputs = op->ninputs; int i, ninputs = op->ninputs;
@ -1350,7 +1350,7 @@ TEST_P(ElemWiseTest, accuracy)
Mat dst0, dst, mask; Mat dst0, dst, mask;
if( haveMask ) if( haveMask )
mask = cvtest::randomMat(rng, size, CV_8U, 0, 2, true); mask = cvtest::randomMat(rng, size, CV_8U, 0, 2, true);
if( (haveMask || ninputs == 0) && !(op->flags & cvtest::BaseElemWiseOp::SCALAR_OUTPUT)) if( (haveMask || ninputs == 0) && !(op->flags & cvtest::BaseElemWiseOp::SCALAR_OUTPUT))
{ {
dst0 = cvtest::randomMat(rng, size, type, minval, maxval, false); dst0 = cvtest::randomMat(rng, size, type, minval, maxval, false);
@ -1358,17 +1358,17 @@ TEST_P(ElemWiseTest, accuracy)
cvtest::copy(dst, dst0); cvtest::copy(dst, dst0);
} }
op->generateScalars(depth, rng); op->generateScalars(depth, rng);
op->refop(src, dst0, mask); op->refop(src, dst0, mask);
op->op(src, dst, mask); op->op(src, dst, mask);
double maxErr = op->getMaxErr(depth); double maxErr = op->getMaxErr(depth);
vector<int> pos; vector<int> pos;
ASSERT_PRED_FORMAT2(cvtest::MatComparator(maxErr, op->context), dst0, dst) << "\nsrc[0] ~ " << cvtest::MatInfo(!src.empty() ? src[0] : Mat()) << "\ntestCase #" << testIdx << "\n"; ASSERT_PRED_FORMAT2(cvtest::MatComparator(maxErr, op->context), dst0, dst) << "\nsrc[0] ~ " << cvtest::MatInfo(!src.empty() ? src[0] : Mat()) << "\ntestCase #" << testIdx << "\n";
} }
} }
INSTANTIATE_TEST_CASE_P(Core_Copy, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::CopyOp))); INSTANTIATE_TEST_CASE_P(Core_Copy, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::CopyOp)));
INSTANTIATE_TEST_CASE_P(Core_Set, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::SetOp))); INSTANTIATE_TEST_CASE_P(Core_Set, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::SetOp)));
INSTANTIATE_TEST_CASE_P(Core_SetZero, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::SetZeroOp))); INSTANTIATE_TEST_CASE_P(Core_SetZero, ElemWiseTest, ::testing::Values(ElemWiseOpPtr(new cvtest::SetZeroOp)));
@ -1429,7 +1429,7 @@ class CV_ArithmMaskTest : public cvtest::BaseTest
{ {
public: public:
CV_ArithmMaskTest() {} CV_ArithmMaskTest() {}
~CV_ArithmMaskTest() {} ~CV_ArithmMaskTest() {}
protected: protected:
void run(int) void run(int)
{ {
@ -1441,7 +1441,7 @@ protected:
for( int iter = 0; iter < 100; iter++ ) for( int iter = 0; iter < 100; iter++ )
{ {
//ts->printf(cvtest::TS::LOG, "."); //ts->printf(cvtest::TS::LOG, ".");
ts->update_context(this, iter, true); ts->update_context(this, iter, true);
int k, dims = rng.uniform(1, MAX_DIM+1), p = 1; int k, dims = rng.uniform(1, MAX_DIM+1), p = 1;
int depth = rng.uniform(CV_8U, CV_64F+1); int depth = rng.uniform(CV_8U, CV_64F+1);
@ -1459,15 +1459,15 @@ protected:
Mat mask(dims, sizes, CV_8U); Mat mask(dims, sizes, CV_8U);
Mat mask1; Mat mask1;
Mat c, d; Mat c, d;
rng.fill(a, RNG::UNIFORM, 0, 100); rng.fill(a, RNG::UNIFORM, 0, 100);
rng.fill(b, RNG::UNIFORM, 0, 100); rng.fill(b, RNG::UNIFORM, 0, 100);
// [-2,2) range means that the each generated random number // [-2,2) range means that the each generated random number
// will be one of -2, -1, 0, 1. Saturated to [0,255], it will become // will be one of -2, -1, 0, 1. Saturated to [0,255], it will become
// 0, 0, 0, 1 => the mask will be filled by ~25%. // 0, 0, 0, 1 => the mask will be filled by ~25%.
rng.fill(mask, RNG::UNIFORM, -2, 2); rng.fill(mask, RNG::UNIFORM, -2, 2);
a.convertTo(a1, depth1); a.convertTo(a1, depth1);
b.convertTo(b1, depth1); b.convertTo(b1, depth1);
// invert the mask // invert the mask
@ -1504,7 +1504,7 @@ protected:
d.convertTo(d1, depth); d.convertTo(d1, depth);
CV_Assert( norm(c, d1, CV_C) <= DBL_EPSILON ); CV_Assert( norm(c, d1, CV_C) <= DBL_EPSILON );
} }
Mat_<uchar> tmpSrc(100,100); Mat_<uchar> tmpSrc(100,100);
tmpSrc = 124; tmpSrc = 124;
Mat_<uchar> tmpMask(100,100); Mat_<uchar> tmpMask(100,100);

View File

@ -31,7 +31,7 @@ static SparseMat cvTsGetRandomSparseMat(int dims, const int* sz, int type,
else else
*(double*)ptr = saturate_cast<double>(val); *(double*)ptr = saturate_cast<double>(val);
} }
return m; return m;
} }
@ -40,11 +40,11 @@ static bool cvTsCheckSparse(const CvSparseMat* m1, const CvSparseMat* m2, double
CvSparseMatIterator it1; CvSparseMatIterator it1;
CvSparseNode* node1; CvSparseNode* node1;
int depth = CV_MAT_DEPTH(m1->type); int depth = CV_MAT_DEPTH(m1->type);
if( m1->heap->active_count != m2->heap->active_count || if( m1->heap->active_count != m2->heap->active_count ||
m1->dims != m2->dims || CV_MAT_TYPE(m1->type) != CV_MAT_TYPE(m2->type) ) m1->dims != m2->dims || CV_MAT_TYPE(m1->type) != CV_MAT_TYPE(m2->type) )
return false; return false;
for( node1 = cvInitSparseMatIterator( m1, &it1 ); for( node1 = cvInitSparseMatIterator( m1, &it1 );
node1 != 0; node1 = cvGetNextSparseNode( &it1 )) node1 != 0; node1 = cvGetNextSparseNode( &it1 ))
{ {
@ -75,7 +75,7 @@ static bool cvTsCheckSparse(const CvSparseMat* m1, const CvSparseMat* m2, double
else if( fabs(*(double*)v1 - *(double*)v2) > eps*(fabs(*(double*)v2) + 1) ) else if( fabs(*(double*)v1 - *(double*)v2) > eps*(fabs(*(double*)v2) + 1) )
return false; return false;
} }
return true; return true;
} }
@ -94,27 +94,27 @@ protected:
test_case_count = 4; test_case_count = 4;
int progress = 0; int progress = 0;
MemStorage storage(cvCreateMemStorage(0)); MemStorage storage(cvCreateMemStorage(0));
for( int idx = 0; idx < test_case_count; idx++ ) for( int idx = 0; idx < test_case_count; idx++ )
{ {
ts->update_context( this, idx, false ); ts->update_context( this, idx, false );
progress = update_progress( progress, idx, test_case_count, 0 ); progress = update_progress( progress, idx, test_case_count, 0 );
cvClearMemStorage(storage); cvClearMemStorage(storage);
bool mem = (idx % 4) >= 2; bool mem = (idx % 4) >= 2;
string filename = tempfile(idx % 2 ? ".yml" : ".xml"); string filename = tempfile(idx % 2 ? ".yml" : ".xml");
FileStorage fs(filename, FileStorage::WRITE + (mem ? FileStorage::MEMORY : 0)); FileStorage fs(filename, FileStorage::WRITE + (mem ? FileStorage::MEMORY : 0));
int test_int = (int)cvtest::randInt(rng); int test_int = (int)cvtest::randInt(rng);
double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9); double test_real = (cvtest::randInt(rng)%2?1:-1)*exp(cvtest::randReal(rng)*18-9);
string test_string = "vw wv23424rt\"&amp;&lt;&gt;&amp;&apos;@#$@$%$%&%IJUKYILFD@#$@%$&*&() "; string test_string = "vw wv23424rt\"&amp;&lt;&gt;&amp;&apos;@#$@$%$%&%IJUKYILFD@#$@%$&*&() ";
int depth = cvtest::randInt(rng) % (CV_64F+1); int depth = cvtest::randInt(rng) % (CV_64F+1);
int cn = cvtest::randInt(rng) % 4 + 1; int cn = cvtest::randInt(rng) % 4 + 1;
Mat test_mat(cvtest::randInt(rng)%30+1, cvtest::randInt(rng)%30+1, CV_MAKETYPE(depth, cn)); 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, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
if( depth >= CV_32F ) if( depth >= CV_32F )
{ {
@ -123,11 +123,11 @@ protected:
rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1)); rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
multiply(test_mat, test_mat_scale, test_mat); multiply(test_mat, test_mat_scale, test_mat);
} }
CvSeq* seq = cvCreateSeq(test_mat.type(), (int)sizeof(CvSeq), CvSeq* seq = cvCreateSeq(test_mat.type(), (int)sizeof(CvSeq),
(int)test_mat.elemSize(), storage); (int)test_mat.elemSize(), storage);
cvSeqPushMulti(seq, test_mat.data, test_mat.cols*test_mat.rows); cvSeqPushMulti(seq, test_mat.data, test_mat.cols*test_mat.rows);
CvGraph* graph = cvCreateGraph( CV_ORIENTED_GRAPH, CvGraph* graph = cvCreateGraph( CV_ORIENTED_GRAPH,
sizeof(CvGraph), sizeof(CvGraphVtx), sizeof(CvGraph), sizeof(CvGraphVtx),
sizeof(CvGraphEdge), storage ); sizeof(CvGraphEdge), storage );
@ -141,12 +141,12 @@ protected:
cvGraphAddEdge(graph, edges[i][0], edges[i][1], 0, &edge); cvGraphAddEdge(graph, edges[i][0], edges[i][1], 0, &edge);
edge->weight = (float)(i+1); edge->weight = (float)(i+1);
} }
depth = cvtest::randInt(rng) % (CV_64F+1); depth = cvtest::randInt(rng) % (CV_64F+1);
cn = cvtest::randInt(rng) % 4 + 1; cn = cvtest::randInt(rng) % 4 + 1;
int sz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1}; int sz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1};
MatND test_mat_nd(3, sz, CV_MAKETYPE(depth, cn)); 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, CV_RAND_UNI, Scalar::all(ranges[depth][0]), Scalar::all(ranges[depth][1]));
if( depth >= CV_32F ) if( depth >= CV_32F )
{ {
@ -155,44 +155,44 @@ protected:
rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1)); rng0.fill(test_mat_scale, CV_RAND_UNI, Scalar::all(-1), Scalar::all(1));
multiply(test_mat_nd, test_mat_scale, test_mat_nd); multiply(test_mat_nd, test_mat_scale, test_mat_nd);
} }
int ssz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1, int ssz[] = {cvtest::randInt(rng)%10+1, cvtest::randInt(rng)%10+1,
cvtest::randInt(rng)%10+1,cvtest::randInt(rng)%10+1}; cvtest::randInt(rng)%10+1,cvtest::randInt(rng)%10+1};
SparseMat test_sparse_mat = cvTsGetRandomSparseMat(4, ssz, cvtest::randInt(rng)%(CV_64F+1), SparseMat test_sparse_mat = cvTsGetRandomSparseMat(4, ssz, cvtest::randInt(rng)%(CV_64F+1),
cvtest::randInt(rng) % 10000, 0, 100, rng); cvtest::randInt(rng) % 10000, 0, 100, rng);
fs << "test_int" << test_int << "test_real" << test_real << "test_string" << test_string; fs << "test_int" << test_int << "test_real" << test_real << "test_string" << test_string;
fs << "test_mat" << test_mat; fs << "test_mat" << test_mat;
fs << "test_mat_nd" << test_mat_nd; fs << "test_mat_nd" << test_mat_nd;
fs << "test_sparse_mat" << test_sparse_mat; fs << "test_sparse_mat" << test_sparse_mat;
fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" << fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
"{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]"; "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:"; fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1}; const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0]))); fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
fs << "]" << "}"; fs << "]" << "}";
cvWriteComment(*fs, "test comment", 0); cvWriteComment(*fs, "test comment", 0);
fs.writeObj("test_seq", seq); fs.writeObj("test_seq", seq);
fs.writeObj("test_graph",graph); fs.writeObj("test_graph",graph);
CvGraph* graph2 = (CvGraph*)cvClone(graph); CvGraph* graph2 = (CvGraph*)cvClone(graph);
string content = fs.releaseAndGetString(); string content = fs.releaseAndGetString();
if(!fs.open(mem ? content : filename, FileStorage::READ + (mem ? FileStorage::MEMORY : 0))) if(!fs.open(mem ? content : filename, FileStorage::READ + (mem ? FileStorage::MEMORY : 0)))
{ {
ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", !mem ? filename.c_str() : content.c_str()); ts->printf( cvtest::TS::LOG, "filename %s can not be read\n", !mem ? filename.c_str() : content.c_str());
ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA ); ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
return; return;
} }
int real_int = (int)fs["test_int"]; int real_int = (int)fs["test_int"];
double real_real = (double)fs["test_real"]; double real_real = (double)fs["test_real"];
string real_string = (string)fs["test_string"]; string real_string = (string)fs["test_string"];
if( real_int != test_int || if( real_int != test_int ||
fabs(real_real - test_real) > DBL_EPSILON*(fabs(test_real)+1) || fabs(real_real - test_real) > DBL_EPSILON*(fabs(test_real)+1) ||
real_string != test_string ) real_string != test_string )
@ -201,7 +201,7 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
CvMat* m = (CvMat*)fs["test_mat"].readObj(); CvMat* m = (CvMat*)fs["test_mat"].readObj();
CvMat _test_mat = test_mat; CvMat _test_mat = test_mat;
double max_diff = 0; double max_diff = 0;
@ -209,7 +209,7 @@ protected:
cvReshape(m, &stub1, 1, 0); cvReshape(m, &stub1, 1, 0);
cvReshape(&_test_mat, &_test_stub1, 1, 0); cvReshape(&_test_mat, &_test_stub1, 1, 0);
vector<int> pt; vector<int> pt;
if( !m || !CV_IS_MAT(m) || m->rows != test_mat.rows || m->cols != test_mat.cols || if( !m || !CV_IS_MAT(m) || m->rows != test_mat.rows || m->cols != test_mat.cols ||
cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 ) cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
{ {
@ -221,26 +221,26 @@ protected:
} }
if( m && CV_IS_MAT(m)) if( m && CV_IS_MAT(m))
cvReleaseMat(&m); cvReleaseMat(&m);
CvMatND* m_nd = (CvMatND*)fs["test_mat_nd"].readObj(); CvMatND* m_nd = (CvMatND*)fs["test_mat_nd"].readObj();
CvMatND _test_mat_nd = test_mat_nd; CvMatND _test_mat_nd = test_mat_nd;
if( !m_nd || !CV_IS_MATND(m_nd) ) if( !m_nd || !CV_IS_MATND(m_nd) )
{ {
ts->printf( cvtest::TS::LOG, "the read nd-matrix is not correct\n" ); ts->printf( cvtest::TS::LOG, "the read nd-matrix is not correct\n" );
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
CvMat stub, _test_stub; CvMat stub, _test_stub;
cvGetMat(m_nd, &stub, 0, 1); cvGetMat(m_nd, &stub, 0, 1);
cvGetMat(&_test_mat_nd, &_test_stub, 0, 1); cvGetMat(&_test_mat_nd, &_test_stub, 0, 1);
cvReshape(&stub, &stub1, 1, 0); cvReshape(&stub, &stub1, 1, 0);
cvReshape(&_test_stub, &_test_stub1, 1, 0); cvReshape(&_test_stub, &_test_stub1, 1, 0);
if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) || if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
!CV_ARE_SIZES_EQ(&stub, &_test_stub) || !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
//cvNorm(&stub, &_test_stub, CV_L2) != 0 ) //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 ) cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
{ {
ts->printf( cvtest::TS::LOG, "readObj method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n", ts->printf( cvtest::TS::LOG, "readObj method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
@ -249,16 +249,16 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
MatND mat_nd2; MatND mat_nd2;
fs["test_mat_nd"] >> mat_nd2; fs["test_mat_nd"] >> mat_nd2;
CvMatND m_nd2 = mat_nd2; CvMatND m_nd2 = mat_nd2;
cvGetMat(&m_nd2, &stub, 0, 1); cvGetMat(&m_nd2, &stub, 0, 1);
cvReshape(&stub, &stub1, 1, 0); cvReshape(&stub, &stub1, 1, 0);
if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) || if( !CV_ARE_TYPES_EQ(&stub, &_test_stub) ||
!CV_ARE_SIZES_EQ(&stub, &_test_stub) || !CV_ARE_SIZES_EQ(&stub, &_test_stub) ||
//cvNorm(&stub, &_test_stub, CV_L2) != 0 ) //cvNorm(&stub, &_test_stub, CV_L2) != 0 )
cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 ) cvtest::cmpEps( Mat(&stub1), Mat(&_test_stub1), &max_diff, 0, &pt, true) < 0 )
{ {
ts->printf( cvtest::TS::LOG, "C++ method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n", ts->printf( cvtest::TS::LOG, "C++ method: the read nd matrix is not correct: (%.20g vs %.20g) vs at (%d,%d)\n",
@ -267,16 +267,16 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
cvRelease((void**)&m_nd); cvRelease((void**)&m_nd);
Ptr<CvSparseMat> m_s = (CvSparseMat*)fs["test_sparse_mat"].readObj(); Ptr<CvSparseMat> m_s = (CvSparseMat*)fs["test_sparse_mat"].readObj();
Ptr<CvSparseMat> _test_sparse_ = (CvSparseMat*)test_sparse_mat; Ptr<CvSparseMat> _test_sparse_ = (CvSparseMat*)test_sparse_mat;
Ptr<CvSparseMat> _test_sparse = (CvSparseMat*)cvClone(_test_sparse_); Ptr<CvSparseMat> _test_sparse = (CvSparseMat*)cvClone(_test_sparse_);
SparseMat m_s2; SparseMat m_s2;
fs["test_sparse_mat"] >> m_s2; fs["test_sparse_mat"] >> m_s2;
Ptr<CvSparseMat> _m_s2 = (CvSparseMat*)m_s2; Ptr<CvSparseMat> _m_s2 = (CvSparseMat*)m_s2;
if( !m_s || !CV_IS_SPARSE_MAT(m_s) || if( !m_s || !CV_IS_SPARSE_MAT(m_s) ||
!cvTsCheckSparse(m_s, _test_sparse,0) || !cvTsCheckSparse(m_s, _test_sparse,0) ||
!cvTsCheckSparse(_m_s2, _test_sparse,0)) !cvTsCheckSparse(_m_s2, _test_sparse,0))
@ -285,7 +285,7 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
FileNode tl = fs["test_list"]; FileNode tl = fs["test_list"];
if( tl.type() != FileNode::SEQ || tl.size() != 6 || if( tl.type() != FileNode::SEQ || tl.size() != 6 ||
fabs((double)tl[0] - 0.0000000000001) >= DBL_EPSILON || fabs((double)tl[0] - 0.0000000000001) >= DBL_EPSILON ||
@ -302,15 +302,15 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
FileNode tm = fs["test_map"]; FileNode tm = fs["test_map"];
FileNode tm_lbp = tm["lbp"]; FileNode tm_lbp = tm["lbp"];
int real_x = (int)tm["x"]; int real_x = (int)tm["x"];
int real_y = (int)tm["y"]; int real_y = (int)tm["y"];
int real_width = (int)tm["width"]; int real_width = (int)tm["width"];
int real_height = (int)tm["height"]; int real_height = (int)tm["height"];
int real_lbp_val = 0; int real_lbp_val = 0;
FileNodeIterator it; FileNodeIterator it;
it = tm_lbp.begin(); it = tm_lbp.begin();
@ -332,7 +332,7 @@ protected:
real_lbp_val |= (int)*it2 << 4; real_lbp_val |= (int)*it2 << 4;
it2 += -1; it2 += -1;
CV_Assert( it == it2 ); CV_Assert( it == it2 );
if( tm.type() != FileNode::MAP || tm.size() != 5 || if( tm.type() != FileNode::MAP || tm.size() != 5 ||
real_x != 1 || real_x != 1 ||
real_y != 2 || real_y != 2 ||
@ -346,7 +346,7 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
CvGraph* graph3 = (CvGraph*)fs["test_graph"].readObj(); CvGraph* graph3 = (CvGraph*)fs["test_graph"].readObj();
if(graph2->active_count != vcount || graph3->active_count != vcount || if(graph2->active_count != vcount || graph3->active_count != vcount ||
graph2->edges->active_count != ecount || graph3->edges->active_count != ecount) graph2->edges->active_count != ecount || graph3->edges->active_count != ecount)
@ -355,7 +355,7 @@ protected:
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
return; return;
} }
for( i = 0; i < ecount; i++ ) for( i = 0; i < ecount; i++ )
{ {
CvGraphEdge* edge2 = cvFindGraphEdge(graph2, edges[i][0], edges[i][1]); CvGraphEdge* edge2 = cvFindGraphEdge(graph2, edges[i][0], edges[i][1]);
@ -368,7 +368,7 @@ protected:
return; return;
} }
} }
fs.release(); fs.release();
if( !mem ) if( !mem )
remove(filename.c_str()); remove(filename.c_str());
@ -383,13 +383,14 @@ class CV_MiscIOTest : public cvtest::BaseTest
{ {
public: public:
CV_MiscIOTest() {} CV_MiscIOTest() {}
~CV_MiscIOTest() {} ~CV_MiscIOTest() {}
protected: protected:
void run(int) void run(int)
{ {
try try
{ {
FileStorage fs("test.xml", FileStorage::WRITE); string fname = cv::tempfile(".xml");
FileStorage fs(fname, FileStorage::WRITE);
vector<int> mi, mi2, mi3, mi4; vector<int> mi, mi2, mi3, mi4;
vector<Mat> mv, mv2, mv3, mv4; vector<Mat> mv, mv2, mv3, mv4;
Mat m(10, 9, CV_32F); Mat m(10, 9, CV_32F);
@ -403,7 +404,7 @@ protected:
fs << "mv3" << mv3; fs << "mv3" << mv3;
fs << "empty" << empty; fs << "empty" << empty;
fs.release(); fs.release();
fs.open("test.xml", FileStorage::READ); fs.open(fname, FileStorage::READ);
fs["mi"] >> mi2; fs["mi"] >> mi2;
fs["mv"] >> mv2; fs["mv"] >> mv2;
fs["mi3"] >> mi4; fs["mi3"] >> mi4;
@ -429,7 +430,7 @@ TEST(Core_InputOutput, misc) { CV_MiscIOTest test; test.safe_run(); }
{ {
public: public:
CV_BigMatrixIOTest() {} CV_BigMatrixIOTest() {}
~CV_BigMatrixIOTest() {} ~CV_BigMatrixIOTest() {}
protected: protected:
void run(int) void run(int)
{ {
@ -439,7 +440,7 @@ protected:
int N = 1000, M = 1200000; int N = 1000, M = 1200000;
Mat mat(M, N, CV_32F); Mat mat(M, N, CV_32F);
rng.fill(mat, RNG::UNIFORM, 0, 1); rng.fill(mat, RNG::UNIFORM, 0, 1);
FileStorage fs("test.xml", FileStorage::WRITE); FileStorage fs(cv::tempfile(".xml"), FileStorage::WRITE);
fs << "mat" << mat; fs << "mat" << mat;
fs.release(); fs.release();
} }

View File

@ -328,7 +328,7 @@ public:
float patternScale = 22.0f, float patternScale = 22.0f,
int nOctaves = 4, int nOctaves = 4,
const vector<int>& selectedPairs = vector<int>()); const vector<int>& selectedPairs = vector<int>());
FREAK( const FREAK& rhs ); FREAK( const FREAK& rhs );
FREAK& operator=( const FREAK& ); FREAK& operator=( const FREAK& );
virtual ~FREAK(); virtual ~FREAK();
@ -349,51 +349,51 @@ public:
vector<int> selectPairs( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints, vector<int> selectPairs( const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints,
const double corrThresh = 0.7, bool verbose = true ); const double corrThresh = 0.7, bool verbose = true );
AlgorithmInfo* info() const; AlgorithmInfo* info() const;
enum enum
{ {
NB_SCALES = 64, NB_PAIRS = 512, NB_ORIENPAIRS = 45 NB_SCALES = 64, NB_PAIRS = 512, NB_ORIENPAIRS = 45
}; };
protected: protected:
virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const; virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
void buildPattern(); void buildPattern();
uchar meanIntensity( const Mat& image, const Mat& integral, const float kp_x, const float kp_y, uchar meanIntensity( const Mat& image, const Mat& integral, const float kp_x, const float kp_y,
const unsigned int scale, const unsigned int rot, const unsigned int point ) const; const unsigned int scale, const unsigned int rot, const unsigned int point ) const;
bool orientationNormalized; //true if the orientation is normalized, false otherwise bool orientationNormalized; //true if the orientation is normalized, false otherwise
bool scaleNormalized; //true if the scale is normalized, false otherwise bool scaleNormalized; //true if the scale is normalized, false otherwise
double patternScale; //scaling of the pattern double patternScale; //scaling of the pattern
int nOctaves; //number of octaves int nOctaves; //number of octaves
bool extAll; // true if all pairs need to be extracted for pairs selection bool extAll; // true if all pairs need to be extracted for pairs selection
double patternScale0; double patternScale0;
int nOctaves0; int nOctaves0;
vector<int> selectedPairs0; vector<int> selectedPairs0;
struct PatternPoint struct PatternPoint
{ {
float x; // x coordinate relative to center float x; // x coordinate relative to center
float y; // x coordinate relative to center float y; // x coordinate relative to center
float sigma; // Gaussian smoothing sigma float sigma; // Gaussian smoothing sigma
}; };
struct DescriptionPair struct DescriptionPair
{ {
uchar i; // index of the first point uchar i; // index of the first point
uchar j; // index of the second point uchar j; // index of the second point
}; };
struct OrientationPair struct OrientationPair
{ {
uchar i; // index of the first point uchar i; // index of the first point
uchar j; // index of the second point uchar j; // index of the second point
int weight_dx; // dx/(norm_sq))*4096 int weight_dx; // dx/(norm_sq))*4096
int weight_dy; // dy/(norm_sq))*4096 int weight_dy; // dy/(norm_sq))*4096
}; };
vector<PatternPoint> patternLookup; // look-up table for the pattern points (position+sigma of all points at all scales and orientation) vector<PatternPoint> patternLookup; // look-up table for the pattern points (position+sigma of all points at all scales and orientation)
int patternSizes[NB_SCALES]; // size of the pattern at a specific scale (used to check if a point is within image boundaries) int patternSizes[NB_SCALES]; // size of the pattern at a specific scale (used to check if a point is within image boundaries)
DescriptionPair descriptionPairs[NB_PAIRS]; DescriptionPair descriptionPairs[NB_PAIRS];
OrientationPair orientationPairs[NB_ORIENPAIRS]; OrientationPair orientationPairs[NB_ORIENPAIRS];
@ -603,7 +603,7 @@ public:
// TODO implement read/write // TODO implement read/write
virtual bool empty() const; virtual bool empty() const;
AlgorithmInfo* info() const; AlgorithmInfo* info() const;
protected: protected:
@ -641,8 +641,8 @@ protected:
class CV_EXPORTS AdjusterAdapter: public FeatureDetector class CV_EXPORTS AdjusterAdapter: public FeatureDetector
{ {
public: public:
/** pure virtual interface /** pure virtual interface
*/ */
virtual ~AdjusterAdapter() {} virtual ~AdjusterAdapter() {}
/** too few features were detected so, adjust the detector params accordingly /** too few features were detected so, adjust the detector params accordingly
* \param min the minimum number of desired features * \param min the minimum number of desired features
@ -682,7 +682,7 @@ public:
/** \param adjuster an AdjusterAdapter that will do the detection and parameter adjustment /** \param adjuster an AdjusterAdapter that will do the detection and parameter adjustment
* \param max_features the maximum desired number of features * \param max_features the maximum desired number of features
* \param max_iters the maximum number of times to try to adjust the feature detector params * \param max_iters the maximum number of times to try to adjust the feature detector params
* for the FastAdjuster this can be high, but with Star or Surf this can get time consuming * for the FastAdjuster this can be high, but with Star or Surf this can get time consuming
* \param min_features the minimum desired features * \param min_features the minimum desired features
*/ */
DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 ); DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, int min_features=400, int max_features=500, int max_iters=5 );
@ -693,8 +693,8 @@ protected:
virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const; virtual void detectImpl( const Mat& image, vector<KeyPoint>& keypoints, const Mat& mask=Mat() ) const;
private: private:
DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&); DynamicAdaptedFeatureDetector& operator=(const DynamicAdaptedFeatureDetector&);
DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&); DynamicAdaptedFeatureDetector(const DynamicAdaptedFeatureDetector&);
int escape_iters_; int escape_iters_;
int min_features_, max_features_; int min_features_, max_features_;
@ -792,7 +792,7 @@ public:
virtual bool empty() const; virtual bool empty() const;
protected: protected:
virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const; virtual void computeImpl( const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors ) const;
Ptr<DescriptorExtractor> descriptorExtractor; Ptr<DescriptorExtractor> descriptorExtractor;
}; };
@ -962,7 +962,7 @@ class CV_EXPORTS_W DescriptorMatcher : public Algorithm
public: public:
virtual ~DescriptorMatcher(); virtual ~DescriptorMatcher();
/* /*
* Add descriptors to train descriptor collection. * Add descriptors to train descriptor collection.
* descriptors Descriptors to add. Each descriptors[i] is a descriptors set from one image. * descriptors Descriptors to add. Each descriptors[i] is a descriptors set from one image.
*/ */
@ -1078,7 +1078,7 @@ protected:
static bool isMaskedOut( const vector<Mat>& masks, int queryIdx ); static bool isMaskedOut( const vector<Mat>& masks, int queryIdx );
static Mat clone_op( Mat m ) { return m.clone(); } static Mat clone_op( Mat m ) { return m.clone(); }
void checkMasks( const vector<Mat>& masks, int queryDescriptorsCount ) const; void checkMasks( const vector<Mat>& masks, int queryDescriptorsCount ) const;
// Collection of descriptors from train images. // Collection of descriptors from train images.
vector<Mat> trainDescCollection; vector<Mat> trainDescCollection;

View File

@ -48,8 +48,8 @@ class CV_FastTest : public cvtest::BaseTest
{ {
public: public:
CV_FastTest(); CV_FastTest();
~CV_FastTest(); ~CV_FastTest();
protected: protected:
void run(int); void run(int);
}; };
@ -58,13 +58,13 @@ CV_FastTest::~CV_FastTest() {}
void CV_FastTest::run( int ) void CV_FastTest::run( int )
{ {
Mat image1 = imread(string(ts->get_data_path()) + "inpaint/orig.jpg"); Mat image1 = imread(string(ts->get_data_path()) + "inpaint/orig.jpg");
Mat image2 = imread(string(ts->get_data_path()) + "cameracalibration/chess9.jpg"); Mat image2 = imread(string(ts->get_data_path()) + "cameracalibration/chess9.jpg");
string xml = string(ts->get_data_path()) + "fast/result.xml"; string xml = string(ts->get_data_path()) + "fast/result.xml";
if (image1.empty() || image2.empty()) if (image1.empty() || image2.empty())
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
return; return;
} }
@ -73,20 +73,20 @@ void CV_FastTest::run( int )
cvtColor(image2, gray2, CV_BGR2GRAY); cvtColor(image2, gray2, CV_BGR2GRAY);
vector<KeyPoint> keypoints1; vector<KeyPoint> keypoints1;
vector<KeyPoint> keypoints2; vector<KeyPoint> keypoints2;
FAST(gray1, keypoints1, 30); FAST(gray1, keypoints1, 30);
FAST(gray2, keypoints2, 30); FAST(gray2, keypoints2, 30);
for(size_t i = 0; i < keypoints1.size(); ++i) for(size_t i = 0; i < keypoints1.size(); ++i)
{ {
const KeyPoint& kp = keypoints1[i]; const KeyPoint& kp = keypoints1[i];
cv::circle(image1, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0)); cv::circle(image1, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0));
} }
for(size_t i = 0; i < keypoints2.size(); ++i) for(size_t i = 0; i < keypoints2.size(); ++i)
{ {
const KeyPoint& kp = keypoints2[i]; const KeyPoint& kp = keypoints2[i];
cv::circle(image2, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0)); cv::circle(image2, kp.pt, cvRound(kp.size/2), CV_RGB(255, 0, 0));
} }
Mat kps1(1, (int)(keypoints1.size() * sizeof(KeyPoint)), CV_8U, &keypoints1[0]); Mat kps1(1, (int)(keypoints1.size() * sizeof(KeyPoint)), CV_8U, &keypoints1[0]);
@ -99,14 +99,14 @@ void CV_FastTest::run( int )
fs << "exp_kps1" << kps1; fs << "exp_kps1" << kps1;
fs << "exp_kps2" << kps2; fs << "exp_kps2" << kps2;
fs.release(); fs.release();
} }
if (!fs.isOpened()) if (!fs.isOpened())
fs.open(xml, FileStorage::READ); fs.open(xml, FileStorage::READ);
Mat exp_kps1, exp_kps2; Mat exp_kps1, exp_kps2;
read( fs["exp_kps1"], exp_kps1, Mat() ); read( fs["exp_kps1"], exp_kps1, Mat() );
read( fs["exp_kps2"], exp_kps2, Mat() ); read( fs["exp_kps2"], exp_kps2, Mat() );
fs.release(); fs.release();
if ( 0 != norm(exp_kps1, kps1, NORM_L2) || 0 != norm(exp_kps2, kps2, NORM_L2)) if ( 0 != norm(exp_kps1, kps1, NORM_L2) || 0 != norm(exp_kps2, kps2, NORM_L2))
@ -114,7 +114,7 @@ void CV_FastTest::run( int )
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return; return;
} }
/* cv::namedWindow("Img1"); cv::imshow("Img1", image1); /* cv::namedWindow("Img1"); cv::imshow("Img1", image1);
cv::namedWindow("Img2"); cv::imshow("Img2", image2); cv::namedWindow("Img2"); cv::imshow("Img2", image2);
cv::waitKey(0);*/ cv::waitKey(0);*/

View File

@ -50,8 +50,8 @@ using namespace cv;
class CV_MserTest : public cvtest::BaseTest class CV_MserTest : public cvtest::BaseTest
{ {
public: public:
CV_MserTest(); CV_MserTest();
protected: protected:
void run(int); void run(int);
int LoadBoxes(const char* path, vector<CvBox2D>& boxes); int LoadBoxes(const char* path, vector<CvBox2D>& boxes);
int SaveBoxes(const char* path, const vector<CvBox2D>& boxes); int SaveBoxes(const char* path, const vector<CvBox2D>& boxes);
@ -71,7 +71,7 @@ int CV_MserTest::LoadBoxes(const char* path, vector<CvBox2D>& boxes)
{ {
return 0; return 0;
} }
while (!feof(f)) while (!feof(f))
{ {
CvBox2D box; CvBox2D box;
@ -175,12 +175,12 @@ void CV_MserTest::run(int)
{ {
RotatedRect box = fitEllipse(msers[i]); RotatedRect box = fitEllipse(msers[i]);
box.angle=(float)CV_PI/2-box.angle; box.angle=(float)CV_PI/2-box.angle;
boxes.push_back(box); boxes.push_back(box);
} }
string boxes_path = string(ts->get_data_path()) + "mser/boxes.txt"; string boxes_path = string(ts->get_data_path()) + "mser/boxes.txt";
string calc_boxes_path = string(ts->get_data_path()) + "mser/boxes.calc.txt"; string calc_boxes_path = string(ts->get_data_path()) + "mser/boxes.calc.txt";
if (!LoadBoxes(boxes_path.c_str(),boxes_orig)) if (!LoadBoxes(boxes_path.c_str(),boxes_orig))
{ {
SaveBoxes(boxes_path.c_str(),boxes); SaveBoxes(boxes_path.c_str(),boxes);

View File

@ -128,7 +128,7 @@ void NearestNeighborTest::run( int /*start_from*/ ) {
randu( desc, Scalar(minValue), Scalar(maxValue) ); randu( desc, Scalar(minValue), Scalar(maxValue) );
createModel( desc ); createModel( desc );
tempCode = checkGetPoins( desc ); tempCode = checkGetPoins( desc );
if( tempCode != cvtest::TS::OK ) if( tempCode != cvtest::TS::OK )
{ {
@ -149,9 +149,9 @@ void NearestNeighborTest::run( int /*start_from*/ ) {
ts->printf( cvtest::TS::LOG, "bad accuracy of Find \n" ); ts->printf( cvtest::TS::LOG, "bad accuracy of Find \n" );
code = tempCode; code = tempCode;
} }
releaseModel(); releaseModel();
ts->set_failed_test_info( code ); ts->set_failed_test_info( code );
} }
@ -398,7 +398,7 @@ void CV_FlannSavedIndexTest::createModel(const cv::Mat &data)
} }
string filename = tempfile(); string filename = tempfile();
index->save( filename ); index->save( filename );
createIndex( data, SavedIndexParams(filename.c_str())); createIndex( data, SavedIndexParams(filename.c_str()));
remove( filename.c_str() ); remove( filename.c_str() );
} }

View File

@ -529,7 +529,7 @@ GPU_PERF_TEST(VideoWriter, cv::gpu::DeviceInfo, std::string)
cv::gpu::setDevice(devInfo.deviceID()); cv::gpu::setDevice(devInfo.deviceID());
std::string inputFile = perf::TestBase::getDataPath(std::string("gpu/video/") + GET_PARAM(1)); std::string inputFile = perf::TestBase::getDataPath(std::string("gpu/video/") + GET_PARAM(1));
std::string outputFile = inputFile.substr(0, inputFile.find('.')) + "_test.avi"; std::string outputFile = cv::tempfile(".avi");
cv::VideoCapture reader(inputFile); cv::VideoCapture reader(inputFile);
ASSERT_TRUE( reader.isOpened() ); ASSERT_TRUE( reader.isOpened() );

View File

@ -338,7 +338,7 @@ GPU_PERF_TEST(VideoWriter, cv::gpu::DeviceInfo, std::string)
const double FPS = 25.0; const double FPS = 25.0;
std::string inputFile = perf::TestBase::getDataPath(std::string("gpu/video/") + GET_PARAM(1)); std::string inputFile = perf::TestBase::getDataPath(std::string("gpu/video/") + GET_PARAM(1));
std::string outputFile = inputFile.substr(0, inputFile.find('.')) + "_test.avi"; std::string outputFile = cv::tempfile(".avi");
cv::VideoCapture reader(inputFile); cv::VideoCapture reader(inputFile);
ASSERT_TRUE( reader.isOpened() ); ASSERT_TRUE( reader.isOpened() );

View File

@ -687,7 +687,7 @@ PARAM_TEST_CASE(VideoWriter, cv::gpu::DeviceInfo, std::string)
cv::gpu::setDevice(devInfo.deviceID()); cv::gpu::setDevice(devInfo.deviceID());
inputFile = std::string(cvtest::TS::ptr()->get_data_path()) + "video/" + inputFile; inputFile = std::string(cvtest::TS::ptr()->get_data_path()) + "video/" + inputFile;
outputFile = inputFile.substr(0, inputFile.find('.')) + "_test.avi"; outputFile = cv::tempfile(".avi");
} }
}; };

View File

@ -59,7 +59,7 @@ public:
const int img_c = 4096; const int img_c = 4096;
const double fps0 = 15; const double fps0 = 15;
const double time_sec = 1; const double time_sec = 1;
const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]); const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]);
bool created = false; bool created = false;
@ -68,7 +68,7 @@ public:
{ {
stringstream s; s << codec_bmp_tags[j].tag; stringstream s; s << codec_bmp_tags[j].tag;
int tag = codec_bmp_tags[j].tag; int tag = codec_bmp_tags[j].tag;
if( tag != MKTAG('H', '2', '6', '3') && if( tag != MKTAG('H', '2', '6', '3') &&
tag != MKTAG('H', '2', '6', '1') && tag != MKTAG('H', '2', '6', '1') &&
//tag != MKTAG('D', 'I', 'V', 'X') && //tag != MKTAG('D', 'I', 'V', 'X') &&
@ -93,7 +93,7 @@ public:
{ {
double fps = fps0; double fps = fps0;
Size frame_s = Size(img_c, img_r); Size frame_s = Size(img_c, img_r);
if( tag == CV_FOURCC('H', '2', '6', '1') ) if( tag == CV_FOURCC('H', '2', '6', '1') )
frame_s = Size(352, 288); frame_s = Size(352, 288);
else if( tag == CV_FOURCC('H', '2', '6', '3') ) else if( tag == CV_FOURCC('H', '2', '6', '3') )
@ -101,10 +101,10 @@ public:
/*else if( tag == CV_FOURCC('M', 'J', 'P', 'G') || /*else if( tag == CV_FOURCC('M', 'J', 'P', 'G') ||
tag == CV_FOURCC('j', 'p', 'e', 'g') ) tag == CV_FOURCC('j', 'p', 'e', 'g') )
frame_s = Size(1920, 1080);*/ frame_s = Size(1920, 1080);*/
if( tag == CV_FOURCC('M', 'P', 'E', 'G') ) if( tag == CV_FOURCC('M', 'P', 'E', 'G') )
fps = 25; fps = 25;
VideoWriter writer(filename, tag, fps, frame_s); VideoWriter writer(filename, tag, fps, frame_s);
if (writer.isOpened() == false) if (writer.isOpened() == false)
@ -157,9 +157,9 @@ public:
Mat img, img_next; Mat img, img_next;
cap >> img; cap >> img;
cap >> img_next; cap >> img_next;
CV_Assert( !img0.empty() && !img.empty() && img_next.empty() ); CV_Assert( !img0.empty() && !img.empty() && img_next.empty() );
double diff = norm(img0, img, CV_C); double diff = norm(img0, img, CV_C);
CV_Assert( diff == 0 ); CV_Assert( diff == 0 );
} }

View File

@ -59,7 +59,7 @@ public:
ts->printf(cvtest::TS::LOG, "finish reading big image\n"); ts->printf(cvtest::TS::LOG, "finish reading big image\n");
if (img.empty()) ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA); if (img.empty()) ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
ts->printf(cvtest::TS::LOG, "start writing big image\n"); ts->printf(cvtest::TS::LOG, "start writing big image\n");
imwrite(string(ts->get_data_path()) + "readwrite/write.png", img); imwrite(cv::tempfile(".png"), img);
ts->printf(cvtest::TS::LOG, "finish writing big image\n"); ts->printf(cvtest::TS::LOG, "finish writing big image\n");
} }
catch(...) catch(...)
@ -72,10 +72,14 @@ public:
string ext_from_int(int ext) string ext_from_int(int ext)
{ {
#ifdef HAVE_PNG
if (ext == 0) return ".png"; if (ext == 0) return ".png";
#endif
if (ext == 1) return ".bmp"; if (ext == 1) return ".bmp";
if (ext == 2) return ".pgm"; if (ext == 2) return ".pgm";
#ifdef HAVE_TIFF
if (ext == 3) return ".tiff"; if (ext == 3) return ".tiff";
#endif
return ""; return "";
} }
@ -92,16 +96,21 @@ public:
for (int k = 1; k <= 5; ++k) for (int k = 1; k <= 5; ++k)
{ {
for (int ext = 0; ext < 4; ++ext) // 0 - png, 1 - bmp, 2 - pgm, 3 - tiff for (int ext = 0; ext < 4; ++ext) // 0 - png, 1 - bmp, 2 - pgm, 3 - tiff
{
if(ext_from_int(ext).empty())
continue;
for (int num_channels = 1; num_channels <= 3; num_channels+=2) for (int num_channels = 1; num_channels <= 3; num_channels+=2)
{ {
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ext_from_int(ext).c_str()); ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ext_from_int(ext).c_str());
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
ts->printf(ts->LOG, "writing image : %s\n", string(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext)).c_str());
imwrite(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext), img);
ts->printf(ts->LOG, "reading test image : %s\n", string(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext)).c_str());
Mat img_test = imread(string(ts->get_data_path()) + "readwrite/test" + ext_from_int(ext), CV_LOAD_IMAGE_UNCHANGED); string img_path = cv::tempfile(ext_from_int(ext).c_str());
ts->printf(ts->LOG, "writing image : %s\n", img_path.c_str());
imwrite(img_path, img);
ts->printf(ts->LOG, "reading test image : %s\n", img_path.c_str());
Mat img_test = imread(img_path, CV_LOAD_IMAGE_UNCHANGED);
if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH); if (img_test.empty()) ts->set_failed_test_info(ts->FAIL_MISMATCH);
@ -115,14 +124,17 @@ public:
ts->set_failed_test_info(ts->FAIL_MISMATCH); ts->set_failed_test_info(ts->FAIL_MISMATCH);
} }
} }
}
#ifdef HAVE_JPEG
for (int num_channels = 1; num_channels <= 3; num_channels+=2) for (int num_channels = 1; num_channels <= 3; num_channels+=2)
{ {
// jpeg // jpeg
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ".jpg"); ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_8U, num_channels, ".jpg");
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0)); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_8U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
string filename = string(ts->get_data_path() + "readwrite/test_" + char(k + 48) + "_c" + char(num_channels + 48) + "_.jpg");
string filename = cv::tempfile(".jpg");
imwrite(filename, img); imwrite(filename, img);
img = imread(filename, CV_LOAD_IMAGE_UNCHANGED); img = imread(filename, CV_LOAD_IMAGE_UNCHANGED);
@ -142,14 +154,17 @@ public:
ts->set_failed_test_info(ts->FAIL_MISMATCH); ts->set_failed_test_info(ts->FAIL_MISMATCH);
} }
} }
#endif
#ifdef HAVE_TIFF
for (int num_channels = 1; num_channels <= 3; num_channels+=2) for (int num_channels = 1; num_channels <= 3; num_channels+=2)
{ {
// tiff // tiff
ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_16U, num_channels, ".tiff"); ts->printf(ts->LOG, "image type depth:%d channels:%d ext: %s\n", CV_16U, num_channels, ".tiff");
Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_16U, num_channels), Scalar::all(0)); Mat img(img_r * k, img_c * k, CV_MAKETYPE(CV_16U, num_channels), Scalar::all(0));
circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255)); circle(img, Point2i((img_c * k) / 2, (img_r * k) / 2), cv::min((img_r * k), (img_c * k)) / 4 , Scalar::all(255));
string filename = string(ts->get_data_path() + "readwrite/test.tiff");
string filename = cv::tempfile(".tiff");
imwrite(filename, img); imwrite(filename, img);
ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str()); ts->printf(ts->LOG, "reading test image : %s\n", filename.c_str());
Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED); Mat img_test = imread(filename, CV_LOAD_IMAGE_UNCHANGED);
@ -171,6 +186,7 @@ public:
ts->set_failed_test_info(ts->FAIL_MISMATCH); ts->set_failed_test_info(ts->FAIL_MISMATCH);
} }
} }
#endif
} }
} }
catch(const cv::Exception & e) catch(const cv::Exception & e)
@ -205,9 +221,7 @@ public:
TEST(Highgui_Image, write_big) { CV_GrfmtWriteBigImageTest test; test.safe_run(); } TEST(Highgui_Image, write_big) { CV_GrfmtWriteBigImageTest test; test.safe_run(); }
#endif #endif
#if defined(HAVE_PNG) && defined(HAVE_TIFF) && defined(HAVE_JPEG)
TEST(Highgui_Image, write_imageseq) { CV_GrfmtWriteSequenceImageTest test; test.safe_run(); } TEST(Highgui_Image, write_imageseq) { CV_GrfmtWriteSequenceImageTest test; test.safe_run(); }
#endif
TEST(Highgui_Image, read_bmp_rle8) { CV_GrfmtReadBMPRLE8Test test; test.safe_run(); } TEST(Highgui_Image, read_bmp_rle8) { CV_GrfmtReadBMPRLE8Test test; test.safe_run(); }

View File

@ -155,7 +155,7 @@ void CV_HighGuiTest::ImageTest(const string& dir)
for(size_t i = 0; i < ext_num; ++i) for(size_t i = 0; i < ext_num; ++i)
{ {
string ext = exts[i]; string ext = exts[i];
string full_name = "img." + ext; string full_name = cv::tempfile(ext.c_str());
ts->printf(ts->LOG, " full_name : %s\n", full_name.c_str()); ts->printf(ts->LOG, " full_name : %s\n", full_name.c_str());
imwrite(full_name, image); imwrite(full_name, image);
@ -225,7 +225,7 @@ void CV_HighGuiTest::ImageTest(const string& dir)
void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt) void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt)
{ {
string src_file = dir + "../cv/shared/video_for_test.avi"; string src_file = dir + "../cv/shared/video_for_test.avi";
string tmp_name = format("video_%s.%s", cvtest::fourccToString(fmt.fourcc).c_str(), fmt.ext.c_str()); string tmp_name = cv::tempfile((cvtest::fourccToString(fmt.fourcc) + "." + fmt.ext).c_str());
ts->printf(ts->LOG, "reading video : %s and converting it to %s\n", src_file.c_str(), tmp_name.c_str()); ts->printf(ts->LOG, "reading video : %s and converting it to %s\n", src_file.c_str(), tmp_name.c_str());
@ -291,8 +291,8 @@ void CV_HighGuiTest::VideoTest(const string& dir, const cvtest::VideoFormat& fmt
if (psnr < thresDbell) if (psnr < thresDbell)
{ {
printf("Too low psnr = %gdb\n", psnr); printf("Too low psnr = %gdb\n", psnr);
imwrite("img.png", img); // imwrite("img.png", img);
imwrite("img1.png", img1); // imwrite("img1.png", img1);
ts->set_failed_test_info(ts->FAIL_MISMATCH); ts->set_failed_test_info(ts->FAIL_MISMATCH);
break; break;
} }
@ -323,7 +323,7 @@ void CV_HighGuiTest::SpecificImageTest(const string& dir)
stringstream s_digit; s_digit << i; stringstream s_digit; s_digit << i;
string full_name = "img_"+s_digit.str()+".bmp"; string full_name = cv::tempfile((s_digit.str() + ".bmp").c_str());
ts->printf(ts->LOG, " full_name : %s\n", full_name.c_str()); ts->printf(ts->LOG, " full_name : %s\n", full_name.c_str());
imwrite(full_name, image); imwrite(full_name, image);
@ -395,7 +395,7 @@ void CV_HighGuiTest::SpecificVideoTest(const string& dir, const cvtest::VideoFor
int fourcc = fmt.fourcc; int fourcc = fmt.fourcc;
string fourcc_str = cvtest::fourccToString(fourcc); string fourcc_str = cvtest::fourccToString(fourcc);
const string video_file = "video_" + fourcc_str + "." + ext; const string video_file = cv::tempfile((fourcc_str + "." + ext).c_str());
Size frame_size(968 & -2, 757 & -2); Size frame_size(968 & -2, 757 & -2);
VideoWriter writer(video_file, fourcc, 25, frame_size, true); VideoWriter writer(video_file, fourcc, 25, frame_size, true);

View File

@ -53,29 +53,27 @@ public:
{ {
framesize = Size(640, 480); framesize = Size(640, 480);
} }
Mat drawFrame(int i) Mat drawFrame(int i)
{ {
Mat mat = Mat::zeros(framesize, CV_8UC3); Mat mat = Mat::zeros(framesize, CV_8UC3);
mat = Scalar(fabs(cos(i*0.08)*255), fabs(sin(i*0.05)*255), i); mat = Scalar(fabs(cos(i*0.08)*255), fabs(sin(i*0.05)*255), i);
putText(mat, format("%03d", i), Point(10, 350), 0, 10, Scalar(128, 255, 255), 15); putText(mat, format("%03d", i), Point(10, 350), 0, 10, Scalar(128, 255, 255), 15);
return mat; return mat;
} }
string getFilename(const cvtest::VideoFormat& fmt) string getFilename(const cvtest::VideoFormat& fmt)
{ {
return format("test_video_%s.%s", cvtest::fourccToString(fmt.fourcc).c_str(), fmt.ext.c_str()); return cv::tempfile((cvtest::fourccToString(fmt.fourcc) + "." + fmt.ext).c_str());
} }
bool CreateTestVideo(const cvtest::VideoFormat& fmt, int framecount) bool CreateTestVideo(const cvtest::VideoFormat& fmt, int framecount, string filename)
{ {
string filename = getFilename(fmt);
VideoWriter writer(filename, fmt.fourcc, 25, framesize, true); VideoWriter writer(filename, fmt.fourcc, 25, framesize, true);
if( !writer.isOpened() ) if( !writer.isOpened() )
return false; return false;
for (int i = 0; i < framecount; ++i) for (int i = 0; i < framecount; ++i)
{ {
Mat img = drawFrame(i); Mat img = drawFrame(i);
@ -87,7 +85,7 @@ public:
void run(int) void run(int)
{ {
int n_frames = 100; int n_frames = 100;
for( int testcase = 0; ; testcase++ ) for( int testcase = 0; ; testcase++ )
{ {
const cvtest::VideoFormat& fmt = cvtest::g_specific_fmt_list[testcase]; const cvtest::VideoFormat& fmt = cvtest::g_specific_fmt_list[testcase];
@ -96,82 +94,82 @@ public:
string filename = getFilename(fmt); string filename = getFilename(fmt);
ts->printf(ts->LOG, "\nFile: %s\n", filename.c_str()); ts->printf(ts->LOG, "\nFile: %s\n", filename.c_str());
if( !CreateTestVideo(fmt, n_frames) ) if( !CreateTestVideo(fmt, n_frames, filename) )
{ {
ts->printf(ts->LOG, "\nError: cannot create video file"); ts->printf(ts->LOG, "\nError: cannot create video file");
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
return; return;
} }
VideoCapture cap(filename); VideoCapture cap(filename);
if (!cap.isOpened()) if (!cap.isOpened())
{ {
ts->printf(ts->LOG, "\nError: cannot read video file."); ts->printf(ts->LOG, "\nError: cannot read video file.");
ts->set_failed_test_info(ts->FAIL_INVALID_TEST_DATA); ts->set_failed_test_info(ts->FAIL_INVALID_TEST_DATA);
return; return;
} }
int N0 = (int)cap.get(CV_CAP_PROP_FRAME_COUNT); int N0 = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
cap.set(CV_CAP_PROP_POS_FRAMES, 0); cap.set(CV_CAP_PROP_POS_FRAMES, 0);
int N = (int)cap.get(CV_CAP_PROP_FRAME_COUNT); int N = (int)cap.get(CV_CAP_PROP_FRAME_COUNT);
if (N != n_frames || N != N0) if (N != n_frames || N != N0)
{ {
ts->printf(ts->LOG, "\nError: returned frame count (N0=%d, N=%d) is different from the reference number %d\n", N0, N, n_frames); ts->printf(ts->LOG, "\nError: returned frame count (N0=%d, N=%d) is different from the reference number %d\n", N0, N, n_frames);
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
return; return;
} }
for (int k = 0; k < N; ++k) for (int k = 0; k < N; ++k)
{ {
int idx = theRNG().uniform(0, N); int idx = theRNG().uniform(0, N);
if( !cap.set(CV_CAP_PROP_POS_FRAMES, idx) ) if( !cap.set(CV_CAP_PROP_POS_FRAMES, idx) )
{ {
ts->printf(ts->LOG, "\nError: cannot seek to frame %d.\n", idx); ts->printf(ts->LOG, "\nError: cannot seek to frame %d.\n", idx);
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
return; return;
} }
int idx1 = (int)cap.get(CV_CAP_PROP_POS_FRAMES); int idx1 = (int)cap.get(CV_CAP_PROP_POS_FRAMES);
Mat img; cap >> img; Mat img; cap >> img;
Mat img0 = drawFrame(idx); Mat img0 = drawFrame(idx);
if( idx != idx1 ) if( idx != idx1 )
{ {
ts->printf(ts->LOG, "\nError: the current position (%d) after seek is different from specified (%d)\n", ts->printf(ts->LOG, "\nError: the current position (%d) after seek is different from specified (%d)\n",
idx1, idx); idx1, idx);
ts->printf(ts->LOG, "Saving both frames ...\n"); ts->printf(ts->LOG, "Saving both frames ...\n");
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
imwrite("opencv_test_highgui_postest_actual.png", img); // imwrite("opencv_test_highgui_postest_actual.png", img);
imwrite("opencv_test_highgui_postest_expected.png", img0); // imwrite("opencv_test_highgui_postest_expected.png", img0);
return; return;
} }
if (img.empty()) if (img.empty())
{ {
ts->printf(ts->LOG, "\nError: cannot read a frame at position %d.\n", idx); ts->printf(ts->LOG, "\nError: cannot read a frame at position %d.\n", idx);
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
return; return;
} }
double err = PSNR(img, img0); double err = PSNR(img, img0);
if( err < 20 ) if( err < 20 )
{ {
ts->printf(ts->LOG, "The frame read after positioning to %d is incorrect (PSNR=%g)\n", idx, err); ts->printf(ts->LOG, "The frame read after positioning to %d is incorrect (PSNR=%g)\n", idx, err);
ts->printf(ts->LOG, "Saving both frames ...\n"); ts->printf(ts->LOG, "Saving both frames ...\n");
ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT);
imwrite("opencv_test_highgui_postest_actual.png", img); // imwrite("opencv_test_highgui_postest_actual.png", img);
imwrite("opencv_test_highgui_postest_expected.png", img0); // imwrite("opencv_test_highgui_postest_expected.png", img0);
return; return;
} }
} }
} }
} }
Size framesize; Size framesize;
}; };

View File

@ -52,10 +52,10 @@ class CV_GrabcutTest : public cvtest::BaseTest
{ {
public: public:
CV_GrabcutTest(); CV_GrabcutTest();
~CV_GrabcutTest(); ~CV_GrabcutTest();
protected: protected:
bool verify(const Mat& mask, const Mat& exp); bool verify(const Mat& mask, const Mat& exp);
void run(int); void run(int);
}; };
CV_GrabcutTest::CV_GrabcutTest() {} CV_GrabcutTest::CV_GrabcutTest() {}
@ -73,29 +73,29 @@ bool CV_GrabcutTest::verify(const Mat& mask, const Mat& exp)
} }
void CV_GrabcutTest::run( int /* start_from */) void CV_GrabcutTest::run( int /* start_from */)
{ {
cvtest::DefaultRngAuto defRng; cvtest::DefaultRngAuto defRng;
Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg"); Mat img = imread(string(ts->get_data_path()) + "shared/airplane.jpg");
Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0); Mat mask_prob = imread(string(ts->get_data_path()) + "grabcut/mask_prob.png", 0);
Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0); Mat exp_mask1 = imread(string(ts->get_data_path()) + "grabcut/exp_mask1.png", 0);
Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0); Mat exp_mask2 = imread(string(ts->get_data_path()) + "grabcut/exp_mask2.png", 0);
if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) || if (img.empty() || (!mask_prob.empty() && img.size() != mask_prob.size()) ||
(!exp_mask1.empty() && img.size() != exp_mask1.size()) || (!exp_mask1.empty() && img.size() != exp_mask1.size()) ||
(!exp_mask2.empty() && img.size() != exp_mask2.size()) ) (!exp_mask2.empty() && img.size() != exp_mask2.size()) )
{ {
ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA); ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA);
return; return;
} }
Rect rect(Point(24, 126), Point(483, 294)); Rect rect(Point(24, 126), Point(483, 294));
Mat exp_bgdModel, exp_fgdModel; Mat exp_bgdModel, exp_fgdModel;
Mat mask; Mat mask;
mask = Scalar(0); mask = Scalar(0);
Mat bgdModel, fgdModel; Mat bgdModel, fgdModel;
grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT ); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT );
grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL ); grabCut( img, mask, rect, bgdModel, fgdModel, 2, GC_EVAL );
// Multiply images by 255 for more visuality of test data. // Multiply images by 255 for more visuality of test data.
@ -109,16 +109,16 @@ void CV_GrabcutTest::run( int /* start_from */)
exp_mask1 = (mask & 1) * 255; exp_mask1 = (mask & 1) * 255;
imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1); imwrite(string(ts->get_data_path()) + "grabcut/exp_mask1.png", exp_mask1);
} }
if (!verify((mask & 1) * 255, exp_mask1)) if (!verify((mask & 1) * 255, exp_mask1))
{ {
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return; return;
} }
mask = mask_prob; mask = mask_prob;
bgdModel.release(); bgdModel.release();
fgdModel.release(); fgdModel.release();
rect = Rect(); rect = Rect();
grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK ); grabCut( img, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_MASK );
grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL ); grabCut( img, mask, rect, bgdModel, fgdModel, 1, GC_EVAL );
@ -128,13 +128,13 @@ void CV_GrabcutTest::run( int /* start_from */)
exp_mask2 = (mask & 1) * 255; exp_mask2 = (mask & 1) * 255;
imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2); imwrite(string(ts->get_data_path()) + "grabcut/exp_mask2.png", exp_mask2);
} }
if (!verify((mask & 1) * 255, exp_mask2)) if (!verify((mask & 1) * 255, exp_mask2))
{ {
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return; return;
} }
ts->set_failed_test_info(cvtest::TS::OK); ts->set_failed_test_info(cvtest::TS::OK);
} }
TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); } TEST(Imgproc_GrabCut, regression) { CV_GrabcutTest test; test.safe_run(); }

View File

@ -50,8 +50,8 @@ class CV_WatershedTest : public cvtest::BaseTest
{ {
public: public:
CV_WatershedTest(); CV_WatershedTest();
~CV_WatershedTest(); ~CV_WatershedTest();
protected: protected:
void run(int); void run(int);
}; };
@ -59,23 +59,23 @@ CV_WatershedTest::CV_WatershedTest() {}
CV_WatershedTest::~CV_WatershedTest() {} CV_WatershedTest::~CV_WatershedTest() {}
void CV_WatershedTest::run( int /* start_from */) void CV_WatershedTest::run( int /* start_from */)
{ {
string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png"; string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png";
Mat exp = imread(exp_path, 0); Mat exp = imread(exp_path, 0);
Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.jpg"); Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.jpg");
FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ); FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ);
if (orig.empty() || !fs.isOpened()) if (orig.empty() || !fs.isOpened())
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
return; return;
} }
CvSeq* cnts = (CvSeq*)fs["contours"].readObj(); CvSeq* cnts = (CvSeq*)fs["contours"].readObj();
Mat markers(orig.size(), CV_32SC1); Mat markers(orig.size(), CV_32SC1);
markers = Scalar(0); markers = Scalar(0);
IplImage iplmrks = markers; IplImage iplmrks = markers;
vector<unsigned char> colors(1); vector<unsigned char> colors(1);
for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i ) for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i )
@ -105,25 +105,25 @@ void CV_WatershedTest::run( int /* start_from */)
if (pixel <= 0 || pixel > compNum) if (pixel <= 0 || pixel > compNum)
continue; // bad result, doing nothing and going to get error latter; continue; // bad result, doing nothing and going to get error latter;
// repaint in saved color to compare with expected; // repaint in saved color to compare with expected;
if(exp.data) if(exp.data)
pixel = colors[pixel]; pixel = colors[pixel];
} }
} }
Mat markers8U; Mat markers8U;
markers.convertTo(markers8U, CV_8U, 1, 1); markers.convertTo(markers8U, CV_8U, 1, 1);
if( exp.empty() || orig.size() != exp.size() ) if( exp.empty() || orig.size() != exp.size() )
{ {
imwrite(exp_path, markers8U); imwrite(exp_path, markers8U);
exp = markers8U; exp = markers8U;
} }
if (0 != norm(markers8U, exp, NORM_INF)) if (0 != norm(markers8U, exp, NORM_INF))
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH ); ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
return; return;
} }
ts->set_failed_test_info(cvtest::TS::OK); ts->set_failed_test_info(cvtest::TS::OK);

View File

@ -366,7 +366,7 @@ void CV_CvEMTest::run( int /*start_from*/ )
int currCode = runCase(caseIndex++, params, trainData, trainLabels, testData, testLabels, sizes); int currCode = runCase(caseIndex++, params, trainData, trainLabels, testData, testLabels, sizes);
code = currCode == cvtest::TS::OK ? code : currCode; code = currCode == cvtest::TS::OK ? code : currCode;
} }
ts->set_failed_test_info( code ); ts->set_failed_test_info( code );
} }
@ -382,7 +382,7 @@ protected:
samples.at<float>(0,0) = 1; samples.at<float>(0,0) = 1;
samples.at<float>(1,0) = 2; samples.at<float>(1,0) = 2;
samples.at<float>(2,0) = 3; samples.at<float>(2,0) = 3;
Mat labels(samples.rows, 1, CV_32S); Mat labels(samples.rows, 1, CV_32S);
CvEMParams params; CvEMParams params;
@ -398,7 +398,7 @@ protected:
// Write out // Write out
string filename = tempfile() + ".xml"; string filename = cv::tempfile(".xml");
{ {
FileStorage fs = FileStorage(filename, FileStorage::WRITE); FileStorage fs = FileStorage(filename, FileStorage::WRITE);
try try

View File

@ -421,7 +421,7 @@ void CV_StereoMatchingTest::run(int)
ts->set_failed_test_info( code ); ts->set_failed_test_info( code );
return; return;
} }
string fullResultFilename = dataPath + ALGORITHMS_DIR + algorithmName + RESULT_FILE; string fullResultFilename = dataPath + ALGORITHMS_DIR + algorithmName + RESULT_FILE;
FileStorage resFS( fullResultFilename, FileStorage::READ ); FileStorage resFS( fullResultFilename, FileStorage::READ );
bool isWrite = true; // write or compare results bool isWrite = true; // write or compare results
@ -660,7 +660,7 @@ class CV_StereoGCTest : public CV_StereoMatchingTest
public: public:
CV_StereoGCTest() CV_StereoGCTest()
{ {
name = "stereogc"; name = "stereogc";
fill(rmsEps.begin(), rmsEps.end(), 3.f); fill(rmsEps.begin(), rmsEps.end(), 3.f);
fracEps[0] = 0.05f; // all fracEps[0] = 0.05f; // all
fracEps[1] = 0.05f; // noOccl fracEps[1] = 0.05f; // noOccl

View File

@ -527,7 +527,7 @@ protected:
firstResult.at<int>(i) = static_cast<int>(em.predict(samples.row(i))[1]); firstResult.at<int>(i) = static_cast<int>(em.predict(samples.row(i))[1]);
// Write out // Write out
string filename = tempfile() + ".xml"; string filename = cv::tempfile(".xml");
{ {
FileStorage fs = FileStorage(filename, FileStorage::WRITE); FileStorage fs = FileStorage(filename, FileStorage::WRITE);
try try

View File

@ -62,7 +62,7 @@ protected:
class CV_AMLTest : public CV_MLBaseTest class CV_AMLTest : public CV_MLBaseTest
{ {
public: public:
CV_AMLTest( const char* _modelName ); CV_AMLTest( const char* _modelName );
protected: protected:
virtual int run_test_case( int testCaseIdx ); virtual int run_test_case( int testCaseIdx );
virtual int validate_test_results( int testCaseIdx ); virtual int validate_test_results( int testCaseIdx );
@ -71,7 +71,7 @@ protected:
class CV_SLMLTest : public CV_MLBaseTest class CV_SLMLTest : public CV_MLBaseTest
{ {
public: public:
CV_SLMLTest( const char* _modelName ); CV_SLMLTest( const char* _modelName );
protected: protected:
virtual int run_test_case( int testCaseIdx ); virtual int run_test_case( int testCaseIdx );
virtual int validate_test_results( int testCaseIdx ); virtual int validate_test_results( int testCaseIdx );

View File

@ -84,7 +84,7 @@ int CV_SLMLTest::validate_test_results( int testCaseIdx )
// 1. compare files // 1. compare files
ifstream f1( fname1.c_str() ), f2( fname2.c_str() ); ifstream f1( fname1.c_str() ), f2( fname2.c_str() );
string s1, s2; string s1, s2;
int lineIdx = 0; int lineIdx = 0;
CV_Assert( f1.is_open() && f2.is_open() ); CV_Assert( f1.is_open() && f2.is_open() );
for( ; !f1.eof() && !f2.eof(); lineIdx++ ) for( ; !f1.eof() && !f2.eof(); lineIdx++ )
{ {

View File

@ -44,7 +44,7 @@
#include <string> #include <string>
#ifdef HAVE_CVCONFIG_H #ifdef HAVE_CVCONFIG_H
#include "cvconfig.h" #include "cvconfig.h"
#endif #endif
@ -61,7 +61,7 @@ const CvRect true_bounding_boxes[3] = {cvRect(0, 45, 362, 452), cvRect(304, 0, 6
class CV_LatentSVMDetectorTest : public cvtest::BaseTest class CV_LatentSVMDetectorTest : public cvtest::BaseTest
{ {
protected: protected:
void run(int); void run(int);
bool isEqual(CvRect r1, CvRect r2, int eps); bool isEqual(CvRect r1, CvRect r2, int eps);
}; };
@ -75,7 +75,7 @@ bool CV_LatentSVMDetectorTest::isEqual(CvRect r1, CvRect r2, int eps)
} }
void CV_LatentSVMDetectorTest::run( int /* start_from */) void CV_LatentSVMDetectorTest::run( int /* start_from */)
{ {
string img_path = string(ts->get_data_path()) + "latentsvmdetector/cat.jpg"; string img_path = string(ts->get_data_path()) + "latentsvmdetector/cat.jpg";
string model_path = string(ts->get_data_path()) + "latentsvmdetector/models_VOC2007/cat.xml"; string model_path = string(ts->get_data_path()) + "latentsvmdetector/models_VOC2007/cat.xml";
int numThreads = -1; int numThreads = -1;
@ -102,7 +102,7 @@ void CV_LatentSVMDetectorTest::run( int /* start_from */)
} }
CvMemStorage* storage = cvCreateMemStorage(0); CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* detections = 0; CvSeq* detections = 0;
detections = cvLatentSvmDetectObjects(image, detector, storage, 0.5f, numThreads); detections = cvLatentSvmDetectObjects(image, detector, storage, 0.5f, numThreads);
if (detections->total != num_detections) if (detections->total != num_detections)
{ {

View File

@ -49,8 +49,8 @@ class CV_InpaintTest : public cvtest::BaseTest
{ {
public: public:
CV_InpaintTest(); CV_InpaintTest();
~CV_InpaintTest(); ~CV_InpaintTest();
protected: protected:
void run(int); void run(int);
}; };
@ -61,43 +61,40 @@ CV_InpaintTest::~CV_InpaintTest() {}
void CV_InpaintTest::run( int ) void CV_InpaintTest::run( int )
{ {
string folder = string(ts->get_data_path()) + "inpaint/"; string folder = string(ts->get_data_path()) + "inpaint/";
Mat orig = imread(folder + "orig.jpg"); Mat orig = imread(folder + "orig.jpg");
Mat exp1 = imread(folder + "exp1.png"); Mat exp1 = imread(folder + "exp1.png");
Mat exp2 = imread(folder + "exp2.png"); Mat exp2 = imread(folder + "exp2.png");
Mat mask = imread(folder + "mask.png"); Mat mask = imread(folder + "mask.png");
if (orig.empty() || exp1.empty() || exp2.empty() || mask.empty()) if (orig.empty() || exp1.empty() || exp2.empty() || mask.empty())
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
return; return;
} }
Mat inv_mask; Mat inv_mask;
mask.convertTo(inv_mask, CV_8UC3, -1.0, 255.0); mask.convertTo(inv_mask, CV_8UC3, -1.0, 255.0);
Mat mask1ch; Mat mask1ch;
cv::cvtColor(mask, mask1ch, CV_BGR2GRAY); cv::cvtColor(mask, mask1ch, CV_BGR2GRAY);
Mat test = orig.clone(); Mat test = orig.clone();
test.setTo(Scalar::all(255), mask1ch); test.setTo(Scalar::all(255), mask1ch);
Mat res1, res2; Mat res1, res2;
inpaint( test, mask1ch, res1, 5, CV_INPAINT_NS ); inpaint( test, mask1ch, res1, 5, CV_INPAINT_NS );
inpaint( test, mask1ch, res2, 5, CV_INPAINT_TELEA ); inpaint( test, mask1ch, res2, 5, CV_INPAINT_TELEA );
imwrite("d:/exp1.png", res1);
imwrite("d:/exp2.png", res2);
Mat diff1, diff2; Mat diff1, diff2;
absdiff( orig, res1, diff1 ); absdiff( orig, res1, diff1 );
absdiff( orig, res2, diff2 ); absdiff( orig, res2, diff2 );
double n1 = norm(diff1.reshape(1), NORM_INF, inv_mask.reshape(1)); double n1 = norm(diff1.reshape(1), NORM_INF, inv_mask.reshape(1));
double n2 = norm(diff2.reshape(1), NORM_INF, inv_mask.reshape(1)); double n2 = norm(diff2.reshape(1), NORM_INF, inv_mask.reshape(1));
if (n1 != 0 || n2 != 0) if (n1 != 0 || n2 != 0)
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH ); ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
return; return;
} }
@ -109,9 +106,9 @@ void CV_InpaintTest::run( int )
n2 = norm(diff2.reshape(1), NORM_INF, mask.reshape(1)); n2 = norm(diff2.reshape(1), NORM_INF, mask.reshape(1));
const int jpeg_thres = 3; const int jpeg_thres = 3;
if (n1 > jpeg_thres || n2 > jpeg_thres) if (n1 > jpeg_thres || n2 > jpeg_thres)
{ {
ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY ); ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
return; return;
} }

View File

@ -37,8 +37,6 @@ for l in open("%s/api" % sys.argv[1]):
# Validation: check that any optional arguments are last # Validation: check that any optional arguments are last
had_error = False had_error = False
for (f, args, ty, flags) in api: for (f, args, ty, flags) in api:
if f == 'PolarToCart':
print f, [(a.init != None) for a in args]
has_init = [(a.init != None) for a in args if not 'O' in a.flags] has_init = [(a.init != None) for a in args if not 'O' in a.flags]
if True in has_init and not all(has_init[has_init.index(True):]): if True in has_init and not all(has_init[has_init.index(True):]):
print 'Error in definition for "%s", optional arguments must be last' % f print 'Error in definition for "%s", optional arguments must be last' % f
@ -130,7 +128,7 @@ def has_optional(al):
def gen(name, args, ty, flags): def gen(name, args, ty, flags):
yield "" yield ""
if has_optional(args): if has_optional(args):
yield "static PyObject *pycv%s(PyObject *self, PyObject *args, PyObject *kw)" % cname(name) yield "static PyObject *pycv%s(PyObject *self, PyObject *args, PyObject *kw)" % cname(name)
else: else:
yield "static PyObject *pycv%s(PyObject *self, PyObject *args)" % cname(name) yield "static PyObject *pycv%s(PyObject *self, PyObject *args)" % cname(name)
if 'doconly' in flags: if 'doconly' in flags:
@ -185,7 +183,7 @@ def gen(name, args, ty, flags):
in_args = [ a for a in args if not 'O' in a.flags ] in_args = [ a for a in args if not 'O' in a.flags ]
fmt0 = "".join([ fmap[a.ty] for a in in_args if not a.init]) fmt0 = "".join([ fmap[a.ty] for a in in_args if not a.init])
fmt1 = "".join([ fmap[a.ty] for a in in_args if a.init]) fmt1 = "".join([ fmap[a.ty] for a in in_args if a.init])
yield '' yield ''
if len(fmt0 + fmt1) > 0: if len(fmt0 + fmt1) > 0:
if len(fmt1) > 0: if len(fmt1) > 0:

View File

@ -96,13 +96,13 @@ def query_yes_no(stdout, question, default="yes"):
else: else:
stdout.write("Please respond with 'yes' or 'no' "\ stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n") "(or 'y' or 'n').\n")
def getRunningProcessExePathByName_win32(name): def getRunningProcessExePathByName_win32(name):
from ctypes import windll, POINTER, pointer, Structure, sizeof from ctypes import windll, POINTER, pointer, Structure, sizeof
from ctypes import c_long , c_int , c_uint , c_char , c_ubyte , c_char_p , c_void_p from ctypes import c_long , c_int , c_uint , c_char , c_ubyte , c_char_p , c_void_p
class PROCESSENTRY32(Structure): class PROCESSENTRY32(Structure):
_fields_ = [ ( 'dwSize' , c_uint ) , _fields_ = [ ( 'dwSize' , c_uint ) ,
( 'cntUsage' , c_uint) , ( 'cntUsage' , c_uint) ,
( 'th32ProcessID' , c_uint) , ( 'th32ProcessID' , c_uint) ,
( 'th32DefaultHeapID' , c_uint) , ( 'th32DefaultHeapID' , c_uint) ,
@ -111,25 +111,25 @@ def getRunningProcessExePathByName_win32(name):
( 'th32ParentProcessID' , c_uint) , ( 'th32ParentProcessID' , c_uint) ,
( 'pcPriClassBase' , c_long) , ( 'pcPriClassBase' , c_long) ,
( 'dwFlags' , c_uint) , ( 'dwFlags' , c_uint) ,
( 'szExeFile' , c_char * 260 ) , ( 'szExeFile' , c_char * 260 ) ,
( 'th32MemoryBase' , c_long) , ( 'th32MemoryBase' , c_long) ,
( 'th32AccessKey' , c_long ) ] ( 'th32AccessKey' , c_long ) ]
class MODULEENTRY32(Structure): class MODULEENTRY32(Structure):
_fields_ = [ ( 'dwSize' , c_long ) , _fields_ = [ ( 'dwSize' , c_long ) ,
( 'th32ModuleID' , c_long ), ( 'th32ModuleID' , c_long ),
( 'th32ProcessID' , c_long ), ( 'th32ProcessID' , c_long ),
( 'GlblcntUsage' , c_long ), ( 'GlblcntUsage' , c_long ),
( 'ProccntUsage' , c_long ) , ( 'ProccntUsage' , c_long ) ,
( 'modBaseAddr' , c_long ) , ( 'modBaseAddr' , c_long ) ,
( 'modBaseSize' , c_long ) , ( 'modBaseSize' , c_long ) ,
( 'hModule' , c_void_p ) , ( 'hModule' , c_void_p ) ,
( 'szModule' , c_char * 256 ), ( 'szModule' , c_char * 256 ),
( 'szExePath' , c_char * 260 ) ] ( 'szExePath' , c_char * 260 ) ]
TH32CS_SNAPPROCESS = 2 TH32CS_SNAPPROCESS = 2
TH32CS_SNAPMODULE = 0x00000008 TH32CS_SNAPMODULE = 0x00000008
## CreateToolhelp32Snapshot ## CreateToolhelp32Snapshot
CreateToolhelp32Snapshot= windll.kernel32.CreateToolhelp32Snapshot CreateToolhelp32Snapshot= windll.kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.reltype = c_long CreateToolhelp32Snapshot.reltype = c_long
@ -150,7 +150,7 @@ def getRunningProcessExePathByName_win32(name):
Module32First = windll.kernel32.Module32First Module32First = windll.kernel32.Module32First
Module32First.argtypes = [ c_void_p , POINTER(MODULEENTRY32) ] Module32First.argtypes = [ c_void_p , POINTER(MODULEENTRY32) ]
Module32First.rettype = c_int Module32First.rettype = c_int
hProcessSnap = c_void_p(0) hProcessSnap = c_void_p(0)
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS , 0 ) hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS , 0 )
@ -180,7 +180,7 @@ def getRunningProcessExePathByName_posix(name):
for pid in pids: for pid in pids:
try: try:
path = os.readlink(os.path.join('/proc', pid, 'exe')) path = os.readlink(os.path.join('/proc', pid, 'exe'))
if path and path.endswith(name): if path and path.endswith(name):
return path return path
except: except:
pass pass
@ -195,7 +195,7 @@ def getRunningProcessExePathByName(name):
return None return None
except: except:
return None return None
class RunInfo(object): class RunInfo(object):
def setCallback(self, name, callback): def setCallback(self, name, callback):
setattr(self, name, callback) setattr(self, name, callback)
@ -224,7 +224,7 @@ class RunInfo(object):
except: except:
pass pass
cachefile.close() cachefile.close()
# fix empty tests dir # fix empty tests dir
if not self.tests_dir: if not self.tests_dir:
self.tests_dir = self.path self.tests_dir = self.path
@ -236,12 +236,12 @@ class RunInfo(object):
else: else:
self.adb = None self.adb = None
# detect target platform # detect target platform
if self.android_executable or self.android_abi or self.ndk_path: if self.android_executable or self.android_abi or self.ndk_path:
self.targetos = "android" self.targetos = "android"
else: else:
self.targetos = hostos self.targetos = hostos
if self.targetos == "android": if self.targetos == "android":
# fix adb tool location # fix adb tool location
if not self.adb: if not self.adb:
@ -250,7 +250,7 @@ class RunInfo(object):
self.adb = "adb" self.adb = "adb"
if options.adb_serial: if options.adb_serial:
self.adb = [self.adb, "-s", options.adb_serial] self.adb = [self.adb, "-s", options.adb_serial]
else: else:
self.adb = [self.adb] self.adb = [self.adb]
try: try:
output = Popen(self.adb + ["shell", "ls"], stdout=PIPE, stderr=PIPE).communicate() output = Popen(self.adb + ["shell", "ls"], stdout=PIPE, stderr=PIPE).communicate()
@ -317,23 +317,23 @@ class RunInfo(object):
self.targetarch = "x86" self.targetarch = "x86"
else: else:
self.targetarch = "unknown" self.targetarch = "unknown"
# fix CUDA attributes # fix CUDA attributes
self.with_cuda = self.with_cuda == "ON" self.with_cuda = self.with_cuda == "ON"
if self.cuda_library and self.cuda_library.endswith("-NOTFOUND"): if self.cuda_library and self.cuda_library.endswith("-NOTFOUND"):
self.cuda_library = None self.cuda_library = None
self.has_cuda = self.with_cuda and self.cuda_library and self.targetarch in ["x86", "x64"] self.has_cuda = self.with_cuda and self.cuda_library and self.targetarch in ["x86", "x64"]
self.hardware = None self.hardware = None
self.getSvnVersion(self.cmake_home, "cmake_home_svn") self.getSvnVersion(self.cmake_home, "cmake_home_svn")
if self.opencv_home == self.cmake_home: if self.opencv_home == self.cmake_home:
self.opencv_home_svn = self.cmake_home_svn self.opencv_home_svn = self.cmake_home_svn
else: else:
self.getSvnVersion(self.opencv_home, "opencv_home_svn") self.getSvnVersion(self.opencv_home, "opencv_home_svn")
self.tests = self.getAvailableTestApps() self.tests = self.getAvailableTestApps()
def getSvnVersion(self, path, name): def getSvnVersion(self, path, name):
if not path: if not path:
setattr(self, name, None) setattr(self, name, None)
@ -352,7 +352,7 @@ class RunInfo(object):
setattr(self, name, None) setattr(self, name, None)
except OSError: except OSError:
setattr(self, name, None) setattr(self, name, None)
def tryGetSvnVersionWithTortoise(self, path, name): def tryGetSvnVersionWithTortoise(self, path, name):
try: try:
wcrev = "SubWCRev.exe" wcrev = "SubWCRev.exe"
@ -377,7 +377,7 @@ class RunInfo(object):
if dir: if dir:
import shutil import shutil
shutil.rmtree(dir) shutil.rmtree(dir)
def isTest(self, fullpath): def isTest(self, fullpath):
if not os.path.isfile(fullpath): if not os.path.isfile(fullpath):
return False return False
@ -388,14 +388,14 @@ class RunInfo(object):
if self.targetos == "android" and fullpath.endswith(".apk"): if self.targetos == "android" and fullpath.endswith(".apk"):
return True return True
return True return True
def getAvailableTestApps(self): def getAvailableTestApps(self):
if self.tests_dir and os.path.isdir(self.tests_dir): if self.tests_dir and os.path.isdir(self.tests_dir):
files = glob.glob(os.path.join(self.tests_dir, self.nameprefix + "*")) files = glob.glob(os.path.join(self.tests_dir, self.nameprefix + "*"))
files = [f for f in files if self.isTest(f)] files = [f for f in files if self.isTest(f)]
return files return files
return [] return []
def getLogName(self, app, timestamp): def getLogName(self, app, timestamp):
app = os.path.basename(app) app = os.path.basename(app)
if app.endswith(".exe"): if app.endswith(".exe"):
@ -508,17 +508,17 @@ class RunInfo(object):
hw = "" hw = ""
tstamp = timestamp.strftime("%Y-%m-%d--%H-%M-%S") tstamp = timestamp.strftime("%Y-%m-%d--%H-%M-%S")
return "%s_%s_%s_%s%s%s.xml" % (app, self.targetos, self.targetarch, hw, rev, tstamp) return "%s_%s_%s_%s%s%s.xml" % (app, self.targetos, self.targetarch, hw, rev, tstamp)
def getTest(self, name): def getTest(self, name):
# full path # full path
if self.isTest(name): if self.isTest(name):
return name return name
# name only # name only
fullname = os.path.join(self.tests_dir, name) fullname = os.path.join(self.tests_dir, name)
if self.isTest(fullname): if self.isTest(fullname):
return fullname return fullname
# name without extension # name without extension
fullname += ".exe" fullname += ".exe"
if self.isTest(fullname): if self.isTest(fullname):
@ -527,7 +527,7 @@ class RunInfo(object):
fullname += ".apk" fullname += ".apk"
if self.isTest(fullname): if self.isTest(fullname):
return fullname return fullname
# short name for OpenCV tests # short name for OpenCV tests
for t in self.tests: for t in self.tests:
if t == name: if t == name:
@ -547,7 +547,7 @@ class RunInfo(object):
if fname == name: if fname == name:
return t return t
return None return None
def runAdb(self, *args): def runAdb(self, *args):
cmd = self.adb[:] cmd = self.adb[:]
cmd.extend(args) cmd.extend(args)
@ -559,7 +559,7 @@ class RunInfo(object):
except OSError: except OSError:
pass pass
return None return None
def isRunnable(self): def isRunnable(self):
if self.error: if self.error:
return False return False
@ -585,7 +585,7 @@ class RunInfo(object):
if hw: if hw:
self.hardware = hw.groups()[0].strip() self.hardware = hw.groups()[0].strip()
return True return True
def runTest(self, path, workingDir, _stdout, _stderr, args = []): def runTest(self, path, workingDir, _stdout, _stderr, args = []):
if self.error: if self.error:
return return
@ -593,13 +593,13 @@ class RunInfo(object):
timestamp = datetime.datetime.now() timestamp = datetime.datetime.now()
logfile = self.getLogName(path, timestamp) logfile = self.getLogName(path, timestamp)
exe = os.path.abspath(path) exe = os.path.abspath(path)
userlog = [a for a in args if a.startswith("--gtest_output=")] userlog = [a for a in args if a.startswith("--gtest_output=")]
if len(userlog) == 0: if len(userlog) == 0:
args.append("--gtest_output=xml:" + logfile) args.append("--gtest_output=xml:" + logfile)
else: else:
logfile = userlog[0][userlog[0].find(":")+1:] logfile = userlog[0][userlog[0].find(":")+1:]
if self.targetos == "android" and exe.endswith(".apk"): if self.targetos == "android" and exe.endswith(".apk"):
print "running java tests:", exe print "running java tests:", exe
try: try:
@ -653,10 +653,11 @@ class RunInfo(object):
elif self.targetos == "android": elif self.targetos == "android":
hostlogpath = "" hostlogpath = ""
usercolor = [a for a in args if a.startswith("--gtest_color=")] usercolor = [a for a in args if a.startswith("--gtest_color=")]
if len(userlog) == 0 and _stdout.isatty() and hostos != "nt": if len(usercolor) == 0 and _stdout.isatty() and hostos != "nt":
args.append("--gtest_color=yes") args.append("--gtest_color=yes")
try: try:
andoidcwd = "/data/bin/" + getpass.getuser().replace(" ","") + "_" + self.options.mode +"/" tempdir = "/data/local/tmp/"
andoidcwd = tempdir + getpass.getuser().replace(" ","") + "_" + self.options.mode +"/"
exename = os.path.basename(exe) exename = os.path.basename(exe)
androidexe = andoidcwd + exename androidexe = andoidcwd + exename
#upload #upload
@ -692,6 +693,9 @@ class RunInfo(object):
return return
#rm log #rm log
Popen(self.adb + ["shell", "rm " + andoidcwd + logfile], stdout=_stdout, stderr=_stderr).wait() Popen(self.adb + ["shell", "rm " + andoidcwd + logfile], stdout=_stdout, stderr=_stderr).wait()
# clean temporary files
Popen(self.adb + ["shell", "rm " + tempdir + "__opencv_temp.*"], stdout=_stdout, stderr=_stderr).wait()
except OSError: except OSError:
pass pass
if os.path.isfile(hostlogpath): if os.path.isfile(hostlogpath):
@ -704,16 +708,27 @@ class RunInfo(object):
else: else:
cmd.extend(args) cmd.extend(args)
print >> _stderr, "Running:", " ".join(cmd) print >> _stderr, "Running:", " ".join(cmd)
try: try:
Popen(cmd, stdout=_stdout, stderr=_stderr, cwd = workingDir).wait() Popen(cmd, stdout=_stdout, stderr=_stderr, cwd = workingDir).wait()
except OSError: except OSError:
pass pass
# clean temporary files
temp_path = os.environ.get('OPENCV_TEMP_PATH')
if not temp_path:
if hostos == "nt":
temp_path = tempfile.gettempdir()
else:
temp_path = "/tmp"
for filename in glob.glob(os.path.join(temp_path, "__opencv_temp.*")) :
os.remove( filename )
logpath = os.path.join(workingDir, logfile) logpath = os.path.join(workingDir, logfile)
if os.path.isfile(logpath): if os.path.isfile(logpath):
return logpath return logpath
return None return None
def runTests(self, tests, _stdout, _stderr, workingDir, args = []): def runTests(self, tests, _stdout, _stderr, workingDir, args = []):
if self.error: if self.error:
return [] return []
@ -747,10 +762,10 @@ def getRunArgs(args):
if __name__ == "__main__": if __name__ == "__main__":
test_args = [a for a in sys.argv if a.startswith("--perf_") or a.startswith("--gtest_")] test_args = [a for a in sys.argv if a.startswith("--perf_") or a.startswith("--gtest_")]
argv = [a for a in sys.argv if not(a.startswith("--perf_") or a.startswith("--gtest_"))] argv = [a for a in sys.argv if not(a.startswith("--perf_") or a.startswith("--gtest_"))]
parser = OptionParser() parser = OptionParser()
parser.add_option("-t", "--tests", dest="tests", help="comma-separated list of modules to test", metavar="SUITS", default="") parser.add_option("-t", "--tests", dest="tests", help="comma-separated list of modules to test", metavar="SUITS", default="")
parser.add_option("-w", "--cwd", dest="cwd", help="working directory for tests", metavar="PATH", default=".") parser.add_option("-w", "--cwd", dest="cwd", help="working directory for tests", metavar="PATH", default=".")
parser.add_option("-a", "--accuracy", dest="accuracy", help="look for accuracy tests instead of performance tests", action="store_true", default=False) parser.add_option("-a", "--accuracy", dest="accuracy", help="look for accuracy tests instead of performance tests", action="store_true", default=False)
parser.add_option("-l", "--longname", dest="useLongNames", action="store_true", help="generate log files with long names", default=False) parser.add_option("-l", "--longname", dest="useLongNames", action="store_true", help="generate log files with long names", default=False)
@ -759,26 +774,26 @@ if __name__ == "__main__":
parser.add_option("", "--serial", dest="adb_serial", help="Android: directs command to the USB device or emulator with the given serial number", metavar="serial number", default="") parser.add_option("", "--serial", dest="adb_serial", help="Android: directs command to the USB device or emulator with the given serial number", metavar="serial number", default="")
parser.add_option("", "--package", dest="junit_package", help="Android: run jUnit tests for specified package", metavar="package", default="") parser.add_option("", "--package", dest="junit_package", help="Android: run jUnit tests for specified package", metavar="package", default="")
parser.add_option("", "--help-tests", dest="help", help="Show help for test executable", action="store_true", default=False) parser.add_option("", "--help-tests", dest="help", help="Show help for test executable", action="store_true", default=False)
(options, args) = parser.parse_args(argv) (options, args) = parser.parse_args(argv)
if options.accuracy: if options.accuracy:
options.mode = "test" options.mode = "test"
else: else:
options.mode = "perf" options.mode = "perf"
run_args = getRunArgs(args[1:] or ['.']) run_args = getRunArgs(args[1:] or ['.'])
if len(run_args) == 0: if len(run_args) == 0:
print >> sys.stderr, "Usage:\n", os.path.basename(sys.argv[0]), "<build_path>" print >> sys.stderr, "Usage:\n", os.path.basename(sys.argv[0]), "<build_path>"
exit(1) exit(1)
tests = [s.strip() for s in options.tests.split(",") if s] tests = [s.strip() for s in options.tests.split(",") if s]
if len(tests) != 1 or len(run_args) != 1: if len(tests) != 1 or len(run_args) != 1:
#remove --gtest_output from params #remove --gtest_output from params
test_args = [a for a in test_args if not a.startswith("--gtest_output=")] test_args = [a for a in test_args if not a.startswith("--gtest_output=")]
logs = [] logs = []
for path in run_args: for path in run_args:
info = RunInfo(path, options) info = RunInfo(path, options)
@ -789,5 +804,5 @@ if __name__ == "__main__":
info.test_data_path = options.test_data_path info.test_data_path = options.test_data_path
logs.extend(info.runTests(tests, sys.stdout, sys.stderr, options.cwd, test_args)) logs.extend(info.runTests(tests, sys.stdout, sys.stderr, options.cwd, test_args))
if logs: if logs:
print >> sys.stderr, "Collected:", " ".join(logs) print >> sys.stderr, "Collected:", " ".join(logs)