diff --git a/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.markdown b/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.markdown index a50492890b..8fcb094abd 100644 --- a/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.markdown +++ b/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.markdown @@ -204,9 +204,9 @@ receives three arguments: We can choose any of three shapes for our kernel: - - Rectangular box: CV_SHAPE_RECT - - Cross: CV_SHAPE_CROSS - - Ellipse: CV_SHAPE_ELLIPSE + - Rectangular box: Imgproc.SHAPE_RECT + - Cross: Imgproc.SHAPE_CROSS + - Ellipse: Imgproc.SHAPE_ELLIPSE Together with the shape we specify the size of our kernel and the *anchor point*. If the anchor point is not specified, it is assumed to be in the center. diff --git a/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.markdown b/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.markdown index 5f56995a7b..30b82143f9 100644 --- a/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.markdown +++ b/doc/tutorials/imgproc/histograms/histogram_comparison/histogram_comparison.markdown @@ -27,19 +27,19 @@ Theory (\f$d(H_{1}, H_{2})\f$) to express how well both histograms match. - OpenCV implements the function @ref cv::compareHist to perform a comparison. It also offers 4 different metrics to compute the matching: - -# **Correlation ( CV_COMP_CORREL )** + -# **Correlation ( cv::HISTCMP_CORREL )** \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] where \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] and \f$N\f$ is the total number of histogram bins. - -# **Chi-Square ( CV_COMP_CHISQR )** + -# **Chi-Square ( cv::HISTCMP_CHISQR )** \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] - -# **Intersection ( method=CV_COMP_INTERSECT )** + -# **Intersection ( method=cv::HISTCMP_INTERSECT )** \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] - -# **Bhattacharyya distance ( CV_COMP_BHATTACHARYYA )** + -# **Bhattacharyya distance ( cv::HISTCMP_BHATTACHARYYA )** \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] Code diff --git a/modules/3d/test/test_undistort.cpp b/modules/3d/test/test_undistort.cpp index 30f75e3711..dc59b327e1 100644 --- a/modules/3d/test/test_undistort.cpp +++ b/modules/3d/test/test_undistort.cpp @@ -998,7 +998,7 @@ TEST(DISABLED_Calib3d_InitInverseRectificationMap, accuracy) { CV_InitInverseRec ////////////////////////////// undistort ///////////////////////////////// static void test_remap( const Mat& src, Mat& dst, const Mat& mapx, const Mat& mapy, - Mat* mask=0, int interpolation=CV_INTER_LINEAR ) + Mat* mask=0, int interpolation=cv::INTER_LINEAR ) { int x, y, k; int drows = dst.rows, dcols = dst.cols; @@ -1009,7 +1009,7 @@ static void test_remap( const Mat& src, Mat& dst, const Mat& mapx, const Mat& ma int step = (int)(src.step / CV_ELEM_SIZE(depth)); int delta; - if( interpolation != CV_INTER_CUBIC ) + if( interpolation != cv::INTER_CUBIC ) { delta = 0; scols -= 1; srows -= 1; @@ -1318,7 +1318,7 @@ void CV_UndistortTest::get_test_array_types_and_sizes( int test_case_idx, vector sizes[INPUT][2] = cvtest::randInt(rng)%2 ? cvSize(4,1) : cvSize(1,4); types[INPUT][3] = types[INPUT][1]; sizes[INPUT][3] = sizes[INPUT][1]; - interpolation = CV_INTER_LINEAR; + interpolation = cv::INTER_LINEAR; } diff --git a/modules/calib/src/calibinit.cpp b/modules/calib/src/calibinit.cpp index 4f9a20535f..e49b5c2a66 100644 --- a/modules/calib/src/calibinit.cpp +++ b/modules/calib/src/calibinit.cpp @@ -102,8 +102,6 @@ namespace cv { #define MAX_CONTOUR_APPROX 7 -#define USE_CV_FINDCONTOURS // switch between findContours() and legacy C API -#ifdef USE_CV_FINDCONTOURS struct QuadCountour { Point pt[4]; int parent_contour; @@ -114,13 +112,6 @@ struct QuadCountour { pt[0] = pt_[0]; pt[1] = pt_[1]; pt[2] = pt_[2]; pt[3] = pt_[3]; } }; -#else -struct CvContourEx -{ - CV_CONTOUR_FIELDS() - int counter; -}; -#endif /** This structure stores information about the chessboard corner.*/ struct ChessBoardCorner @@ -547,13 +538,7 @@ bool findChessboardCorners(InputArray image_, Size pattern_size, rectangle( thresh_img_new, Point(0,0), Point(thresh_img_new.cols-1, thresh_img_new.rows-1), Scalar(255,255,255), 3, LINE_8); detector.reset(); - -#ifdef USE_CV_FINDCONTOURS - Mat binarized_img = thresh_img_new; -#else - Mat binarized_img = thresh_img_new.clone(); // make clone because cvFindContours modifies the source image -#endif - detector.generateQuads(binarized_img, flags); + detector.generateQuads(thresh_img_new, flags); DPRINTF("Quad count: %d/%d", detector.all_quads_count, (pattern_size.width/2+1)*(pattern_size.height/2+1)); SHOW_QUADS("New quads", thresh_img_new, &detector.all_quads[0], detector.all_quads_count); if (detector.processQuads(out_corners, prev_sqr_size)) @@ -618,13 +603,7 @@ bool findChessboardCorners(InputArray image_, Size pattern_size, rectangle( thresh_img, Point(0,0), Point(thresh_img.cols-1, thresh_img.rows-1), Scalar(255,255,255), 3, LINE_8); detector.reset(); - -#ifdef USE_CV_FINDCONTOURS - Mat binarized_img = thresh_img; -#else - Mat binarized_img = (useAdaptive) ? thresh_img : thresh_img.clone(); // make clone because cvFindContours modifies the source image -#endif - detector.generateQuads(binarized_img, flags); + detector.generateQuads(thresh_img, flags); DPRINTF("Quad count: %d/%d", detector.all_quads_count, (pattern_size.width/2+1)*(pattern_size.height/2+1)); SHOW_QUADS("Old quads", thresh_img, &detector.all_quads[0], detector.all_quads_count); if (detector.processQuads(out_corners, prev_sqr_size)) @@ -1371,7 +1350,6 @@ int ChessBoardDetector::checkQuadGroup(std::vector& quad_group, for (int j = 0; j < 4; ++j) { - //cvLine( debug_img, cvPointFrom32f(q->corners[j]->pt), cvPointFrom32f(q->corners[(j+1)&3]->pt), color, 1, CV_AA, 0 ); if (q->neighbors[j]) { int next_j = (j + 1) & 3; @@ -1460,7 +1438,6 @@ int ChessBoardDetector::checkQuadGroup(std::vector& quad_group, goto finalize; cur->row = 0; - //cvCircle( debug_img, cvPointFrom32f(cur->pt), 3, cvScalar(0,255,0), -1, 8, 0 ); first = below; // remember the first corner in the next row @@ -1469,7 +1446,6 @@ int ChessBoardDetector::checkQuadGroup(std::vector& quad_group, { right->row = 0; out_corners.push_back(right); - //cvCircle( debug_img, cvPointFrom32f(right->pt), 3, cvScalar(0,255-j*10,0), -1, 8, 0 ); if( right->count == 2 ) break; if( right->count != 3 || (int)out_corners.size() >= std::max(pattern_size.width,pattern_size.height) ) @@ -1514,7 +1490,6 @@ int ChessBoardDetector::checkQuadGroup(std::vector& quad_group, { cur->row = i; out_corners.push_back(cur); - //cvCircle( debug_img, cvPointFrom32f(cur->pt), 3, cvScalar(0,0,255-j*10), -1, 8, 0 ); if (cur->count == 2 + (i < height-1) && j > 0) break; @@ -1759,7 +1734,6 @@ void ChessBoardDetector::generateQuads(const Mat& image_, int flags) int min_size = 25; //cvRound( image->cols * image->rows * .03 * 0.01 * 0.92 ); bool filterQuads = (flags & CALIB_CB_FILTER_QUADS) != 0; -#ifdef USE_CV_FINDCONTOURS // use findContours std::vector > contours; std::vector hierarchy; @@ -1874,122 +1848,6 @@ void ChessBoardDetector::generateQuads(const Mat& image_, int flags) } } -#else // use legacy API: cvStartFindContours / cvFindNextContour / cvEndFindContours - - CvMat image_old = cvMat(image_), *image = &image_old; - - CvContourEx* board = 0; - - // create temporary storage for contours and the sequence of pointers to found quadrangles - Ptr temp_storage(cvCreateMemStorage(0)); - CvSeq *root = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvSeq*), temp_storage); - - // initialize contour retrieving routine - CvContourScanner scanner = cvStartFindContours(image, temp_storage, sizeof(CvContourEx), - CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); - - // get all the contours one by one - CvSeq* src_contour = NULL; - while ((src_contour = cvFindNextContour(scanner)) != NULL) - { - CvSeq *dst_contour = 0; - CvRect rect = ((CvContour*)src_contour)->rect; - - // reject contours with too small perimeter - if( CV_IS_SEQ_HOLE(src_contour) && rect.width*rect.height >= min_size ) - { - const int min_approx_level = 1, max_approx_level = MAX_CONTOUR_APPROX; - for (int approx_level = min_approx_level; approx_level <= max_approx_level; approx_level++ ) - { - dst_contour = cvApproxPoly( src_contour, sizeof(CvContour), temp_storage, - CV_POLY_APPROX_DP, (float)approx_level ); - if( dst_contour->total == 4 ) - break; - - // we call this again on its own output, because sometimes - // cvApproxPoly() does not simplify as much as it should. - dst_contour = cvApproxPoly( dst_contour, sizeof(CvContour), temp_storage, - CV_POLY_APPROX_DP, (float)approx_level ); - - if( dst_contour->total == 4 ) - break; - } - - // reject non-quadrangles - if( dst_contour->total == 4 && cvCheckContourConvexity(dst_contour) ) - { - Point2i pt[4]; - double p = cvContourPerimeter(dst_contour); - double area = fabs(cvContourArea(dst_contour, CV_WHOLE_SEQ)); - - for (int i = 0; i < 4; ++i) - pt[i] = *(CvPoint*)cvGetSeqElem(dst_contour, i); - CV_LOG_VERBOSE(NULL, 9, "... contours(" << root->total << " added):" << pt[0] << " " << pt[1] << " " << pt[2] << " " << pt[3]); - - double d1 = sqrt(normL2Sqr(pt[0] - pt[2])); - double d2 = sqrt(normL2Sqr(pt[1] - pt[3])); - - // philipg. Only accept those quadrangles which are more square - // than rectangular and which are big enough - double d3 = sqrt(normL2Sqr(pt[0] - pt[1])); - double d4 = sqrt(normL2Sqr(pt[1] - pt[2])); - if (!filterQuads || - (d3*4 > d4 && d4*4 > d3 && d3*d4 < area*1.5 && area > min_size && - d1 >= 0.15 * p && d2 >= 0.15 * p)) - { - CvContourEx* parent = (CvContourEx*)(src_contour->v_prev); - parent->counter++; - if( !board || board->counter < parent->counter ) - board = parent; - dst_contour->v_prev = (CvSeq*)parent; - //for( i = 0; i < 4; i++ ) cvLine( debug_img, pt[i], pt[(i+1)&3], cvScalar(200,255,255), 1, CV_AA, 0 ); - cvSeqPush( root, &dst_contour ); - } - } - } - } - - // finish contour retrieving - cvEndFindContours( &scanner ); - - // allocate quad & corner buffers - int total = root->total; - size_t max_quad_buf_size = std::max((size_t)2, (size_t)total * 3); - all_quads.allocate(max_quad_buf_size); - all_corners.allocate(max_quad_buf_size * 4); - - // Create array of quads structures - for (int idx = 0; idx < total; ++idx) - { - /* CvSeq* */src_contour = *(CvSeq**)cvGetSeqElem(root, idx); - if (filterQuads && src_contour->v_prev != (CvSeq*)board) - continue; - - int quad_idx = quad_count++; - ChessBoardQuad& q = all_quads[quad_idx]; - - // reset group ID - q = ChessBoardQuad(); - CV_Assert(src_contour->total == 4); - for (int i = 0; i < 4; i++) - { - Point* onePoint = (Point*)cvGetSeqElem(src_contour, i); - CV_Assert(onePoint != NULL); - Point2f pt(*onePoint); - ChessBoardCorner& corner = all_corners[quad_idx*4 + i]; - - corner = ChessBoardCorner(pt); - q.corners[i] = &corner; - } - q.edge_len = FLT_MAX; - for (int i = 0; i < 4; ++i) - { - float d = normL2Sqr(q.corners[i]->pt - q.corners[(i+1)&3]->pt); - q.edge_len = std::min(q.edge_len, d); - } - } -#endif - all_quads_count = quad_count; CV_LOG_VERBOSE(NULL, 3, "Total quad contours: " << total); diff --git a/modules/core/include/opencv2/core/cuda.hpp b/modules/core/include/opencv2/core/cuda.hpp index ba4aa290a3..525373cfdf 100644 --- a/modules/core/include/opencv2/core/cuda.hpp +++ b/modules/core/include/opencv2/core/cuda.hpp @@ -609,8 +609,8 @@ Below is an example that utilizes BufferPool with StackAllocator: GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB - cvtColor(d_src1, d_dst1, CV_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, CV_GRAY2BGR, 0, stream2); + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); } @endcode @@ -675,8 +675,8 @@ and the corresponding memory is automatically returned to the pool for later usa d_src1.setTo(Scalar(i), stream1); d_src2.setTo(Scalar(i), stream2); - cvtColor(d_src1, d_dst1, CV_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, CV_GRAY2BGR, 0, stream2); + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); // The order of destruction of the local variables is: // d_dst2 => d_src2 => d_dst1 => d_src1 // LIFO rule is satisfied, this code runs without error diff --git a/modules/core/include/opencv2/core/types.hpp b/modules/core/include/opencv2/core/types.hpp index 3950ec7cc8..40f3267564 100644 --- a/modules/core/include/opencv2/core/types.hpp +++ b/modules/core/include/opencv2/core/types.hpp @@ -954,10 +954,6 @@ public: //! the full constructor Moments(double m00, double m10, double m01, double m20, double m11, double m02, double m30, double m21, double m12, double m03 ); - ////! the conversion from CvMoments - //Moments( const CvMoments& moments ); - ////! the conversion to CvMoments - //operator CvMoments() const; //! @name spatial moments //! @{ diff --git a/modules/gapi/include/opencv2/gapi/core.hpp b/modules/gapi/include/opencv2/gapi/core.hpp index f46f159adf..4175da09cc 100644 --- a/modules/gapi/include/opencv2/gapi/core.hpp +++ b/modules/gapi/include/opencv2/gapi/core.hpp @@ -1418,7 +1418,7 @@ types. */ GAPI_EXPORTS GMat threshold(const GMat& src, const GScalar& thresh, const GScalar& maxval, int type); /** @overload -This function applicable for all threshold types except CV_THRESH_OTSU and CV_THRESH_TRIANGLE +This function applicable for all threshold types except cv::THRESH_OTSU and cv::THRESH_TRIANGLE @note Function textual ID is "org.opencv.core.matrixop.thresholdOT" */ GAPI_EXPORTS_W std::tuple threshold(const GMat& src, const GScalar& maxval, int type); diff --git a/modules/highgui/include/opencv2/highgui.hpp b/modules/highgui/include/opencv2/highgui.hpp index 7ae2395737..0d9ad2e3db 100644 --- a/modules/highgui/include/opencv2/highgui.hpp +++ b/modules/highgui/include/opencv2/highgui.hpp @@ -167,8 +167,6 @@ It provides easy interface to: cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); } @endcode - - @defgroup highgui_c C API @} */ @@ -797,7 +795,7 @@ CV_EXPORTS_W void displayOverlay(const String& winname, const String& text, int The function displayStatusBar displays useful information/tips on top of the window for a certain amount of time *delayms* . This information is displayed on the window statusbar (the window must be -created with the CV_GUI_EXPANDED flags). +created with the cv::WINDOW_GUI_EXPANDED flags). @param winname Name of the window. @param text Text to write on the window statusbar. diff --git a/modules/highgui/include/opencv2/highgui/highgui_c.h b/modules/highgui/include/opencv2/highgui/highgui_c.h deleted file mode 100644 index e508e14975..0000000000 --- a/modules/highgui/include/opencv2/highgui/highgui_c.h +++ /dev/null @@ -1,251 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HIGHGUI_H -#define OPENCV_HIGHGUI_H - -#include "opencv2/core/core_c.h" -#include "opencv2/imgproc/imgproc_c.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup highgui_c - @{ - */ - -/****************************************************************************************\ -* Basic GUI functions * -\****************************************************************************************/ -//YV -//-----------New for Qt -/* For font */ -enum { CV_FONT_LIGHT = 25,//QFont::Light, - CV_FONT_NORMAL = 50,//QFont::Normal, - CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, - CV_FONT_BOLD = 75,//QFont::Bold, - CV_FONT_BLACK = 87 //QFont::Black -}; - -enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, - CV_STYLE_ITALIC = 1,//QFont::StyleItalic, - CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique -}; -/* ---------*/ - -//for color cvScalar(blue_component, green_component, red_component[, alpha_component]) -//and alpha= 0 <-> 0xFF (not transparent <-> transparent) -CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); - -CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); - -CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); -CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); - -CVAPI(void) cvSaveWindowParameters(const char* name); -CVAPI(void) cvLoadWindowParameters(const char* name); -CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); -CVAPI(void) cvStopLoop( void ); - -typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); -enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; -CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); -//---------------------- - - -/* this function is used to set some external parameters in case of X Window */ -CVAPI(int) cvInitSystem( int argc, char** argv ); - -CVAPI(int) cvStartWindowThread( void ); - -// --------- YV --------- -enum -{ - //These 3 flags are used by cvSet/GetWindowProperty - CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property - CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property - CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property - CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support - CV_WND_PROP_VISIBLE = 4, - - //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size - CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed - CV_WINDOW_OPENGL = 0x00001000, //window with opengl support - - //Those flags are only for Qt - CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar - CV_GUI_NORMAL = 0x00000010, //old fashious way - - //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen - CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) - CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. -}; - -/* create window */ -CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); - -/* Set and Get Property of the window */ -CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); -CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); - -/* display image within window (highgui windows remember their content) */ -CVAPI(void) cvShowImage( const char* name, const CvArr* image ); - -/* resize/move window */ -CVAPI(void) cvResizeWindow( const char* name, int width, int height ); -CVAPI(void) cvMoveWindow( const char* name, int x, int y ); - - -/* destroy window and all the trackers associated with it */ -CVAPI(void) cvDestroyWindow( const char* name ); - -CVAPI(void) cvDestroyAllWindows(void); - -/* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ -CVAPI(void*) cvGetWindowHandle( const char* name ); - -/* get name of highgui window given its native handle */ -CVAPI(const char*) cvGetWindowName( void* window_handle ); - - -typedef void (CV_CDECL *CvTrackbarCallback)(int pos); - -/* create trackbar and display it on top of given window, set callback */ -CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); - -typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); - -CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback2 on_change, - void* userdata CV_DEFAULT(0)); - -/* retrieve or set trackbar position */ -CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); -CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); -CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); -CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); - -enum -{ - CV_EVENT_MOUSEMOVE =0, - CV_EVENT_LBUTTONDOWN =1, - CV_EVENT_RBUTTONDOWN =2, - CV_EVENT_MBUTTONDOWN =3, - CV_EVENT_LBUTTONUP =4, - CV_EVENT_RBUTTONUP =5, - CV_EVENT_MBUTTONUP =6, - CV_EVENT_LBUTTONDBLCLK =7, - CV_EVENT_RBUTTONDBLCLK =8, - CV_EVENT_MBUTTONDBLCLK =9, - CV_EVENT_MOUSEWHEEL =10, - CV_EVENT_MOUSEHWHEEL =11 -}; - -enum -{ - CV_EVENT_FLAG_LBUTTON =1, - CV_EVENT_FLAG_RBUTTON =2, - CV_EVENT_FLAG_MBUTTON =4, - CV_EVENT_FLAG_CTRLKEY =8, - CV_EVENT_FLAG_SHIFTKEY =16, - CV_EVENT_FLAG_ALTKEY =32 -}; - - -#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits - -typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); - -/* assign callback for mouse events */ -CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, - void* param CV_DEFAULT(NULL)); - -/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ -CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); - -// OpenGL support - -typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); -CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); - -CVAPI(void) cvSetOpenGlContext(const char* window_name); -CVAPI(void) cvUpdateWindow(const char* window_name); - - -/****************************************************************************************\ - -* Obsolete functions/synonyms * -\****************************************************************************************/ - -#define cvAddSearchPath(path) -#define cvvInitSystem cvInitSystem -#define cvvNamedWindow cvNamedWindow -#define cvvShowImage cvShowImage -#define cvvResizeWindow cvResizeWindow -#define cvvDestroyWindow cvDestroyWindow -#define cvvCreateTrackbar cvCreateTrackbar -#define cvvAddSearchPath cvAddSearchPath -#define cvvWaitKey(name) cvWaitKey(0) -#define cvvWaitKeyEx(name,delay) cvWaitKey(delay) -#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE -#define set_preprocess_func cvSetPreprocessFuncWin32 -#define set_postprocess_func cvSetPostprocessFuncWin32 - -#if defined _WIN32 - -CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); -CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); -#define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) -#define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) - -#endif - -/** @} highgui_c */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/modules/highgui/src/precomp.hpp b/modules/highgui/src/precomp.hpp index 574eaba773..2daa82143f 100644 --- a/modules/highgui/src/precomp.hpp +++ b/modules/highgui/src/precomp.hpp @@ -58,7 +58,6 @@ #include "opencv2/imgproc.hpp" #include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/highgui/highgui_c.h" #include #include @@ -89,6 +88,34 @@ #define CV_WINDOW_MAGIC_VAL 0x00420042 #define CV_TRACKBAR_MAGIC_VAL 0x00420043 +// Obsolete but widely used types and functions hidden here +typedef void (CV_CDECL *CvTrackbarCallback)(int pos); +int namedWindowImpl(const char* name, int flags = cv::WINDOW_AUTOSIZE); +void showImageImpl( const char* name, const CvArr* image ); +void resizeWindowImpl( const char* name, int width, int height ); +void moveWindowImpl( const char* name, int x, int y ); +void destroyWindowImpl(const char* name); +void destroyAllWindowsImpl(void); +int waitKeyImpl(int delay); + +int getTrackbarPosImpl( const char* trackbar_name, const char* window_name ); +void setTrackbarPosImpl( const char* trackbar_name, const char* window_name, int pos ); +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval); +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval); +typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); +int createTrackbar2Impl( const char* trackbar_name, const char* window_name, + int* value, int count, CvTrackbarCallback2 on_change, + void* userdata CV_DEFAULT(0)); + +typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); +void setMouseCallbackImpl( const char* window_name, CvMouseCallback on_mouse, void* param); + +typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); +void setOpenGLDrawCallbackImpl(const char* window_name, CvOpenGlDrawCallback callback, void* userdata); +void setOpenGLContextImpl(const char* window_name); +void updateWindowImpl(const char* window_name); + + //Yannick Verdie 2010, Max Kostin 2015 void cvSetModeWindow_W32(const char* name, double prop_value); void cvSetModeWindow_GTK(const char* name, double prop_value); diff --git a/modules/highgui/src/window.cpp b/modules/highgui/src/window.cpp index dd70fd2456..f166b2c874 100644 --- a/modules/highgui/src/window.cpp +++ b/modules/highgui/src/window.cpp @@ -187,10 +187,10 @@ static void deprecateNotFoundNoOpBehavior() #define CV_NOT_FOUND_DEPRECATION deprecateNotFoundNoOpBehavior() #endif -CV_IMPL void cvSetWindowProperty(const char* name, int prop_id, double prop_value) +void cv::setWindowProperty(const String& name, int prop_id, double prop_value) { CV_TRACE_FUNCTION(); - CV_Assert(name); + CV_Assert(!name.empty()); { auto window = findWindow_(name); @@ -217,34 +217,34 @@ CV_IMPL void cvSetWindowProperty(const char* name, int prop_id, double prop_valu switch(prop_id) { //change between fullscreen or not. - case CV_WND_PROP_FULLSCREEN: + case cv::WND_PROP_FULLSCREEN: - if (prop_value != CV_WINDOW_NORMAL && prop_value != CV_WINDOW_FULLSCREEN) // bad argument + if (prop_value != cv::WINDOW_NORMAL && prop_value != cv::WINDOW_FULLSCREEN) // bad argument break; #if defined (HAVE_QT) - cvSetModeWindow_QT(name,prop_value); + cvSetModeWindow_QT(name.c_str(),prop_value); #elif defined(HAVE_WIN32UI) - cvSetModeWindow_W32(name,prop_value); + cvSetModeWindow_W32(name.c_str(),prop_value); #elif defined (HAVE_GTK) - cvSetModeWindow_GTK(name,prop_value); + cvSetModeWindow_GTK(name.c_str(),prop_value); #elif defined (HAVE_COCOA) - cvSetModeWindow_COCOA(name,prop_value); + cvSetModeWindow_COCOA(name.c_str(),prop_value); #elif defined (WINRT) - cvSetModeWindow_WinRT(name, prop_value); + cvSetModeWindow_WinRT(name.c_str(), prop_value); #endif break; - case CV_WND_PROP_AUTOSIZE: + case cv::WND_PROP_AUTOSIZE: #if defined (HAVE_QT) - cvSetPropWindow_QT(name,prop_value); + cvSetPropWindow_QT(name.c_str(),prop_value); #endif break; - case CV_WND_PROP_ASPECTRATIO: + case cv::WND_PROP_ASPECT_RATIO: #if defined (HAVE_QT) - cvSetRatioWindow_QT(name,prop_value); + cvSetRatioWindow_QT(name.c_str(),prop_value); #endif break; @@ -252,9 +252,9 @@ CV_IMPL void cvSetWindowProperty(const char* name, int prop_id, double prop_valu #if defined (HAVE_QT) // nothing #elif defined(HAVE_WIN32UI) - cvSetPropTopmost_W32(name, (prop_value != 0 ? true : false)); + cvSetPropTopmost_W32(name.c_str(), (prop_value != 0 ? true : false)); #elif defined(HAVE_COCOA) - cvSetPropTopmost_COCOA(name, (prop_value != 0 ? true : false)); + cvSetPropTopmost_COCOA(name.c_str(), (prop_value != 0 ? true : false)); #endif break; @@ -262,7 +262,7 @@ CV_IMPL void cvSetWindowProperty(const char* name, int prop_id, double prop_valu #if defined (HAVE_QT) // nothing #elif defined (HAVE_WIN32UI) - cvSetPropVsync_W32(name, (prop_value != 0)); + cvSetPropVsync_W32(name.c_str(), (prop_value != 0)); #else // not implemented yet for other toolkits #endif @@ -273,11 +273,10 @@ CV_IMPL void cvSetWindowProperty(const char* name, int prop_id, double prop_valu #endif } -/* return -1 if error */ -CV_IMPL double cvGetWindowProperty(const char* name, int prop_id) +double cv::getWindowProperty(const String& name, int prop_id) { CV_TRACE_FUNCTION(); - CV_Assert(name); + CV_Assert(!name.empty()); { auto window = findWindow_(name); @@ -305,67 +304,67 @@ CV_IMPL double cvGetWindowProperty(const char* name, int prop_id) #else switch(prop_id) { - case CV_WND_PROP_FULLSCREEN: + case cv::WND_PROP_FULLSCREEN: #if defined (HAVE_QT) - return cvGetModeWindow_QT(name); + return cvGetModeWindow_QT(name.c_str()); #elif defined(HAVE_WIN32UI) - return cvGetModeWindow_W32(name); + return cvGetModeWindow_W32(name.c_str()); #elif defined (HAVE_GTK) - return cvGetModeWindow_GTK(name); + return cvGetModeWindow_GTK(name.c_str()); #elif defined (HAVE_COCOA) - return cvGetModeWindow_COCOA(name); + return cvGetModeWindow_COCOA(name.c_str()); #elif defined (WINRT) - return cvGetModeWindow_WinRT(name); + return cvGetModeWindow_WinRT(name.c_str()); #else return -1; #endif break; - case CV_WND_PROP_AUTOSIZE: + case cv::WND_PROP_AUTOSIZE: #if defined (HAVE_QT) - return cvGetPropWindow_QT(name); + return cvGetPropWindow_QT(name.c_str()); #elif defined(HAVE_WIN32UI) - return cvGetPropWindowAutoSize_W32(name); + return cvGetPropWindowAutoSize_W32(name.c_str()); #elif defined (HAVE_GTK) - return cvGetPropWindowAutoSize_GTK(name); + return cvGetPropWindowAutoSize_GTK(name.c_str()); #else return -1; #endif break; - case CV_WND_PROP_ASPECTRATIO: + case cv::WND_PROP_ASPECT_RATIO: #if defined (HAVE_QT) - return cvGetRatioWindow_QT(name); + return cvGetRatioWindow_QT(name.c_str()); #elif defined(HAVE_WIN32UI) - return cvGetRatioWindow_W32(name); + return cvGetRatioWindow_W32(name.c_str()); #elif defined (HAVE_GTK) - return cvGetRatioWindow_GTK(name); + return cvGetRatioWindow_GTK(name.c_str()); #else return -1; #endif break; - case CV_WND_PROP_OPENGL: + case cv::WND_PROP_OPENGL: #if defined (HAVE_QT) - return cvGetOpenGlProp_QT(name); + return cvGetOpenGlProp_QT(name.c_str()); #elif defined(HAVE_WIN32UI) - return cvGetOpenGlProp_W32(name); + return cvGetOpenGlProp_W32(name.c_str()); #elif defined (HAVE_GTK) - return cvGetOpenGlProp_GTK(name); + return cvGetOpenGlProp_GTK(name.c_str()); #else return -1; #endif break; - case CV_WND_PROP_VISIBLE: + case cv::WND_PROP_VISIBLE: #if defined (HAVE_QT) - return cvGetPropVisible_QT(name); + return cvGetPropVisible_QT(name.c_str()); #elif defined(HAVE_WIN32UI) - return cvGetPropVisible_W32(name); + return cvGetPropVisible_W32(name.c_str()); #else return -1; #endif @@ -375,9 +374,9 @@ CV_IMPL double cvGetWindowProperty(const char* name, int prop_id) #if defined (HAVE_QT) return -1; #elif defined(HAVE_WIN32UI) - return cvGetPropTopmost_W32(name); + return cvGetPropTopmost_W32(name.c_str()); #elif defined(HAVE_COCOA) - return cvGetPropTopmost_COCOA(name); + return cvGetPropTopmost_COCOA(name.c_str()); #else return -1; #endif @@ -387,7 +386,7 @@ CV_IMPL double cvGetWindowProperty(const char* name, int prop_id) #if defined (HAVE_QT) return -1; #elif defined (HAVE_WIN32UI) - return cvGetPropVsync_W32(name); + return cvGetPropVsync_W32(name.c_str()); #else return -1; #endif @@ -478,7 +477,7 @@ void cv::namedWindow( const String& winname, int flags ) } } - cvNamedWindow( winname.c_str(), flags ); + namedWindowImpl( winname.c_str(), flags ); } void cv::destroyWindow( const String& winname ) @@ -495,7 +494,7 @@ void cv::destroyWindow( const String& winname ) } } - cvDestroyWindow( winname.c_str() ); + destroyWindowImpl( winname.c_str() ); } void cv::destroyAllWindows() @@ -513,7 +512,7 @@ void cv::destroyAllWindows() } } - cvDestroyAllWindows(); + destroyAllWindowsImpl(); } void cv::resizeWindow( const String& winname, int width, int height ) @@ -541,14 +540,14 @@ void cv::resizeWindow( const String& winname, int width, int height ) } return; #else - cvResizeWindow( winname.c_str(), width, height ); + resizeWindowImpl( winname.c_str(), width, height ); #endif } void cv::resizeWindow(const String& winname, const cv::Size& size) { CV_TRACE_FUNCTION(); - cvResizeWindow(winname.c_str(), size.width, size.height); + resizeWindowImpl(winname.c_str(), size.width, size.height); } void cv::moveWindow( const String& winname, int x, int y ) @@ -576,7 +575,7 @@ void cv::moveWindow( const String& winname, int x, int y ) } return; #else - cvMoveWindow( winname.c_str(), x, y ); + moveWindowImpl( winname.c_str(), x, y ); #endif } @@ -622,17 +621,7 @@ void cv::setWindowTitle(const String& winname, const String& title) #endif } -void cv::setWindowProperty(const String& winname, int prop_id, double prop_value) -{ - CV_TRACE_FUNCTION(); - cvSetWindowProperty( winname.c_str(), prop_id, prop_value); -} -double cv::getWindowProperty(const String& winname, int prop_id) -{ - CV_TRACE_FUNCTION(); - return cvGetWindowProperty(winname.c_str(), prop_id); -} int cv::waitKeyEx(int delay) { @@ -647,7 +636,7 @@ int cv::waitKeyEx(int delay) } } - return cvWaitKey(delay); + return waitKeyImpl(delay); } int cv::waitKey(int delay) @@ -686,7 +675,7 @@ int cv::pollKey() return pollKey_W32(); #else // fallback. please implement a proper polling function - return cvWaitKey(1); + return waitKeyImpl(1); #endif } @@ -746,7 +735,7 @@ int cv::createTrackbar(const String& trackbarName, const String& winName, } return 0; #else - return cvCreateTrackbar2(trackbarName.c_str(), winName.c_str(), + return createTrackbar2Impl(trackbarName.c_str(), winName.c_str(), value, count, callback, userdata); #endif } @@ -779,7 +768,7 @@ void cv::setTrackbarPos( const String& trackbarName, const String& winName, int } return; #else - cvSetTrackbarPos(trackbarName.c_str(), winName.c_str(), value ); + setTrackbarPosImpl(trackbarName.c_str(), winName.c_str(), value ); #endif } @@ -813,7 +802,7 @@ void cv::setTrackbarMax(const String& trackbarName, const String& winName, int m } return; #else - cvSetTrackbarMax(trackbarName.c_str(), winName.c_str(), maxval); + setTrackbarMaxImpl(trackbarName.c_str(), winName.c_str(), maxval); #endif } @@ -847,7 +836,7 @@ void cv::setTrackbarMin(const String& trackbarName, const String& winName, int m } return; #else - cvSetTrackbarMin(trackbarName.c_str(), winName.c_str(), minval); + setTrackbarMinImpl(trackbarName.c_str(), winName.c_str(), minval); #endif } @@ -879,7 +868,7 @@ int cv::getTrackbarPos( const String& trackbarName, const String& winName ) } return -1; #else - return cvGetTrackbarPos(trackbarName.c_str(), winName.c_str()); + return getTrackbarPosImpl(trackbarName.c_str(), winName.c_str()); #endif } @@ -909,40 +898,42 @@ void cv::setMouseCallback( const String& windowName, MouseCallback onMouse, void } return; #else - cvSetMouseCallback(windowName.c_str(), onMouse, param); + setMouseCallbackImpl(windowName.c_str(), onMouse, param); #endif } int cv::getMouseWheelDelta( int flags ) { CV_TRACE_FUNCTION(); - return CV_GET_WHEEL_DELTA(flags); + return ((short)((flags >> 16) & 0xffff)); // upper 16 bits } +#if !defined (HAVE_GTK) int cv::startWindowThread() { CV_TRACE_FUNCTION(); - return cvStartWindowThread(); + return 0; } +#endif // !GTK // OpenGL support void cv::setOpenGlDrawCallback(const String& name, OpenGlDrawCallback callback, void* userdata) { CV_TRACE_FUNCTION(); - cvSetOpenGlDrawCallback(name.c_str(), callback, userdata); + setOpenGLDrawCallbackImpl(name.c_str(), callback, userdata); } void cv::setOpenGlContext(const String& windowName) { CV_TRACE_FUNCTION(); - cvSetOpenGlContext(windowName.c_str()); + setOpenGLContextImpl(windowName.c_str()); } void cv::updateWindow(const String& windowName) { CV_TRACE_FUNCTION(); - cvUpdateWindow(windowName.c_str()); + updateWindowImpl(windowName.c_str()); } #ifdef HAVE_OPENGL @@ -1003,7 +994,7 @@ void cv::imshow( const String& winname, InputArray _img ) { Mat img = _img.getMat(); CvMat c_img = cvMat(img); - cvShowImage(winname.c_str(), &c_img); + showImageImpl(winname.c_str(), &c_img); } #else const double useGl = getWindowProperty(winname, WND_PROP_OPENGL); @@ -1012,7 +1003,7 @@ void cv::imshow( const String& winname, InputArray _img ) { Mat img = _img.getMat(); CvMat c_img = cvMat(img); - cvShowImage(winname.c_str(), &c_img); + showImageImpl(winname.c_str(), &c_img); } else { @@ -1089,86 +1080,31 @@ void cv::imshow(const String& winname, const ogl::Texture2D& _tex) #endif } -// Without OpenGL +//========================= OpenGL fallback ========================= #ifndef HAVE_OPENGL -CV_IMPL void cvSetOpenGlDrawCallback(const char*, CvOpenGlDrawCallback, void*) +void setOpenGLDrawCallbackImpl(const char*, CvOpenGlDrawCallback, void*) { CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support"); } -CV_IMPL void cvSetOpenGlContext(const char*) +void setOpenGLContextImpl(const char*) { CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support"); } -CV_IMPL void cvUpdateWindow(const char*) +void updateWindowImpl(const char*) { CV_Error(CV_OpenGlNotSupported, "The library is compiled without OpenGL support"); } #endif // !HAVE_OPENGL -#if defined (HAVE_QT) +//========================= Qt fallback ========================= -cv::QtFont cv::fontQt(const String& nameFont, int pointSize, Scalar color, int weight, int style, int spacing) -{ - CvFont f = cvFontQt(nameFont.c_str(), pointSize, cvScalar(color), weight, style, spacing); - void* pf = &f; // to suppress strict-aliasing - return *(cv::QtFont*)pf; -} - -void cv::addText( const Mat& img, const String& text, Point org, const QtFont& font) -{ - CvMat _img = cvMat(img); - cvAddText( &_img, text.c_str(), cvPoint(org), (CvFont*)&font); -} - -void cv::addText( const Mat& img, const String& text, Point org, const String& nameFont, - int pointSize, Scalar color, int weight, int style, int spacing) -{ - CvFont f = cvFontQt(nameFont.c_str(), pointSize, cvScalar(color), weight, style, spacing); - CvMat _img = cvMat(img); - cvAddText( &_img, text.c_str(), cvPoint(org), &f); -} - -void cv::displayStatusBar(const String& name, const String& text, int delayms) -{ - cvDisplayStatusBar(name.c_str(),text.c_str(), delayms); -} - -void cv::displayOverlay(const String& name, const String& text, int delayms) -{ - cvDisplayOverlay(name.c_str(),text.c_str(), delayms); -} - -int cv::startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]) -{ - return cvStartLoop(pt2Func, argc, argv); -} - -void cv::stopLoop() -{ - cvStopLoop(); -} - -void cv::saveWindowParameters(const String& windowName) -{ - cvSaveWindowParameters(windowName.c_str()); -} - -void cv::loadWindowParameters(const String& windowName) -{ - cvLoadWindowParameters(windowName.c_str()); -} - -int cv::createButton(const String& button_name, ButtonCallback on_change, void* userdata, int button_type , bool initial_button_state ) -{ - return cvCreateButton(button_name.c_str(), on_change, userdata, button_type , initial_button_state ); -} - -#else +// moved to window_QT.cpp +#ifndef HAVE_QT static const char* NO_QT_ERR_MSG = "The library is compiled without QT support"; @@ -1222,16 +1158,13 @@ int cv::createButton(const String&, ButtonCallback, void*, int , bool ) CV_Error(CV_StsNotImplemented, NO_QT_ERR_MSG); } -#endif +#endif // !HAVE_QT -#if defined (HAVE_WIN32UI) // see window_w32.cpp -#elif defined (HAVE_GTK) // see window_gtk.cpp -#elif defined (HAVE_COCOA) // see window_cocoa.mm -#elif defined (HAVE_QT) // see window_QT.cpp -#elif defined (HAVE_WAYLAND) // see window_wayland.cpp -#elif defined (WINRT) && !defined (WINRT_8_0) // see window_winrt.cpp -#else +//========================= NO GUI fallback ========================= + +#if !defined (HAVE_WIN32UI) && !defined (HAVE_GTK) && !defined (HAVE_COCOA) && !defined (HAVE_QT) \ + && !defined (HAVE_WAYLAND) && !defined (WINRT) && !defined (WINRT_8_0) // No windowing system present at compile time ;-( // @@ -1248,148 +1181,73 @@ int cv::createButton(const String&, ButtonCallback, void*, int , bool ) funcname, __FILE__, __LINE__) -CV_IMPL int cvNamedWindow( const char*, int ) +int namedWindowImpl( const char*, int ) { - CV_NO_GUI_ERROR("cvNamedWindow"); + CV_NO_GUI_ERROR("namedWindowImpl"); } -CV_IMPL void cvDestroyWindow( const char* ) +void destroyWindowImpl( const char* ) { - CV_NO_GUI_ERROR( "cvDestroyWindow" ); + CV_NO_GUI_ERROR( "destroyWindowImpl" ); } -CV_IMPL void -cvDestroyAllWindows( void ) +void destroyAllWindowsImpl( void ) { - CV_NO_GUI_ERROR( "cvDestroyAllWindows" ); + CV_NO_GUI_ERROR( "destroyAllWindowsImpl" ); } -CV_IMPL void -cvShowImage( const char*, const CvArr* ) +void showImageImpl( const char*, const CvArr* ) { - CV_NO_GUI_ERROR( "cvShowImage" ); + CV_NO_GUI_ERROR( "showImageImpl" ); } -CV_IMPL void cvResizeWindow( const char*, int, int ) +void resizeWindowImpl( const char*, int, int ) { - CV_NO_GUI_ERROR( "cvResizeWindow" ); + CV_NO_GUI_ERROR( "resizeWindowImpl" ); } -CV_IMPL void cvMoveWindow( const char*, int, int ) +void moveWindowImpl( const char*, int, int ) { - CV_NO_GUI_ERROR( "cvMoveWindow" ); + CV_NO_GUI_ERROR( "moveWindowImpl" ); } -CV_IMPL int -cvCreateTrackbar( const char*, const char*, - int*, int, CvTrackbarCallback ) -{ - CV_NO_GUI_ERROR( "cvCreateTrackbar" ); -} - -CV_IMPL int -cvCreateTrackbar2( const char* /*trackbar_name*/, const char* /*window_name*/, +int createTrackbar2Impl( const char* /*trackbar_name*/, const char* /*window_name*/, int* /*val*/, int /*count*/, CvTrackbarCallback2 /*on_notify2*/, void* /*userdata*/ ) { - CV_NO_GUI_ERROR( "cvCreateTrackbar2" ); + CV_NO_GUI_ERROR( "createTrackbar2Impl" ); } -CV_IMPL void -cvSetMouseCallback( const char*, CvMouseCallback, void* ) +void setMouseCallbackImpl( const char*, CvMouseCallback, void* ) { - CV_NO_GUI_ERROR( "cvSetMouseCallback" ); + CV_NO_GUI_ERROR( "setMouseCallbackImpl" ); } -CV_IMPL int cvGetTrackbarPos( const char*, const char* ) +int getTrackbarPosImpl( const char*, const char* ) { - CV_NO_GUI_ERROR( "cvGetTrackbarPos" ); + CV_NO_GUI_ERROR( "getTrackbarPosImpl" ); } -CV_IMPL void cvSetTrackbarPos( const char*, const char*, int ) +void setTrackbarPosImpl( const char*, const char*, int ) { - CV_NO_GUI_ERROR( "cvSetTrackbarPos" ); + CV_NO_GUI_ERROR( "setTrackbarPosImpl" ); } -CV_IMPL void cvSetTrackbarMax(const char*, const char*, int) +void setTrackbarMaxImpl(const char*, const char*, int) { - CV_NO_GUI_ERROR( "cvSetTrackbarMax" ); + CV_NO_GUI_ERROR( "setTrackbarMaxImpl" ); } -CV_IMPL void cvSetTrackbarMin(const char*, const char*, int) +void setTrackbarMinImpl(const char*, const char*, int) { - CV_NO_GUI_ERROR( "cvSetTrackbarMin" ); + CV_NO_GUI_ERROR( "setTrackbarMinImpl" ); } -CV_IMPL void* cvGetWindowHandle( const char* ) +int waitKeyImpl( int ) { - CV_NO_GUI_ERROR( "cvGetWindowHandle" ); + CV_NO_GUI_ERROR( "waitKeyImpl" ); } -CV_IMPL const char* cvGetWindowName( void* ) -{ - CV_NO_GUI_ERROR( "cvGetWindowName" ); -} - -CV_IMPL int cvWaitKey( int ) -{ - CV_NO_GUI_ERROR( "cvWaitKey" ); -} - -CV_IMPL int cvInitSystem( int , char** ) -{ - - CV_NO_GUI_ERROR( "cvInitSystem" ); -} - -CV_IMPL int cvStartWindowThread() -{ - - CV_NO_GUI_ERROR( "cvStartWindowThread" ); -} - -//-------- Qt --------- -CV_IMPL void cvAddText( const CvArr*, const char*, CvPoint , CvFont* ) -{ - CV_NO_GUI_ERROR("cvAddText"); -} - -CV_IMPL void cvDisplayStatusBar(const char* , const char* , int ) -{ - CV_NO_GUI_ERROR("cvDisplayStatusBar"); -} - -CV_IMPL void cvDisplayOverlay(const char* , const char* , int ) -{ - CV_NO_GUI_ERROR("cvNamedWindow"); -} - -CV_IMPL int cvStartLoop(int (*)(int argc, char *argv[]), int , char* argv[]) -{ - CV_UNUSED(argv); - CV_NO_GUI_ERROR("cvStartLoop"); -} - -CV_IMPL void cvStopLoop() -{ - CV_NO_GUI_ERROR("cvStopLoop"); -} - -CV_IMPL void cvSaveWindowParameters(const char* ) -{ - CV_NO_GUI_ERROR("cvSaveWindowParameters"); -} - -// CV_IMPL void cvLoadWindowParameterss(const char* name) -// { -// CV_NO_GUI_ERROR("cvLoadWindowParameters"); -// } - -CV_IMPL int cvCreateButton(const char*, void (*)(int, void*), void*, int, int) -{ - CV_NO_GUI_ERROR("cvCreateButton"); -} - -#endif +#endif // NO_GUI /* End of file. */ diff --git a/modules/highgui/src/window_QT.cpp b/modules/highgui/src/window_QT.cpp index eba3599a0d..9f1cdc2827 100644 --- a/modules/highgui/src/window_QT.cpp +++ b/modules/highgui/src/window_QT.cpp @@ -124,40 +124,120 @@ Qt::ConnectionType autoBlockingConnection() { : Qt::DirectConnection; } -CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing) +cv::QtFont cv::fontQt(const String& nameFont, int pointSize, Scalar color, int weight, int style, int spacing) { - /* - //nameFont <- only Qt - //CvScalar color <- only Qt (blue_component, green_component, red\_component[, alpha_component]) - int font_face;//<- style in Qt - const int* ascii; - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; - int thickness;//<- weight in Qt - float dx;//spacing letter in Qt (0 default) in pixel - int line_type;//<- pointSize in Qt - */ - CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight, (float)spacing, pointSize}; - return f; + QtFont res = { + nameFont.c_str(), color, style, NULL, NULL, NULL, 0,0,0, weight, (float)spacing, pointSize + }; + return res; } +void cv::addText( const Mat& img, const String& text, Point org, const QtFont& font) +{ -CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font) + if (!guiMainThread) + CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); + + CvMat _img = cvMat(img); + QMetaObject::invokeMethod( + guiMainThread, + "putText", + autoBlockingConnection(), + Q_ARG(void*, (void*)&_img), + Q_ARG(QString,QString::fromUtf8(text.c_str())), + Q_ARG(QPoint, QPoint(org.x,org.y)), + Q_ARG(void*,(void*)&font) + ); +} + +void cv::addText( const Mat& img, const String& text, Point org, const String& nameFont, + int pointSize, Scalar color, int weight, int style, int spacing) +{ + cv::QtFont f = cv::fontQt(nameFont.c_str(), pointSize, cvScalar(color), weight, style, spacing); + cv::addText(img, text, org, f); +} + +void cv::displayStatusBar(const String& name, const String& text, int delayms) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, - "putText", + "displayStatusBar", autoBlockingConnection(), - Q_ARG(void*, (void*) img), - Q_ARG(QString,QString::fromUtf8(text)), - Q_ARG(QPoint, QPoint(org.x,org.y)), - Q_ARG(void*,(void*) font)); + Q_ARG(QString, QString(name.c_str())), + Q_ARG(QString, QString(text.c_str())), + Q_ARG(int, delayms)); + } +void cv::displayOverlay(const String& name, const String& text, int delayms) +{ + if (!guiMainThread) + CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); + + QMetaObject::invokeMethod(guiMainThread, + "displayInfo", + autoBlockingConnection(), + Q_ARG(QString, QString(name.c_str())), + Q_ARG(QString, QString(text.c_str())), + Q_ARG(int, delayms)); +} + +//Yannick Verdie +//This function is experimental and some functions (such as cvSet/getWindowProperty will not work) +//We recommend not using this function for now +int cv::startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]) +{ + multiThreads = true; + QFuture future = QtConcurrent::run(pt2Func, argc, argv); + return guiMainThread->start(); +} + +void cv::stopLoop() +{ + qApp->exit(); +} + +void cv::saveWindowParameters(const String& windowName) +{ + if (!guiMainThread) + CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); + + QMetaObject::invokeMethod(guiMainThread, + "saveWindowParameters", + autoBlockingConnection(), + Q_ARG(QString, QString(windowName.c_str()))); +} + +void cv::loadWindowParameters(const String& windowName) +{ + if (!guiMainThread) + CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); + + QMetaObject::invokeMethod(guiMainThread, + "loadWindowParameters", + autoBlockingConnection(), + Q_ARG(QString, QString(windowName.c_str()))); + +} + +int cv::createButton(const String& button_name, ButtonCallback on_change, void* userdata, int button_type , bool initial_button_state ) +{ + if (!guiMainThread) + CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); + + QMetaObject::invokeMethod(guiMainThread, + "addButton", + autoBlockingConnection(), + Q_ARG(QString, QString(button_name.c_str())), + Q_ARG(int, button_type), + Q_ARG(int, initial_button_state ? 1 : 0), + Q_ARG(void*, (void*)on_change), + Q_ARG(void*, userdata)); + + return 1;//dummy value +} double cvGetRatioWindow_QT(const char* name) { @@ -287,60 +367,7 @@ double cvGetModeWindow_QT(const char* name) return result; } - -CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - QMetaObject::invokeMethod(guiMainThread, - "displayInfo", - autoBlockingConnection(), - Q_ARG(QString, QString(name)), - Q_ARG(QString, QString(text)), - Q_ARG(int, delayms)); -} - - -CV_IMPL void cvSaveWindowParameters(const char* name) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - QMetaObject::invokeMethod(guiMainThread, - "saveWindowParameters", - autoBlockingConnection(), - Q_ARG(QString, QString(name))); -} - - -CV_IMPL void cvLoadWindowParameters(const char* name) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - QMetaObject::invokeMethod(guiMainThread, - "loadWindowParameters", - autoBlockingConnection(), - Q_ARG(QString, QString(name))); -} - - -CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - QMetaObject::invokeMethod(guiMainThread, - "displayStatusBar", - autoBlockingConnection(), - Q_ARG(QString, QString(name)), - Q_ARG(QString, QString(text)), - Q_ARG(int, delayms)); -} - - -CV_IMPL int cvWaitKey(int delay) +int waitKeyImpl(int delay) { int result = -1; @@ -414,24 +441,6 @@ CV_IMPL int cvWaitKey(int delay) return result; } - -//Yannick Verdie -//This function is experimental and some functions (such as cvSet/getWindowProperty will not work) -//We recommend not using this function for now -CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]) -{ - multiThreads = true; - QFuture future = QtConcurrent::run(pt2Func, argc, argv); - return guiMainThread->start(); -} - - -CV_IMPL void cvStopLoop() -{ - qApp->exit(); -} - - static CvWindow* icvFindWindowByName(QString name) { CvWindow* window = 0; @@ -494,10 +503,10 @@ static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* if (!w) CV_Error(CV_StsNullPtr, "NULL window handler"); - if (w->param_gui_mode == CV_GUI_NORMAL) + if (w->param_gui_mode == cv::WINDOW_GUI_NORMAL) return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar); - if (w->param_gui_mode == CV_GUI_EXPANDED) + if (w->param_gui_mode == cv::WINDOW_GUI_EXPANDED) { CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar); @@ -545,15 +554,7 @@ static int icvInitSystem(int* c, char** v) return 0; } - -CV_IMPL int cvInitSystem(int, char**) -{ - icvInitSystem(¶meterSystemC, parameterSystemV); - return 0; -} - - -CV_IMPL int cvNamedWindow(const char* name, int flags) +int namedWindowImpl(const char* name, int flags) { if (!guiMainThread) guiMainThread = new GuiReceiver; @@ -572,7 +573,7 @@ CV_IMPL int cvNamedWindow(const char* name, int flags) } -CV_IMPL void cvDestroyWindow(const char* name) +void destroyWindowImpl(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -584,7 +585,7 @@ CV_IMPL void cvDestroyWindow(const char* name) } -CV_IMPL void cvDestroyAllWindows() +void destroyAllWindowsImpl() { if (!guiMainThread) return; @@ -595,25 +596,7 @@ CV_IMPL void cvDestroyAllWindows() } -CV_IMPL void* cvGetWindowHandle(const char* name) -{ - if (!name) - CV_Error( CV_StsNullPtr, "NULL name string" ); - - return (void*) icvFindWindowByName(QLatin1String(name)); -} - - -CV_IMPL const char* cvGetWindowName(void* window_handle) -{ - if( !window_handle ) - CV_Error( CV_StsNullPtr, "NULL window handler" ); - - return ((CvWindow*)window_handle)->objectName().toLatin1().data(); -} - - -CV_IMPL void cvMoveWindow(const char* name, int x, int y) +void moveWindowImpl(const char* name, int x, int y) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -625,7 +608,7 @@ CV_IMPL void cvMoveWindow(const char* name, int x, int y) Q_ARG(int, y)); } -CV_IMPL void cvResizeWindow(const char* name, int width, int height) +void resizeWindowImpl(const char* name, int width, int height) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -638,7 +621,7 @@ CV_IMPL void cvResizeWindow(const char* name, int width, int height) } -CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata) +int createTrackbar2Impl(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -656,53 +639,7 @@ CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int return 1; //dummy value } - -CV_IMPL int cvStartWindowThread() -{ - return 0; -} - - -CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - QMetaObject::invokeMethod(guiMainThread, - "addSlider", - autoBlockingConnection(), - Q_ARG(QString, QString(name_bar)), - Q_ARG(QString, QString(window_name)), - Q_ARG(void*, (void*)value), - Q_ARG(int, count), - Q_ARG(void*, (void*)on_change)); - - return 1; //dummy value -} - - -CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state) -{ - if (!guiMainThread) - CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); - - if (initial_button_state < 0 || initial_button_state > 1) - return 0; - - QMetaObject::invokeMethod(guiMainThread, - "addButton", - autoBlockingConnection(), - Q_ARG(QString, QString(button_name)), - Q_ARG(int, button_type), - Q_ARG(int, initial_button_state), - Q_ARG(void*, (void*)on_change), - Q_ARG(void*, userdata)); - - return 1;//dummy value -} - - -CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name) +int getTrackbarPosImpl(const char* name_bar, const char* window_name) { int result = -1; @@ -715,7 +652,7 @@ CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name) } -CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos) +void setTrackbarPosImpl(const char* name_bar, const char* window_name, int pos) { QPointer t = icvFindTrackBarByName(name_bar, window_name); @@ -724,7 +661,7 @@ CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int } -CV_IMPL void cvSetTrackbarMax(const char* name_bar, const char* window_name, int maxval) +void setTrackbarMaxImpl(const char* name_bar, const char* window_name, int maxval) { QPointer t = icvFindTrackBarByName(name_bar, window_name); if (t) @@ -734,7 +671,7 @@ CV_IMPL void cvSetTrackbarMax(const char* name_bar, const char* window_name, int } -CV_IMPL void cvSetTrackbarMin(const char* name_bar, const char* window_name, int minval) +void setTrackbarMinImpl(const char* name_bar, const char* window_name, int minval) { QPointer t = icvFindTrackBarByName(name_bar, window_name); if (t) @@ -745,7 +682,7 @@ CV_IMPL void cvSetTrackbarMin(const char* name_bar, const char* window_name, int /* assign callback for mouse events */ -CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param) +void setMouseCallbackImpl(const char* window_name, CvMouseCallback on_mouse, void* param) { QPointer w = icvFindWindowByName(QLatin1String(window_name)); @@ -757,7 +694,7 @@ CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mous } -CV_IMPL void cvShowImage(const char* name, const CvArr* arr) +void showImageImpl(const char* name, const CvArr* arr) { if (!guiMainThread) guiMainThread = new GuiReceiver; @@ -777,7 +714,7 @@ CV_IMPL void cvShowImage(const char* name, const CvArr* arr) #ifdef HAVE_QT_OPENGL -CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata) +void setOpenGLDrawCallbackImpl(const char* window_name, CvOpenGlDrawCallback callback, void* userdata) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -791,7 +728,7 @@ CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallba } -CV_IMPL void cvSetOpenGlContext(const char* window_name) +void setOpenGLContextImpl(const char* window_name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -803,7 +740,7 @@ CV_IMPL void cvSetOpenGlContext(const char* window_name) } -CV_IMPL void cvUpdateWindow(const char* window_name) +void updateWindowImpl(const char* window_name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); @@ -889,7 +826,7 @@ void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2) QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888); - CvFont* font = (CvFont*)arg2; + QtFont* font = (QtFont*)arg2; QPainter qp(&qimg); if (font) @@ -989,7 +926,7 @@ void GuiReceiver::setWindowTitle(QString name, QString title) if (!w) { - cvNamedWindow(name.toLatin1().data()); + namedWindowImpl(name.toLatin1().data()); w = icvFindWindowByName(name); } @@ -1016,7 +953,7 @@ double GuiReceiver::isFullScreen(QString name) if (!w) return -1; - return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL; + return w->isFullScreen() ? cv::WINDOW_FULLSCREEN : cv::WINDOW_NORMAL; } @@ -1046,7 +983,7 @@ void GuiReceiver::createWindow(QString name, int flags) nb_windows++; new CvWindow(name, flags); - cvWaitKey(1); + waitKeyImpl(1); } @@ -1080,7 +1017,7 @@ void GuiReceiver::showImage(QString name, void* arr) if (!w) //as observed in the previous implementation (W32, GTK), create a new window is the pointer returned is null { - cvNamedWindow(name.toLatin1().data()); + namedWindowImpl(name.toLatin1().data()); w = icvFindWindowByName(name); } @@ -1228,7 +1165,7 @@ void GuiReceiver::addButton(QString button_name, int button_type, int initial_bu // unset buttonbar flag button_type = button_type & ~cv::QT_NEW_BUTTONBAR; - b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state); + b->addButton(button_name, (ButtonCallback) on_change, userdata, button_type, initial_button_state); } @@ -1491,7 +1428,7 @@ void CvButtonbar::setLabel() } -void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state) +void CvButtonbar::addButton(QString name, cv::ButtonCallback call, void* userdata, int button_type, int initial_button_state) { QString button_name = name; @@ -1500,13 +1437,13 @@ void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, QPointer button; - if (button_type == CV_PUSH_BUTTON) + if (button_type == cv::QT_PUSH_BUTTON) button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata); - if (button_type == CV_CHECKBOX) + if (button_type == cv::QT_CHECKBOX) button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state); - if (button_type == CV_RADIOBOX) + if (button_type == cv::QT_RADIOBOX) { button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state); group_button->addButton(button); @@ -1514,7 +1451,7 @@ void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, if (button) { - if (button_type == CV_PUSH_BUTTON) + if (button_type == cv::QT_PUSH_BUTTON) QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool))); else QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool))); @@ -1529,7 +1466,7 @@ void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, //buttons here -CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4) +CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, ButtonCallback arg3, void* arg4) { myparent = arg1; button_name = arg2; @@ -1551,7 +1488,7 @@ void CvPushButton::callCallBack(bool checked) } -CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state) +CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, ButtonCallback arg3, void* arg4, int initial_button_state) { myparent = arg1; button_name = arg2; @@ -1574,7 +1511,7 @@ void CvCheckBox::callCallBack(bool checked) } -CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state) +CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, ButtonCallback arg3, void* arg4, int initial_button_state) { myparent = arg1; button_name = arg2; @@ -1701,19 +1638,19 @@ CvWindow::CvWindow(QString name, int arg2) //3: my view #ifndef HAVE_QT_OPENGL - if (arg2 & CV_WINDOW_OPENGL) + if (arg2 & cv::WINDOW_OPENGL) CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" ); mode_display = CV_MODE_NORMAL; #else - mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL; + mode_display = arg2 & cv::WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL; if (mode_display == CV_MODE_OPENGL) - param_gui_mode = CV_GUI_NORMAL; + param_gui_mode = cv::WINDOW_GUI_NORMAL; #endif createView(); //4: shortcuts and actions //5: toolBar and statusbar - if (param_gui_mode == CV_GUI_EXPANDED) + if (param_gui_mode == cv::WINDOW_GUI_EXPANDED) { createActions(); createShortcuts(); @@ -1836,13 +1773,13 @@ void CvWindow::setPropWindow(int flags) switch(flags) { - case CV_WINDOW_NORMAL: + case cv::WINDOW_NORMAL: myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); param_flags = flags; break; - case CV_WINDOW_AUTOSIZE: + case cv::WINDOW_AUTOSIZE: myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize); param_flags = flags; @@ -1855,14 +1792,14 @@ void CvWindow::setPropWindow(int flags) void CvWindow::toggleFullScreen(int flags) { - if (isFullScreen() && flags == CV_WINDOW_NORMAL) + if (isFullScreen() && flags == cv::WINDOW_NORMAL) { showTools(); showNormal(); return; } - if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN) + if (!isFullScreen() && flags == cv::WINDOW_FULLSCREEN) { hideTools(); showFullScreen(); @@ -2012,9 +1949,9 @@ void CvWindow::createGlobalLayout() #endif setMinimumSize(1, 1); - if (param_flags == CV_WINDOW_AUTOSIZE) + if (param_flags == cv::WINDOW_AUTOSIZE) myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize); - else if (param_flags == CV_WINDOW_NORMAL) + else if (param_flags == cv::WINDOW_NORMAL) myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); } @@ -2463,23 +2400,23 @@ void OCVViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, // icvmouseHandler called with flags == 0 where it really need. //flags = 0; if(modifiers & Qt::ShiftModifier) - flags |= CV_EVENT_FLAG_SHIFTKEY; + flags |= cv::EVENT_FLAG_SHIFTKEY; if(modifiers & Qt::ControlModifier) - flags |= CV_EVENT_FLAG_CTRLKEY; + flags |= cv::EVENT_FLAG_CTRLKEY; if(modifiers & Qt::AltModifier) - flags |= CV_EVENT_FLAG_ALTKEY; + flags |= cv::EVENT_FLAG_ALTKEY; if(buttons & Qt::LeftButton) - flags |= CV_EVENT_FLAG_LBUTTON; + flags |= cv::EVENT_FLAG_LBUTTON; if(buttons & Qt::RightButton) - flags |= CV_EVENT_FLAG_RBUTTON; + flags |= cv::EVENT_FLAG_RBUTTON; if(buttons & Qt_MiddleButton) - flags |= CV_EVENT_FLAG_MBUTTON; + flags |= cv::EVENT_FLAG_MBUTTON; if (cv_event == -1) { if (category == mouse_wheel) { QWheelEvent *we = (QWheelEvent *) evnt; - cv_event = ((wheelEventOrientation(we) == Qt::Vertical) ? CV_EVENT_MOUSEWHEEL : CV_EVENT_MOUSEHWHEEL); + cv_event = ((wheelEventOrientation(we) == Qt::Vertical) ? cv::EVENT_MOUSEWHEEL : cv::EVENT_MOUSEHWHEEL); flags |= (wheelEventDelta(we) & 0xffff)<<16; return; } @@ -2487,18 +2424,18 @@ void OCVViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, { case Qt::LeftButton: cv_event = tableMouseButtons[category][0]; - flags |= CV_EVENT_FLAG_LBUTTON; + flags |= cv::EVENT_FLAG_LBUTTON; break; case Qt::RightButton: cv_event = tableMouseButtons[category][1]; - flags |= CV_EVENT_FLAG_RBUTTON; + flags |= cv::EVENT_FLAG_RBUTTON; break; case Qt_MiddleButton: cv_event = tableMouseButtons[category][2]; - flags |= CV_EVENT_FLAG_MBUTTON; + flags |= cv::EVENT_FLAG_MBUTTON; break; default: - cv_event = CV_EVENT_MOUSEMOVE; + cv_event = cv::EVENT_MOUSEMOVE; } } } @@ -2603,7 +2540,7 @@ void DefaultViewPort::setRatio(int flags) return; //if valid flags - if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO) + if (flags == cv::WINDOW_FREERATIO || flags == cv::WINDOW_KEEPRATIO) { centralWidget->param_ratio_mode = flags; param_keepRatio = flags; @@ -2814,7 +2751,7 @@ void DefaultViewPort::resizeEvent(QResizeEvent* evnt) ratioX = width() / float(image2Draw_mat->cols); ratioY = height() / float(image2Draw_mat->rows); - if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio + if (param_keepRatio == cv::WINDOW_KEEPRATIO)//to keep the same aspect ratio { QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows); newSize.scale(evnt->size(), Qt::KeepAspectRatio); diff --git a/modules/highgui/src/window_QT.h b/modules/highgui/src/window_QT.h index b93b9ba597..09d93c5460 100644 --- a/modules/highgui/src/window_QT.h +++ b/modules/highgui/src/window_QT.h @@ -182,7 +182,7 @@ class CvButtonbar : public CvBar public: CvButtonbar(QWidget* arg, QString bar_name); - void addButton(QString button_name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state); + void addButton(QString button_name, cv::ButtonCallback call, void* userdata, int button_type, int initial_button_state); private: void setLabel(); @@ -196,12 +196,12 @@ class CvPushButton : public QPushButton { Q_OBJECT public: - CvPushButton(CvButtonbar* par, QString button_name, CvButtonCallback call, void* userdata); + CvPushButton(CvButtonbar* par, QString button_name, cv::ButtonCallback call, void* userdata); private: CvButtonbar* myparent; QString button_name ; - CvButtonCallback callback; + cv::ButtonCallback callback; void* userdata; private slots: @@ -213,12 +213,12 @@ class CvCheckBox : public QCheckBox { Q_OBJECT public: - CvCheckBox(CvButtonbar* par, QString button_name, CvButtonCallback call, void* userdata, int initial_button_state); + CvCheckBox(CvButtonbar* par, QString button_name, cv::ButtonCallback call, void* userdata, int initial_button_state); private: CvButtonbar* myparent; QString button_name ; - CvButtonCallback callback; + cv::ButtonCallback callback; void* userdata; private slots: @@ -230,12 +230,12 @@ class CvRadioButton : public QRadioButton { Q_OBJECT public: - CvRadioButton(CvButtonbar* par, QString button_name, CvButtonCallback call, void* userdata, int initial_button_state); + CvRadioButton(CvButtonbar* par, QString button_name, cv::ButtonCallback call, void* userdata, int initial_button_state); private: CvButtonbar* myparent; QString button_name ; - CvButtonCallback callback; + cv::ButtonCallback callback; void* userdata; private slots: @@ -297,7 +297,7 @@ class CvWindow : public CvWinModel { Q_OBJECT public: - CvWindow(QString arg2, int flag = CV_WINDOW_NORMAL); + CvWindow(QString arg2, int flag = cv::WINDOW_NORMAL); ~CvWindow(); void setMouseCallBack(CvMouseCallback m, void* param); @@ -384,10 +384,10 @@ private slots: enum type_mouse_event { mouse_up = 0, mouse_down = 1, mouse_dbclick = 2, mouse_move = 3, mouse_wheel = 4 }; static const int tableMouseButtons[][3]={ - {CV_EVENT_LBUTTONUP, CV_EVENT_RBUTTONUP, CV_EVENT_MBUTTONUP}, //mouse_up - {CV_EVENT_LBUTTONDOWN, CV_EVENT_RBUTTONDOWN, CV_EVENT_MBUTTONDOWN}, //mouse_down - {CV_EVENT_LBUTTONDBLCLK, CV_EVENT_RBUTTONDBLCLK, CV_EVENT_MBUTTONDBLCLK}, //mouse_dbclick - {CV_EVENT_MOUSEMOVE, CV_EVENT_MOUSEMOVE, CV_EVENT_MOUSEMOVE}, //mouse_move + {cv::EVENT_LBUTTONUP, cv::EVENT_RBUTTONUP, cv::EVENT_MBUTTONUP}, //mouse_up + {cv::EVENT_LBUTTONDOWN, cv::EVENT_RBUTTONDOWN, cv::EVENT_MBUTTONDOWN}, //mouse_down + {cv::EVENT_LBUTTONDBLCLK, cv::EVENT_RBUTTONDBLCLK, cv::EVENT_MBUTTONDBLCLK}, //mouse_dbclick + {cv::EVENT_MOUSEMOVE, cv::EVENT_MOUSEMOVE, cv::EVENT_MOUSEMOVE}, //mouse_move {0, 0, 0} //mouse_wheel, to prevent exceptions in code }; diff --git a/modules/highgui/src/window_cocoa.mm b/modules/highgui/src/window_cocoa.mm index ef3f828cf8..16d3f83ecc 100644 --- a/modules/highgui/src/window_cocoa.mm +++ b/modules/highgui/src/window_cocoa.mm @@ -48,26 +48,21 @@ #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR /*** begin IPhone OS Stubs ***/ // When highgui functions are referred to on iPhone OS, they will fail silently. -CV_IMPL int cvInitSystem( int argc, char** argv) { return 0;} -CV_IMPL int cvStartWindowThread(){ return 0; } -CV_IMPL void cvDestroyWindow( const char* name) {} -CV_IMPL void cvDestroyAllWindows( void ) {} -CV_IMPL void cvShowImage( const char* name, const CvArr* arr) {} -CV_IMPL void cvResizeWindow( const char* name, int width, int height) {} -CV_IMPL void cvMoveWindow( const char* name, int x, int y){} -CV_IMPL int cvCreateTrackbar (const char* trackbar_name,const char* window_name, - int* val, int count, CvTrackbarCallback on_notify) {return 0;} -CV_IMPL int cvCreateTrackbar2(const char* trackbar_name,const char* window_name, +static int cocoa_InitSystem( int argc, char** argv) { return 0;} +void destroyWindowImpl( const char* name) {} +void destroyAllWindowsImpl( void ) {} +void showImageImpl( const char* name, const CvArr* arr) {} +void resizeWindowImpl( const char* name, int width, int height) {} +void moveWindowImpl( const char* name, int x, int y){} +int createTrackbar2Impl(const char* trackbar_name,const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify2, void* userdata) {return 0;} -CV_IMPL void cvSetMouseCallback( const char* name, CvMouseCallback function, void* info) {} -CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name ) {return 0;} -CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos) {} -CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval) {} -CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval) {} -CV_IMPL void* cvGetWindowHandle( const char* name ) {return NULL;} -CV_IMPL const char* cvGetWindowName( void* window_handle ) {return NULL;} -CV_IMPL int cvNamedWindow( const char* name, int flags ) {return 0; } -CV_IMPL int cvWaitKey (int maxWait) {return 0;} +void setMouseCallbackImpl( const char* name, CvMouseCallback function, void* info) {} +int getTrackbarPosImpl( const char* trackbar_name, const char* window_name ) {return 0;} +void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int pos) {} +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval) {} +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval) {} +int namedWindowImpl( const char* name, int flags ) {return 0; } +int waitKeyImpl (int maxWait) {return 0;} //*** end IphoneOS Stubs ***/ #else @@ -137,16 +132,16 @@ static bool wasInitialized = false; //cout << "icvCocoaCleanup" << endl; if( application ) { - cvDestroyAllWindows(); + destroyAllWindowsImpl(); //[application terminate:nil]; application = 0; [pool release]; } }*/ -CV_IMPL int cvInitSystem( int , char** ) +static int cocoa_InitSystem( int , char** ) { - //cout << "cvInitSystem" << endl; + //cout << "cocoa_InitSystem" << endl; wasInitialized = true; pool = [[NSAutoreleasePool alloc] init]; @@ -182,17 +177,11 @@ static CVWindow *cvGetWindow(const char *name) { return retval; } -CV_IMPL int cvStartWindowThread() -{ - //cout << "cvStartWindowThread" << endl; - return 0; -} - -CV_IMPL void cvDestroyWindow( const char* name) +void destroyWindowImpl( const char* name) { NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; - //cout << "cvDestroyWindow" << endl; + //cout << "destroyWindowImpl" << endl; CVWindow *window = cvGetWindow(name); if(window) { [window close]; @@ -202,26 +191,26 @@ CV_IMPL void cvDestroyWindow( const char* name) } -CV_IMPL void cvDestroyAllWindows( void ) +void destroyAllWindowsImpl( void ) { - //cout << "cvDestroyAllWindows" << endl; + //cout << "destroyAllWindowsImpl" << endl; NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; NSDictionary* list = [NSDictionary dictionaryWithDictionary:windows]; for(NSString *key in list) { - cvDestroyWindow([key cStringUsingEncoding:NSASCIIStringEncoding]); + destroyWindowImpl([key cStringUsingEncoding:NSASCIIStringEncoding]); } [localpool drain]; } -CV_IMPL void cvShowImage( const char* name, const CvArr* arr) +void showImageImpl( const char* name, const CvArr* arr) { - //cout << "cvShowImage" << endl; + //cout << "showImageImpl" << endl; NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; CVWindow *window = cvGetWindow(name); if(!window) { - cvNamedWindow(name, CV_WINDOW_AUTOSIZE); + namedWindowImpl(name, cv::WINDOW_AUTOSIZE); window = cvGetWindow(name); } @@ -276,10 +265,10 @@ CV_IMPL void cvShowImage( const char* name, const CvArr* arr) [localpool drain]; } -CV_IMPL void cvResizeWindow( const char* name, int width, int height) +void resizeWindowImpl( const char* name, int width, int height) { - //cout << "cvResizeWindow" << endl; + //cout << "resizeWindowImpl" << endl; NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; CVWindow *window = cvGetWindow(name); if(window && ![window autosize]) { @@ -290,9 +279,9 @@ CV_IMPL void cvResizeWindow( const char* name, int width, int height) [localpool drain]; } -CV_IMPL void cvMoveWindow( const char* name, int x, int y) +void moveWindowImpl( const char* name, int x, int y) { - CV_FUNCNAME("cvMoveWindow"); + CV_FUNCNAME("moveWindowImpl"); __BEGIN__; NSAutoreleasePool* localpool1 = [[NSAutoreleasePool alloc] init]; @@ -300,7 +289,7 @@ CV_IMPL void cvMoveWindow( const char* name, int x, int y) if(name == NULL) CV_ERROR( CV_StsNullPtr, "NULL window name" ); - //cout << "cvMoveWindow"<< endl; + //cout << "moveWindowImpl"<< endl; window = cvGetWindow(name); if(window) { if([window firstContent]) { @@ -317,12 +306,12 @@ CV_IMPL void cvMoveWindow( const char* name, int x, int y) __END__; } -CV_IMPL int cvCreateTrackbar (const char* trackbar_name, +static int cocoa_CreateTrackbar (const char* trackbar_name, const char* window_name, int* val, int count, CvTrackbarCallback on_notify) { - CV_FUNCNAME("cvCreateTrackbar"); + CV_FUNCNAME("cocoa_CreateTrackbar"); int result = 0; @@ -336,7 +325,7 @@ CV_IMPL int cvCreateTrackbar (const char* trackbar_name, if(window_name == NULL) CV_ERROR( CV_StsNullPtr, "NULL window name" ); - //cout << "cvCreateTrackbar" << endl ; + //cout << "cocoa_CreateTrackbar" << endl ; window = cvGetWindow(window_name); if(window) { [window createSliderWithName:trackbar_name @@ -351,15 +340,15 @@ CV_IMPL int cvCreateTrackbar (const char* trackbar_name, } -CV_IMPL int cvCreateTrackbar2(const char* trackbar_name, +int createTrackbar2Impl(const char* trackbar_name, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify2, void* userdata) { - //cout <<"cvCreateTrackbar2" << endl; + //cout <<"createTrackbar2Impl" << endl; NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; - int res = cvCreateTrackbar(trackbar_name, window_name, val, count, NULL); + int res = cocoa_CreateTrackbar(trackbar_name, window_name, val, count, NULL); if(res) { CVWindow *window = cvGetWindow(window_name); if (window && [window respondsToSelector:@selector(sliders)]) { @@ -373,15 +362,14 @@ CV_IMPL int cvCreateTrackbar2(const char* trackbar_name, } -CV_IMPL void -cvSetMouseCallback( const char* name, CvMouseCallback function, void* info) +void setMouseCallbackImpl( const char* name, CvMouseCallback function, void* info) { - CV_FUNCNAME("cvSetMouseCallback"); + CV_FUNCNAME("setMouseCallbackImpl"); CVWindow *window = nil; NSAutoreleasePool* localpool3 = nil; __BEGIN__; - //cout << "cvSetMouseCallback" << endl; + //cout << "setMouseCallbackImpl" << endl; if (localpool3 != nil) [localpool3 drain]; localpool3 = [[NSAutoreleasePool alloc] init]; @@ -399,16 +387,16 @@ cvSetMouseCallback( const char* name, CvMouseCallback function, void* info) __END__; } - CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name ) + int getTrackbarPosImpl( const char* trackbar_name, const char* window_name ) { - CV_FUNCNAME("cvGetTrackbarPos"); + CV_FUNCNAME("getTrackbarPosImpl"); CVWindow *window = nil; int pos = -1; NSAutoreleasePool* localpool4 = nil; __BEGIN__; - //cout << "cvGetTrackbarPos" << endl; + //cout << "getTrackbarPosImpl" << endl; if(trackbar_name == NULL || window_name == NULL) CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" ); @@ -427,16 +415,16 @@ cvSetMouseCallback( const char* name, CvMouseCallback function, void* info) return pos; } -CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos) +void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int pos) { - CV_FUNCNAME("cvSetTrackbarPos"); + CV_FUNCNAME("setTrackbarPosImpl"); CVWindow *window = nil; CVSlider *slider = nil; NSAutoreleasePool* localpool5 = nil; __BEGIN__; - //cout << "cvSetTrackbarPos" << endl; + //cout << "setTrackbarPosImpl" << endl; if(trackbar_name == NULL || window_name == NULL) CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" ); @@ -458,16 +446,16 @@ CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name __END__; } -CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval) +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval) { - CV_FUNCNAME("cvSetTrackbarMax"); + CV_FUNCNAME("setTrackbarMaxImpl"); CVWindow *window = nil; CVSlider *slider = nil; NSAutoreleasePool* localpool5 = nil; __BEGIN__; - //cout << "cvSetTrackbarPos" << endl; + //cout << "setTrackbarPosImpl" << endl; if(trackbar_name == NULL || window_name == NULL) CV_ERROR( CV_StsNullPtr, "NULL trackbar or window name" ); @@ -490,9 +478,9 @@ CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name __END__; } -CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval) +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval) { - CV_FUNCNAME("cvSetTrackbarMin"); + CV_FUNCNAME("setTrackbarMinImpl"); CVWindow *window = nil; CVSlider *slider = nil; @@ -521,38 +509,17 @@ CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name __END__; } -CV_IMPL void* cvGetWindowHandle( const char* name ) -{ - //cout << "cvGetWindowHandle" << endl; - return cvGetWindow(name); -} - - -CV_IMPL const char* cvGetWindowName( void* window_handle ) -{ - //cout << "cvGetWindowName" << endl; - NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; - for(NSString *key in windows) { - if([windows valueForKey:key] == window_handle) { - [localpool drain]; - return [key UTF8String]; - } - } - [localpool drain]; - return 0; -} - -CV_IMPL int cvNamedWindow( const char* name, int flags ) +int namedWindowImpl( const char* name, int flags ) { if( !wasInitialized ) - cvInitSystem(0, 0); + cocoa_InitSystem(0, 0); - //cout << "cvNamedWindow" << endl; + //cout << "namedWindowImpl" << endl; NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init]; CVWindow *window = cvGetWindow(name); if( window ) { - [window setAutosize:(flags == CV_WINDOW_AUTOSIZE)]; + [window setAutosize:(flags == cv::WINDOW_AUTOSIZE)]; [localpool drain]; return 0; } @@ -590,7 +557,7 @@ CV_IMPL int cvNamedWindow( const char* name, int flags ) [window setTitle:windowName]; [window makeKeyAndOrderFront:nil]; - [window setAutosize:(flags == CV_WINDOW_AUTOSIZE)]; + [window setAutosize:(flags == cv::WINDOW_AUTOSIZE)]; [windows setValue:window forKey:windowName]; @@ -598,9 +565,9 @@ CV_IMPL int cvNamedWindow( const char* name, int flags ) return [windows count]-1; } -CV_IMPL int cvWaitKey (int maxWait) +int waitKeyImpl (int maxWait) { - //cout << "cvWaitKey" << endl; + //cout << "waitKeyImpl" << endl; int returnCode = -1; NSAutoreleasePool *localpool = [[NSAutoreleasePool alloc] init]; double start = [[NSDate date] timeIntervalSince1970]; @@ -721,15 +688,15 @@ void cvSetModeWindow_COCOA( const char* name, double prop_value ) localpool = [[NSAutoreleasePool alloc] init]; fullscreenOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSFullScreenModeSetting]; - if ( [[window contentView] isInFullScreenMode] && prop_value==CV_WINDOW_NORMAL ) + if ( [[window contentView] isInFullScreenMode] && prop_value==cv::WINDOW_NORMAL ) { [[window contentView] exitFullScreenModeWithOptions:fullscreenOptions]; - window.status=CV_WINDOW_NORMAL; + window.status=cv::WINDOW_NORMAL; } - else if( ![[window contentView] isInFullScreenMode] && prop_value==CV_WINDOW_FULLSCREEN ) + else if( ![[window contentView] isInFullScreenMode] && prop_value==cv::WINDOW_FULLSCREEN ) { [[window contentView] enterFullScreenMode:[NSScreen mainScreen] withOptions:fullscreenOptions]; - window.status=CV_WINDOW_FULLSCREEN; + window.status=cv::WINDOW_FULLSCREEN; } [localpool drain]; @@ -879,20 +846,20 @@ static NSSize constrainAspectRatio(NSSize base, NSSize constraint) { return; int flags = 0; - if([event modifierFlags] & NSShiftKeyMask) flags |= CV_EVENT_FLAG_SHIFTKEY; - if([event modifierFlags] & NSControlKeyMask) flags |= CV_EVENT_FLAG_CTRLKEY; - if([event modifierFlags] & NSAlternateKeyMask) flags |= CV_EVENT_FLAG_ALTKEY; + if([event modifierFlags] & NSShiftKeyMask) flags |= cv::EVENT_FLAG_SHIFTKEY; + if([event modifierFlags] & NSControlKeyMask) flags |= cv::EVENT_FLAG_CTRLKEY; + if([event modifierFlags] & NSAlternateKeyMask) flags |= cv::EVENT_FLAG_ALTKEY; - if([event type] == NSLeftMouseDown) {[self cvSendMouseEvent:event type:CV_EVENT_LBUTTONDOWN flags:flags | CV_EVENT_FLAG_LBUTTON];} - if([event type] == NSLeftMouseUp) {[self cvSendMouseEvent:event type:CV_EVENT_LBUTTONUP flags:flags | CV_EVENT_FLAG_LBUTTON];} - if([event type] == NSRightMouseDown){[self cvSendMouseEvent:event type:CV_EVENT_RBUTTONDOWN flags:flags | CV_EVENT_FLAG_RBUTTON];} - if([event type] == NSRightMouseUp) {[self cvSendMouseEvent:event type:CV_EVENT_RBUTTONUP flags:flags | CV_EVENT_FLAG_RBUTTON];} - if([event type] == NSOtherMouseDown){[self cvSendMouseEvent:event type:CV_EVENT_MBUTTONDOWN flags:flags];} - if([event type] == NSOtherMouseUp) {[self cvSendMouseEvent:event type:CV_EVENT_MBUTTONUP flags:flags];} - if([event type] == NSMouseMoved) {[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE flags:flags];} - if([event type] == NSLeftMouseDragged) {[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE flags:flags | CV_EVENT_FLAG_LBUTTON];} - if([event type] == NSRightMouseDragged) {[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE flags:flags | CV_EVENT_FLAG_RBUTTON];} - if([event type] == NSOtherMouseDragged) {[self cvSendMouseEvent:event type:CV_EVENT_MOUSEMOVE flags:flags | CV_EVENT_FLAG_MBUTTON];} + if([event type] == NSLeftMouseDown) {[self cvSendMouseEvent:event type:cv::EVENT_LBUTTONDOWN flags:flags | cv::EVENT_FLAG_LBUTTON];} + if([event type] == NSLeftMouseUp) {[self cvSendMouseEvent:event type:cv::EVENT_LBUTTONUP flags:flags | cv::EVENT_FLAG_LBUTTON];} + if([event type] == NSRightMouseDown){[self cvSendMouseEvent:event type:cv::EVENT_RBUTTONDOWN flags:flags | cv::EVENT_FLAG_RBUTTON];} + if([event type] == NSRightMouseUp) {[self cvSendMouseEvent:event type:cv::EVENT_RBUTTONUP flags:flags | cv::EVENT_FLAG_RBUTTON];} + if([event type] == NSOtherMouseDown){[self cvSendMouseEvent:event type:cv::EVENT_MBUTTONDOWN flags:flags];} + if([event type] == NSOtherMouseUp) {[self cvSendMouseEvent:event type:cv::EVENT_MBUTTONUP flags:flags];} + if([event type] == NSMouseMoved) {[self cvSendMouseEvent:event type:cv::EVENT_MOUSEMOVE flags:flags];} + if([event type] == NSLeftMouseDragged) {[self cvSendMouseEvent:event type:cv::EVENT_MOUSEMOVE flags:flags | cv::EVENT_FLAG_LBUTTON];} + if([event type] == NSRightMouseDragged) {[self cvSendMouseEvent:event type:cv::EVENT_MOUSEMOVE flags:flags | cv::EVENT_FLAG_RBUTTON];} + if([event type] == NSOtherMouseDragged) {[self cvSendMouseEvent:event type:cv::EVENT_MOUSEMOVE flags:flags | cv::EVENT_FLAG_MBUTTON];} } - (void)keyDown:(NSEvent *)theEvent { //cout << "keyDown" << endl; diff --git a/modules/highgui/src/window_gtk.cpp b/modules/highgui/src/window_gtk.cpp index 98698cbade..bb2dc0555c 100644 --- a/modules/highgui/src/window_gtk.cpp +++ b/modules/highgui/src/window_gtk.cpp @@ -71,6 +71,7 @@ #endif #include +#include "opencv2/core/utils/trace.hpp" #include "opencv2/imgproc.hpp" using namespace cv; @@ -150,7 +151,8 @@ void cvImageWidgetSetImage(CvImageWidget * widget, const CvArr *arr) CV_Assert(origin == 0); convertToShow(cv::cvarrToMat(arr), widget->original_image); if(widget->scaled_image){ - cvResize( widget->original_image, widget->scaled_image, CV_INTER_AREA ); + cv::Mat dst = cv::cvarrToMat(widget->scaled_image); + cv::resize(cv::cvarrToMat(widget->original_image), dst, dst.size(), 0, 0, cv::INTER_AREA ); } // window does not refresh without this @@ -268,7 +270,7 @@ cvImageWidget_get_preferred_width (GtkWidget *widget, gint *minimal_width, gint CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget ); if(image_widget->original_image != NULL) { - *minimal_width = (image_widget->flags & CV_WINDOW_AUTOSIZE) != CV_WINDOW_AUTOSIZE ? + *minimal_width = (image_widget->flags & cv::WINDOW_AUTOSIZE) != cv::WINDOW_AUTOSIZE ? gdk_window_get_width(gtk_widget_get_window(widget)) : image_widget->original_image->cols; } else { @@ -292,7 +294,7 @@ cvImageWidget_get_preferred_height (GtkWidget *widget, gint *minimal_height, gin CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget ); if(image_widget->original_image != NULL) { - *minimal_height = (image_widget->flags & CV_WINDOW_AUTOSIZE) != CV_WINDOW_AUTOSIZE ? + *minimal_height = (image_widget->flags & cv::WINDOW_AUTOSIZE) != cv::WINDOW_AUTOSIZE ? gdk_window_get_height(gtk_widget_get_window(widget)) : image_widget->original_image->rows; } else { @@ -316,9 +318,9 @@ cvImageWidget_size_request (GtkWidget *widget, CvImageWidget * image_widget = CV_IMAGE_WIDGET( widget ); //printf("cvImageWidget_size_request "); - // the case the first time cvShowImage called or when AUTOSIZE + // the case the first time showImageImpl called or when AUTOSIZE if( image_widget->original_image && - ((image_widget->flags & CV_WINDOW_AUTOSIZE) || + ((image_widget->flags & cv::WINDOW_AUTOSIZE) || (image_widget->flags & CV_WINDOW_NO_IMAGE))) { //printf("original "); @@ -331,7 +333,7 @@ cvImageWidget_size_request (GtkWidget *widget, requisition->width = image_widget->scaled_image->cols; requisition->height = image_widget->scaled_image->rows; } - // the case before cvShowImage called + // the case before showImageImpl called else{ //printf("default "); requisition->width = 320; @@ -347,7 +349,7 @@ static void cvImageWidget_set_size(GtkWidget * widget, int max_width, int max_he //printf("cvImageWidget_set_size %d %d\n", max_width, max_height); // don't allow to set the size - if(image_widget->flags & CV_WINDOW_AUTOSIZE) return; + if(image_widget->flags & cv::WINDOW_AUTOSIZE) return; if(!image_widget->original_image) return; CvSize scaled_image_size = cvImageWidget_calc_size( image_widget->original_image->cols, @@ -386,7 +388,7 @@ cvImageWidget_size_allocate (GtkWidget *widget, image_widget = CV_IMAGE_WIDGET (widget); - if( (image_widget->flags & CV_WINDOW_AUTOSIZE)==0 && image_widget->original_image ){ + if( (image_widget->flags & cv::WINDOW_AUTOSIZE)==0 && image_widget->original_image ){ // (re) allocated scaled image if( image_widget->flags & CV_WINDOW_NO_IMAGE ){ cvImageWidget_set_size( widget, image_widget->original_image->cols, @@ -395,7 +397,10 @@ cvImageWidget_size_allocate (GtkWidget *widget, else{ cvImageWidget_set_size( widget, allocation->width, allocation->height ); } - cvResize( image_widget->original_image, image_widget->scaled_image, CV_INTER_AREA ); + { + cv::Mat dst = cv::cvarrToMat(image_widget->scaled_image); + cv::resize( cv::cvarrToMat(image_widget->original_image), dst, dst.size(), 0, 0, cv::INTER_AREA ); + } } if (gtk_widget_get_realized (widget)) @@ -403,7 +408,7 @@ cvImageWidget_size_allocate (GtkWidget *widget, image_widget = CV_IMAGE_WIDGET (widget); if( image_widget->original_image && - ((image_widget->flags & CV_WINDOW_AUTOSIZE) || + ((image_widget->flags & cv::WINDOW_AUTOSIZE) || (image_widget->flags & CV_WINDOW_NO_IMAGE)) ) { #if defined (GTK_VERSION3) @@ -620,7 +625,7 @@ std::vector< std::shared_ptr >& getGTKWindows() return g_windows; } -CV_IMPL int cvInitSystem( int argc, char** argv ) +static int gtk_InitSystem( int argc, char** argv ) { static int wasInitialized = 0; static bool hasError = false; @@ -654,9 +659,10 @@ CV_IMPL int cvInitSystem( int argc, char** argv ) return 0; } -CV_IMPL int cvStartWindowThread(){ +int cv::startWindowThread(){ + CV_TRACE_FUNCTION(); #ifdef HAVE_GTHREAD - cvInitSystem(0,NULL); + gtk_InitSystem(0,NULL); if (!thread_started) { #if !GLIB_CHECK_VERSION(2, 32, 0) // https://github.com/GNOME/glib/blame/b4d58a7105bb9d75907233968bb534b38f9a6e43/glib/deprecated/gthread.h#L274 @@ -733,19 +739,6 @@ std::shared_ptr icvFindWindowByName(const char* name) return icvFindWindowByName(std::string(name)); } - -static CvWindow* icvWindowByWidget( GtkWidget* widget ) -{ - auto& g_windows = getGTKWindows(); - for (size_t i = 0; i < g_windows.size(); ++i) - { - CvWindow* window = g_windows[i].get(); - if (window->widget == widget || window->frame == widget || window->paned == widget) - return window; - } - return NULL; -} - static Rect getImageRect_(const std::shared_ptr& window); CvRect cvGetWindowRect_GTK(const char* name) @@ -824,7 +817,7 @@ void cvSetModeWindow_GTK( const char* name, double prop_value)//Yannick Verdie static bool setModeWindow_(const std::shared_ptr& window, int mode) { - if (window->flags & CV_WINDOW_AUTOSIZE) //if the flag CV_WINDOW_AUTOSIZE is set + if (window->flags & cv::WINDOW_AUTOSIZE) //if the flag cv::WINDOW_AUTOSIZE is set return false; //so easy to do fullscreen here, Linux rocks ! @@ -832,17 +825,17 @@ static bool setModeWindow_(const std::shared_ptr& window, int mode) if (window->status == mode) return true; - if (window->status==CV_WINDOW_FULLSCREEN && mode==CV_WINDOW_NORMAL) + if (window->status==cv::WINDOW_FULLSCREEN && mode==cv::WINDOW_NORMAL) { gtk_window_unfullscreen(GTK_WINDOW(window->frame)); - window->status=CV_WINDOW_NORMAL; + window->status=cv::WINDOW_NORMAL; return true; } - if (window->status==CV_WINDOW_NORMAL && mode==CV_WINDOW_FULLSCREEN) + if (window->status==cv::WINDOW_NORMAL && mode==cv::WINDOW_FULLSCREEN) { gtk_window_fullscreen(GTK_WINDOW(window->frame)); - window->status=CV_WINDOW_FULLSCREEN; + window->status=cv::WINDOW_FULLSCREEN; return true; } @@ -875,7 +868,7 @@ double cvGetPropWindowAutoSize_GTK(const char* name) if (!window) return -1; // keep silence here - double result = window->flags & CV_WINDOW_AUTOSIZE; + double result = window->flags & cv::WINDOW_AUTOSIZE; return result; } @@ -1098,9 +1091,10 @@ static gboolean cvImageWidget_expose(GtkWidget* widget, GdkEventExpose* event, g #endif //GTK_VERSION3 static std::shared_ptr namedWindow_(const std::string& name, int flags); -CV_IMPL int cvNamedWindow( const char* name, int flags ) + +int namedWindowImpl( const char* name, int flags ) { - cvInitSystem(name ? 1 : 0,(char**)&name); + gtk_InitSystem(name ? 1 : 0,(char**)&name); CV_Assert(name && "NULL name string"); CV_LOCK_MUTEX(); @@ -1116,12 +1110,12 @@ CV_IMPL int cvNamedWindow( const char* name, int flags ) static std::shared_ptr namedWindow_(const std::string& name, int flags) { - cvInitSystem(0, NULL); + gtk_InitSystem(0, NULL); auto window_ptr = std::make_shared(name); CvWindow* window = window_ptr.get(); window->flags = flags; - window->status = CV_WINDOW_NORMAL;//YV + window->status = cv::WINDOW_NORMAL;//YV window->frame = gtk_window_new( GTK_WINDOW_TOPLEVEL ); @@ -1133,10 +1127,10 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags gtk_widget_show( window->paned ); #ifndef HAVE_OPENGL - if (flags & CV_WINDOW_OPENGL) + if (flags & cv::WINDOW_OPENGL) CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" ); #else - if (flags & CV_WINDOW_OPENGL) + if (flags & cv::WINDOW_OPENGL) createGlContext(window); window->glDrawCallback = 0; @@ -1181,7 +1175,7 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags getGTKWindows().push_back(window_ptr); } - bool b_nautosize = ((flags & CV_WINDOW_AUTOSIZE) == 0); + bool b_nautosize = ((flags & cv::WINDOW_AUTOSIZE) == 0); gtk_window_set_resizable( GTK_WINDOW(window->frame), b_nautosize ); // allow window to be resized @@ -1195,7 +1189,7 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags #ifdef HAVE_OPENGL if (window->useGl) - cvSetOpenGlContext(name.c_str()); + setOpenGLContextImpl(name.c_str()); #endif return window_ptr; @@ -1204,7 +1198,7 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags #ifdef HAVE_OPENGL -CV_IMPL void cvSetOpenGlContext(const char* name) +void setOpenGLContextImpl(const char* name) { GdkGLContext* glcontext; GdkGLDrawable* gldrawable; @@ -1227,7 +1221,7 @@ CV_IMPL void cvSetOpenGlContext(const char* name) CV_Error( CV_OpenGlApiCallError, "Can't Activate The GL Rendering Context" ); } -CV_IMPL void cvUpdateWindow(const char* name) +void updateWindowImpl(const char* name) { CV_Assert(name && "NULL name string"); @@ -1241,7 +1235,7 @@ CV_IMPL void cvUpdateWindow(const char* name) gtk_widget_queue_draw( GTK_WIDGET(window->widget) ); } -CV_IMPL void cvSetOpenGlDrawCallback(const char* name, CvOpenGlDrawCallback callback, void* userdata) +void setOpenGLDrawCallbackImpl(const char* name, CvOpenGlDrawCallback callback, void* userdata) { CV_Assert(name && "NULL name string"); @@ -1283,7 +1277,7 @@ static void checkLastWindow() #ifdef HAVE_GTHREAD if( thread_started ) { - // send key press signal to jump out of any waiting cvWaitKey's + // send key press signal to jump out of any waiting waitKeyImpl's g_cond_broadcast( cond_have_key ); } else @@ -1324,7 +1318,7 @@ void icvDeleteWindow_( CvWindow* window ) checkLastWindow(); } -CV_IMPL void cvDestroyWindow( const char* name ) +void destroyWindowImpl( const char* name ) { CV_Assert(name && "NULL name string"); @@ -1347,8 +1341,7 @@ CV_IMPL void cvDestroyWindow( const char* name ) } -CV_IMPL void -cvDestroyAllWindows( void ) +void destroyAllWindowsImpl( void ) { CV_LOCK_MUTEX(); @@ -1368,8 +1361,7 @@ cvDestroyAllWindows( void ) // return window_size; // } -CV_IMPL void -cvShowImage( const char* name, const CvArr* arr ) +void showImageImpl( const char* name, const CvArr* arr ) { CV_Assert(name && "NULL name string"); @@ -1378,7 +1370,7 @@ cvShowImage( const char* name, const CvArr* arr ) auto window = icvFindWindowByName(name); if(!window) { - cvNamedWindow(name, 1); + namedWindowImpl(name, 1); window = icvFindWindowByName(name); } CV_Assert(window); @@ -1399,7 +1391,7 @@ cvShowImage( const char* name, const CvArr* arr ) } static void resizeWindow_(const std::shared_ptr& window, int width, int height); -CV_IMPL void cvResizeWindow(const char* name, int width, int height ) +void resizeWindowImpl(const char* name, int width, int height ) { CV_Assert(name && "NULL name string"); @@ -1417,7 +1409,7 @@ void resizeWindow_(const std::shared_ptr& window, int width, int heigh { CV_Assert(window); CvImageWidget* image_widget = CV_IMAGE_WIDGET( window->widget ); - //if(image_widget->flags & CV_WINDOW_AUTOSIZE) + //if(image_widget->flags & cv::WINDOW_AUTOSIZE) //EXIT; gtk_window_set_resizable( GTK_WINDOW(window->frame), 1 ); @@ -1429,7 +1421,7 @@ void resizeWindow_(const std::shared_ptr& window, int width, int heigh } -CV_IMPL void cvMoveWindow( const char* name, int x, int y ) +void moveWindowImpl( const char* name, int x, int y ) { CV_Assert(name && "NULL name string"); @@ -1528,16 +1520,7 @@ icvCreateTrackbar( const char* trackbar_name, const char* window_name, return 1; } -CV_IMPL int -cvCreateTrackbar( const char* trackbar_name, const char* window_name, - int* val, int count, CvTrackbarCallback on_notify ) -{ - return icvCreateTrackbar(trackbar_name, window_name, val, count, - on_notify, 0, 0); -} - -CV_IMPL int -cvCreateTrackbar2( const char* trackbar_name, const char* window_name, +int createTrackbar2Impl( const char* trackbar_name, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify2, void* userdata ) { @@ -1592,8 +1575,7 @@ std::shared_ptr createTrackbar_( } -CV_IMPL void -cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param ) +void setMouseCallbackImpl( const char* window_name, CvMouseCallback on_mouse, void* param ) { CV_Assert(window_name && "NULL window name"); @@ -1608,7 +1590,7 @@ cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* par } -CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name ) +int getTrackbarPosImpl( const char* trackbar_name, const char* window_name ) { CV_Assert(window_name && "NULL window name"); CV_Assert(trackbar_name && "NULL trackbar name"); @@ -1627,7 +1609,7 @@ CV_IMPL int cvGetTrackbarPos( const char* trackbar_name, const char* window_name } static void setTrackbarPos_(const std::shared_ptr& trackbar, int pos); -CV_IMPL void cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ) +void setTrackbarPosImpl( const char* trackbar_name, const char* window_name, int pos ) { CV_Assert(window_name && "NULL window name"); CV_Assert(trackbar_name && "NULL trackbar name"); @@ -1659,7 +1641,7 @@ static void setTrackbarPos_(const std::shared_ptr& trackbar, int pos } -CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval) +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval) { CV_Assert(window_name && "NULL window name"); CV_Assert(trackbar_name && "NULL trackbar name"); @@ -1680,7 +1662,7 @@ CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name } -CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval) +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval) { CV_Assert(window_name && "NULL window name"); CV_Assert(trackbar_name && "NULL trackbar name"); @@ -1700,34 +1682,6 @@ CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name gtk_range_set_range(GTK_RANGE(trackbar->widget), trackbar->minval, trackbar->maxval); } - -CV_IMPL void* cvGetWindowHandle( const char* window_name ) -{ - CV_Assert(window_name && "NULL window name"); - - CV_LOCK_MUTEX(); - - const auto window = icvFindWindowByName(window_name); - if(!window) - return NULL; - - return (void*)window->widget; -} - - -CV_IMPL const char* cvGetWindowName( void* window_handle ) -{ - CV_Assert(window_handle && "NULL window handle"); - - CV_LOCK_MUTEX(); - - CvWindow* window = icvWindowByWidget( (GtkWidget*)window_handle ); - if (window) - return window->name.c_str(); - - return ""; // FIXME: NULL? -} - static GtkFileFilter* icvMakeGtkFilter(const char* name, const char* patterns, GtkFileFilter* images) { GtkFileFilter* filter = gtk_file_filter_new(); @@ -1930,7 +1884,7 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da { GdkEventMotion* event_motion = (GdkEventMotion*)event; - cv_event = CV_EVENT_MOUSEMOVE; + cv_event = cv::EVENT_MOUSEMOVE; pt32f.x = cvFloor(event_motion->x); pt32f.y = cvFloor(event_motion->y); state = event_motion->state; @@ -1946,21 +1900,21 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da if( event_button->type == GDK_BUTTON_PRESS ) { - cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONDOWN : - event_button->button == 2 ? CV_EVENT_MBUTTONDOWN : - event_button->button == 3 ? CV_EVENT_RBUTTONDOWN : 0; + cv_event = event_button->button == 1 ? cv::EVENT_LBUTTONDOWN : + event_button->button == 2 ? cv::EVENT_MBUTTONDOWN : + event_button->button == 3 ? cv::EVENT_RBUTTONDOWN : 0; } else if( event_button->type == GDK_BUTTON_RELEASE ) { - cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONUP : - event_button->button == 2 ? CV_EVENT_MBUTTONUP : - event_button->button == 3 ? CV_EVENT_RBUTTONUP : 0; + cv_event = event_button->button == 1 ? cv::EVENT_LBUTTONUP : + event_button->button == 2 ? cv::EVENT_MBUTTONUP : + event_button->button == 3 ? cv::EVENT_RBUTTONUP : 0; } else if( event_button->type == GDK_2BUTTON_PRESS ) { - cv_event = event_button->button == 1 ? CV_EVENT_LBUTTONDBLCLK : - event_button->button == 2 ? CV_EVENT_MBUTTONDBLCLK : - event_button->button == 3 ? CV_EVENT_RBUTTONDBLCLK : 0; + cv_event = event_button->button == 1 ? cv::EVENT_LBUTTONDBLCLK : + event_button->button == 2 ? cv::EVENT_MBUTTONDBLCLK : + event_button->button == 3 ? cv::EVENT_RBUTTONDBLCLK : 0; } state = event_button->state; } @@ -1973,9 +1927,9 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da #if defined(GTK_VERSION3_4) // NOTE: in current implementation doesn't possible to put into callback function delta_x and delta_y separately double delta = (event->scroll.delta_x + event->scroll.delta_y); - cv_event = (event->scroll.delta_x==0) ? CV_EVENT_MOUSEWHEEL : CV_EVENT_MOUSEHWHEEL; + cv_event = (event->scroll.delta_x==0) ? cv::EVENT_MOUSEWHEEL : cv::EVENT_MOUSEHWHEEL; #else - cv_event = CV_EVENT_MOUSEWHEEL; + cv_event = cv::EVENT_MOUSEWHEEL; #endif //GTK_VERSION3_4 state = event->scroll.state; @@ -1985,11 +1939,11 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da case GDK_SCROLL_SMOOTH: flags |= (((int)delta << 16)); break; #endif //GTK_VERSION3_4 - case GDK_SCROLL_LEFT: cv_event = CV_EVENT_MOUSEHWHEEL; + case GDK_SCROLL_LEFT: cv_event = cv::EVENT_MOUSEHWHEEL; /* FALLTHRU */ case GDK_SCROLL_UP: flags |= ~0xffff; break; - case GDK_SCROLL_RIGHT: cv_event = CV_EVENT_MOUSEHWHEEL; + case GDK_SCROLL_RIGHT: cv_event = cv::EVENT_MOUSEHWHEEL; /* FALLTHRU */ case GDK_SCROLL_DOWN: flags |= (((int)1 << 16)); break; @@ -2000,7 +1954,7 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da if( cv_event >= 0 ) { // scale point if image is scaled - if( (image_widget->flags & CV_WINDOW_AUTOSIZE)==0 && + if( (image_widget->flags & cv::WINDOW_AUTOSIZE)==0 && image_widget->original_image && image_widget->scaled_image ) { @@ -2029,16 +1983,16 @@ static gboolean icvOnMouse( GtkWidget *widget, GdkEvent *event, gpointer user_da { // handle non-keyboard (mouse) modifiers first flags |= - BIT_MAP(state, GDK_BUTTON1_MASK, CV_EVENT_FLAG_LBUTTON) | - BIT_MAP(state, GDK_BUTTON2_MASK, CV_EVENT_FLAG_MBUTTON) | - BIT_MAP(state, GDK_BUTTON3_MASK, CV_EVENT_FLAG_RBUTTON); + BIT_MAP(state, GDK_BUTTON1_MASK, cv::EVENT_FLAG_LBUTTON) | + BIT_MAP(state, GDK_BUTTON2_MASK, cv::EVENT_FLAG_MBUTTON) | + BIT_MAP(state, GDK_BUTTON3_MASK, cv::EVENT_FLAG_RBUTTON); // keyboard modifiers state &= gtk_accelerator_get_default_mod_mask(); flags |= - BIT_MAP(state, GDK_SHIFT_MASK, CV_EVENT_FLAG_SHIFTKEY) | - BIT_MAP(state, GDK_CONTROL_MASK, CV_EVENT_FLAG_CTRLKEY) | - BIT_MAP(state, GDK_MOD1_MASK, CV_EVENT_FLAG_ALTKEY) | - BIT_MAP(state, GDK_MOD2_MASK, CV_EVENT_FLAG_ALTKEY); + BIT_MAP(state, GDK_SHIFT_MASK, cv::EVENT_FLAG_SHIFTKEY) | + BIT_MAP(state, GDK_CONTROL_MASK, cv::EVENT_FLAG_CTRLKEY) | + BIT_MAP(state, GDK_MOD1_MASK, cv::EVENT_FLAG_ALTKEY) | + BIT_MAP(state, GDK_MOD2_MASK, cv::EVENT_FLAG_ALTKEY); window->on_mouse( cv_event, pt.x, pt.y, flags, window->on_mouse_param ); } } @@ -2054,7 +2008,7 @@ static gboolean icvAlarm( gpointer user_data ) } -CV_IMPL int cvWaitKey( int delay ) +int waitKeyImpl( int delay ) { #ifdef HAVE_GTHREAD if (thread_started && g_thread_self() != window_thread) @@ -2166,20 +2120,19 @@ public: { auto window = window_.lock(); CV_Assert(window); - // see cvGetWindowProperty switch (prop) { - case CV_WND_PROP_FULLSCREEN: + case cv::WND_PROP_FULLSCREEN: return (double)window->status; - case CV_WND_PROP_AUTOSIZE: - return (window->flags & CV_WINDOW_AUTOSIZE) ? 1.0 : 0.0; + case cv::WND_PROP_AUTOSIZE: + return (window->flags & cv::WINDOW_AUTOSIZE) ? 1.0 : 0.0; - case CV_WND_PROP_ASPECTRATIO: + case cv::WND_PROP_ASPECT_RATIO: return getRatioWindow_(window); #ifdef HAVE_OPENGL - case CV_WND_PROP_OPENGL: + case cv::WND_PROP_OPENGL: return window->useGl ? 1.0 : 0.0; #endif @@ -2193,11 +2146,10 @@ public: { auto window = window_.lock(); CV_Assert(window); - // see cvSetWindowProperty switch (prop) { - case CV_WND_PROP_FULLSCREEN: - if (value != CV_WINDOW_NORMAL && value != CV_WINDOW_FULLSCREEN) // bad arg + case cv::WND_PROP_FULLSCREEN: + if (value != cv::WINDOW_NORMAL && value != cv::WINDOW_FULLSCREEN) // bad arg break; setModeWindow_(window, value); return true; @@ -2352,7 +2304,7 @@ public: void destroyAllWindows() CV_OVERRIDE { - cvDestroyAllWindows(); + destroyAllWindowsImpl(); } // namedWindow @@ -2369,11 +2321,11 @@ public: int waitKeyEx(int delay) CV_OVERRIDE { - return cvWaitKey(delay); + return waitKeyImpl(delay); } int pollKey() CV_OVERRIDE { - return cvWaitKey(1); // TODO + return waitKeyImpl(1); // TODO } }; // GTKBackendUI diff --git a/modules/highgui/src/window_w32.cpp b/modules/highgui/src/window_w32.cpp index 42b0892c1b..1468227283 100644 --- a/modules/highgui/src/window_w32.cpp +++ b/modules/highgui/src/window_w32.cpp @@ -309,12 +309,12 @@ static const char* const mainHighGUIclassName = "Main HighGUI class"; static void icvCleanupHighgui() { - cvDestroyAllWindows(); + destroyAllWindowsImpl(); UnregisterClass(highGUIclassName, hg_hinstance); UnregisterClass(mainHighGUIclassName, hg_hinstance); } -CV_IMPL int cvInitSystem(int, char**) +static int win32_InitSystem(int, char**) { static int wasInitialized = 0; @@ -355,11 +355,6 @@ CV_IMPL int cvInitSystem(int, char**) return 0; } -CV_IMPL int cvStartWindowThread(){ - return 0; -} - - static std::shared_ptr icvWindowByHWND(HWND hwnd) { AutoLock lock(getWindowMutex()); @@ -587,7 +582,7 @@ void cvSetModeWindow_W32(const char* name, double prop_value)//Yannick Verdie static bool setModeWindow_(CvWindow& window, int mode) { - if (window.flags & CV_WINDOW_AUTOSIZE)//if the flag CV_WINDOW_AUTOSIZE is set + if (window.flags & cv::WINDOW_AUTOSIZE)//if the flag cv::WINDOW_AUTOSIZE is set return false; if (window.status == mode) @@ -597,18 +592,18 @@ static bool setModeWindow_(CvWindow& window, int mode) DWORD dwStyle = (DWORD)GetWindowLongPtr(window.frame, GWL_STYLE); CvRect position; - if (window.status == CV_WINDOW_FULLSCREEN && mode == CV_WINDOW_NORMAL) + if (window.status == cv::WINDOW_FULLSCREEN && mode == cv::WINDOW_NORMAL) { icvLoadWindowPos(window.name.c_str(), position); SetWindowLongPtr(window.frame, GWL_STYLE, dwStyle | WS_CAPTION | WS_THICKFRAME); SetWindowPos(window.frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED); - window.status=CV_WINDOW_NORMAL; + window.status=cv::WINDOW_NORMAL; return true; } - if (window.status == CV_WINDOW_NORMAL && mode == CV_WINDOW_FULLSCREEN) + if (window.status == cv::WINDOW_NORMAL && mode == cv::WINDOW_FULLSCREEN) { //save dimension RECT rect = { 0 }; @@ -630,7 +625,7 @@ static bool setModeWindow_(CvWindow& window, int mode) SetWindowLongPtr(window.frame, GWL_STYLE, dwStyle & ~WS_CAPTION & ~WS_THICKFRAME); SetWindowPos(window.frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED); - window.status=CV_WINDOW_FULLSCREEN; + window.status=cv::WINDOW_FULLSCREEN; return true; } @@ -836,7 +831,7 @@ double cvGetPropWindowAutoSize_W32(const char* name) if (!window) CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name)); - result = window->flags & CV_WINDOW_AUTOSIZE; + result = window->flags & cv::WINDOW_AUTOSIZE; return result; } @@ -1018,9 +1013,9 @@ namespace static std::shared_ptr namedWindow_(const std::string& name, int flags); -CV_IMPL int cvNamedWindow(const char* name, int flags) +int namedWindowImpl(const char* name, int flags) { - CV_FUNCNAME("cvNamedWindow"); + CV_FUNCNAME("namedWindowImpl"); AutoLock lock(getWindowMutex()); @@ -1042,7 +1037,7 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags { AutoLock lock(getWindowMutex()); - cvInitSystem(0,0); + win32_InitSystem(0,0); HWND hWnd, mainhWnd; DWORD defStyle = WS_VISIBLE | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU; @@ -1055,11 +1050,11 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags CvRect rect; icvLoadWindowPos(name.c_str(), rect); - if (!(flags & CV_WINDOW_AUTOSIZE))//YV add border in order to resize the window + if (!(flags & cv::WINDOW_AUTOSIZE))//YV add border in order to resize the window defStyle |= WS_SIZEBOX; #ifdef HAVE_OPENGL - if (flags & CV_WINDOW_OPENGL) + if (flags & cv::WINDOW_OPENGL) defStyle |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS; #endif @@ -1076,14 +1071,14 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags CV_Error(Error::StsError, "Frame window can not be created"); #ifndef HAVE_OPENGL - if (flags & CV_WINDOW_OPENGL) + if (flags & cv::WINDOW_OPENGL) CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support"); #else useGl = false; hGLDC = 0; hGLRC = 0; - if (flags & CV_WINDOW_OPENGL) + if (flags & cv::WINDOW_OPENGL) createGlContext(hWnd, hGLDC, hGLRC, useGl); #endif @@ -1117,7 +1112,7 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags #endif window->last_key = 0; - window->status = CV_WINDOW_NORMAL;//YV + window->status = cv::WINDOW_NORMAL;//YV window->on_mouse = 0; window->on_mouse_param = 0; @@ -1136,9 +1131,9 @@ static std::shared_ptr namedWindow_(const std::string& name, int flags #ifdef HAVE_OPENGL -CV_IMPL void cvSetOpenGlContext(const char* name) +void setOpenGLContextImpl(const char* name) { - CV_FUNCNAME("cvSetOpenGlContext"); + CV_FUNCNAME("setOpenGLContextImpl"); AutoLock lock(getWindowMutex()); @@ -1156,9 +1151,9 @@ CV_IMPL void cvSetOpenGlContext(const char* name) CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context"); } -CV_IMPL void cvUpdateWindow(const char* name) +void updateWindowImpl(const char* name) { - CV_FUNCNAME("cvUpdateWindow"); + CV_FUNCNAME("updateWindowImpl"); AutoLock lock(getWindowMutex()); @@ -1172,7 +1167,7 @@ CV_IMPL void cvUpdateWindow(const char* name) InvalidateRect(window->hwnd, 0, 0); } -CV_IMPL void cvSetOpenGlDrawCallback(const char* name, CvOpenGlDrawCallback callback, void* userdata) +void setOpenGLDrawCallbackImpl(const char* name, CvOpenGlDrawCallback callback, void* userdata) { CV_FUNCNAME("cvCreateOpenGLCallback"); @@ -1247,9 +1242,9 @@ static void icvRemoveWindow(const std::shared_ptr& window_) } -CV_IMPL void cvDestroyWindow(const char* name) +void destroyWindowImpl(const char* name) { - CV_FUNCNAME("cvDestroyWindow"); + CV_FUNCNAME("destroyWindowImpl"); AutoLock lock(getWindowMutex()); @@ -1338,7 +1333,7 @@ static void icvUpdateWindowPos(CvWindow& window) { RECT rect = { 0 }; - if ((window.flags & CV_WINDOW_AUTOSIZE) && window.image) + if ((window.flags & cv::WINDOW_AUTOSIZE) && window.image) { int i; SIZE size = {0,0}; @@ -1368,10 +1363,9 @@ static void icvUpdateWindowPos(CvWindow& window) static void showImage_(CvWindow& window, const Mat& image); -CV_IMPL void -cvShowImage(const char* name, const CvArr* arr) +void showImageImpl(const char* name, const CvArr* arr) { - CV_FUNCNAME("cvShowImage"); + CV_FUNCNAME("showImageImpl"); if (!name) CV_Error(Error::StsNullPtr, "NULL name"); @@ -1383,7 +1377,7 @@ cvShowImage(const char* name, const CvArr* arr) window = icvFindWindowByName(name); if (!window) { - cvNamedWindow(name, CV_WINDOW_AUTOSIZE); + namedWindowImpl(name, cv::WINDOW_AUTOSIZE); window = icvFindWindowByName(name); } } @@ -1459,9 +1453,9 @@ static void showImage_(CvWindow& window, const Mat& image) static void resizeWindow_(CvWindow& window, const Size& size); -CV_IMPL void cvResizeWindow(const char* name, int width, int height) +void resizeWindowImpl(const char* name, int width, int height) { - CV_FUNCNAME("cvResizeWindow"); + CV_FUNCNAME("resizeWindowImpl"); AutoLock lock(getWindowMutex()); @@ -1501,9 +1495,9 @@ static void resizeWindow_(CvWindow& window, const Size& size) static void moveWindow_(CvWindow& window, const Point& pt); -CV_IMPL void cvMoveWindow(const char* name, int x, int y) +void moveWindowImpl(const char* name, int x, int y) { - CV_FUNCNAME("cvMoveWindow"); + CV_FUNCNAME("moveWindowImpl"); AutoLock lock(getWindowMutex()); @@ -1548,7 +1542,7 @@ MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) break; case WM_GETMINMAXINFO: - if (!(window.flags & CV_WINDOW_AUTOSIZE)) + if (!(window.flags & cv::WINDOW_AUTOSIZE)) { MINMAXINFO* minmax = (MINMAXINFO*)lParam; RECT rect = { 0 }; @@ -1579,7 +1573,7 @@ MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) MoveWindow(window.toolbar.toolbar, 0, 0, pos->cx, rect.bottom - rect.top, TRUE); } - if (!(window.flags & CV_WINDOW_AUTOSIZE)) + if (!(window.flags & cv::WINDOW_AUTOSIZE)) icvUpdateWindowPos(window); break; @@ -1624,13 +1618,13 @@ MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_MOUSEHWHEEL: if (window.on_mouse) { - int flags = (wParam & MK_LBUTTON ? CV_EVENT_FLAG_LBUTTON : 0)| - (wParam & MK_RBUTTON ? CV_EVENT_FLAG_RBUTTON : 0)| - (wParam & MK_MBUTTON ? CV_EVENT_FLAG_MBUTTON : 0)| - (wParam & MK_CONTROL ? CV_EVENT_FLAG_CTRLKEY : 0)| - (wParam & MK_SHIFT ? CV_EVENT_FLAG_SHIFTKEY : 0)| - (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY : 0); - int event = (uMsg == WM_MOUSEWHEEL ? CV_EVENT_MOUSEWHEEL : CV_EVENT_MOUSEHWHEEL); + int flags = (wParam & MK_LBUTTON ? cv::EVENT_FLAG_LBUTTON : 0)| + (wParam & MK_RBUTTON ? cv::EVENT_FLAG_RBUTTON : 0)| + (wParam & MK_MBUTTON ? cv::EVENT_FLAG_MBUTTON : 0)| + (wParam & MK_CONTROL ? cv::EVENT_FLAG_CTRLKEY : 0)| + (wParam & MK_SHIFT ? cv::EVENT_FLAG_SHIFTKEY : 0)| + (GetKeyState(VK_MENU) < 0 ? cv::EVENT_FLAG_ALTKEY : 0); + int event = (uMsg == WM_MOUSEWHEEL ? cv::EVENT_MOUSEWHEEL : cv::EVENT_MOUSEHWHEEL); // Set the wheel delta of mouse wheel to be in the upper word of 'event' int delta = GET_WHEEL_DELTA_WPARAM(wParam); @@ -1822,22 +1816,22 @@ static LRESULT CALLBACK HighGUIProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM { POINT pt; - int flags = (wParam & MK_LBUTTON ? CV_EVENT_FLAG_LBUTTON : 0)| - (wParam & MK_RBUTTON ? CV_EVENT_FLAG_RBUTTON : 0)| - (wParam & MK_MBUTTON ? CV_EVENT_FLAG_MBUTTON : 0)| - (wParam & MK_CONTROL ? CV_EVENT_FLAG_CTRLKEY : 0)| - (wParam & MK_SHIFT ? CV_EVENT_FLAG_SHIFTKEY : 0)| - (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY : 0); - int event = uMsg == WM_LBUTTONDOWN ? CV_EVENT_LBUTTONDOWN : - uMsg == WM_RBUTTONDOWN ? CV_EVENT_RBUTTONDOWN : - uMsg == WM_MBUTTONDOWN ? CV_EVENT_MBUTTONDOWN : - uMsg == WM_LBUTTONUP ? CV_EVENT_LBUTTONUP : - uMsg == WM_RBUTTONUP ? CV_EVENT_RBUTTONUP : - uMsg == WM_MBUTTONUP ? CV_EVENT_MBUTTONUP : - uMsg == WM_LBUTTONDBLCLK ? CV_EVENT_LBUTTONDBLCLK : - uMsg == WM_RBUTTONDBLCLK ? CV_EVENT_RBUTTONDBLCLK : - uMsg == WM_MBUTTONDBLCLK ? CV_EVENT_MBUTTONDBLCLK : - CV_EVENT_MOUSEMOVE; + int flags = (wParam & MK_LBUTTON ? cv::EVENT_FLAG_LBUTTON : 0)| + (wParam & MK_RBUTTON ? cv::EVENT_FLAG_RBUTTON : 0)| + (wParam & MK_MBUTTON ? cv::EVENT_FLAG_MBUTTON : 0)| + (wParam & MK_CONTROL ? cv::EVENT_FLAG_CTRLKEY : 0)| + (wParam & MK_SHIFT ? cv::EVENT_FLAG_SHIFTKEY : 0)| + (GetKeyState(VK_MENU) < 0 ? cv::EVENT_FLAG_ALTKEY : 0); + int event = uMsg == WM_LBUTTONDOWN ? cv::EVENT_LBUTTONDOWN : + uMsg == WM_RBUTTONDOWN ? cv::EVENT_RBUTTONDOWN : + uMsg == WM_MBUTTONDOWN ? cv::EVENT_MBUTTONDOWN : + uMsg == WM_LBUTTONUP ? cv::EVENT_LBUTTONUP : + uMsg == WM_RBUTTONUP ? cv::EVENT_RBUTTONUP : + uMsg == WM_MBUTTONUP ? cv::EVENT_MBUTTONUP : + uMsg == WM_LBUTTONDBLCLK ? cv::EVENT_LBUTTONDBLCLK : + uMsg == WM_RBUTTONDBLCLK ? cv::EVENT_RBUTTONDBLCLK : + uMsg == WM_MBUTTONDBLCLK ? cv::EVENT_MBUTTONDBLCLK : + cv::EVENT_MOUSEMOVE; if (uMsg == WM_LBUTTONDOWN || uMsg == WM_RBUTTONDOWN || uMsg == WM_MBUTTONDOWN) SetCapture(hwnd); if (uMsg == WM_LBUTTONUP || uMsg == WM_RBUTTONUP || uMsg == WM_MBUTTONUP) @@ -1846,7 +1840,7 @@ static LRESULT CALLBACK HighGUIProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam); - if (window.flags & CV_WINDOW_AUTOSIZE) + if (window.flags & cv::WINDOW_AUTOSIZE) { // As user can't change window size, do not scale window coordinates. Underlying windowing system // may prevent full window from being displayed and in this case coordinates should not be scaled. @@ -1908,7 +1902,7 @@ static LRESULT CALLBACK HighGUIProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM SetDIBColorTable(window.dc, 0, 255, table); } - if (window.flags & CV_WINDOW_AUTOSIZE) + if (window.flags & cv::WINDOW_AUTOSIZE) { BitBlt(hdc, 0, 0, size.cx, size.cy, window.dc, 0, 0, SRCCOPY); } @@ -2097,8 +2091,7 @@ static LRESULT CALLBACK HGToolbarProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARA } -CV_IMPL void -cvDestroyAllWindows(void) +void destroyAllWindowsImpl(void) { std::vector< std::shared_ptr > g_windows; { @@ -2296,8 +2289,7 @@ int pollKey_W32() } } -CV_IMPL int -cvWaitKey(int delay) +int waitKeyImpl(int delay) { int64 time0 = cv::getTickCount(); int64 timeEnd = time0 + (int64)(delay * 0.001f * cv::getTickFrequency()); @@ -2537,16 +2529,7 @@ std::shared_ptr createTrackbar_(CvWindow& window, const std::string& return trackbar; } -CV_IMPL int -cvCreateTrackbar(const char* trackbar_name, const char* window_name, - int* val, int count, CvTrackbarCallback on_notify) -{ - return icvCreateTrackbar(trackbar_name, window_name, val, count, - on_notify, 0, 0); -} - -CV_IMPL int -cvCreateTrackbar2(const char* trackbar_name, const char* window_name, +int createTrackbar2Impl(const char* trackbar_name, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify2, void* userdata) { @@ -2554,10 +2537,9 @@ cvCreateTrackbar2(const char* trackbar_name, const char* window_name, 0, on_notify2, userdata); } -CV_IMPL void -cvSetMouseCallback(const char* name, CvMouseCallback on_mouse, void* param) +void setMouseCallbackImpl(const char* name, CvMouseCallback on_mouse, void* param) { - CV_FUNCNAME("cvSetMouseCallback"); + CV_FUNCNAME("setMouseCallbackImpl"); if (!name) CV_Error(Error::StsNullPtr, "NULL window name"); @@ -2573,9 +2555,9 @@ cvSetMouseCallback(const char* name, CvMouseCallback on_mouse, void* param) } -CV_IMPL int cvGetTrackbarPos(const char* trackbar_name, const char* window_name) +int getTrackbarPosImpl(const char* trackbar_name, const char* window_name) { - CV_FUNCNAME("cvGetTrackbarPos"); + CV_FUNCNAME("getTrackbarPosImpl"); AutoLock lock(getWindowMutex()); @@ -2594,9 +2576,9 @@ CV_IMPL int cvGetTrackbarPos(const char* trackbar_name, const char* window_name) } -CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos) +void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int pos) { - CV_FUNCNAME("cvSetTrackbarPos"); + CV_FUNCNAME("setTrackbarPosImpl"); AutoLock lock(getWindowMutex()); @@ -2624,9 +2606,9 @@ CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name } -CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval) +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval) { - CV_FUNCNAME("cvSetTrackbarMax"); + CV_FUNCNAME("setTrackbarMaxImpl"); if (trackbar_name == 0 || window_name == 0) { @@ -2653,9 +2635,9 @@ CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name } -CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval) +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval) { - CV_FUNCNAME("cvSetTrackbarMin"); + CV_FUNCNAME("setTrackbarMinImpl"); if (trackbar_name == 0 || window_name == 0) { @@ -2682,53 +2664,6 @@ CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name } -CV_IMPL void* cvGetWindowHandle(const char* window_name) -{ - CV_FUNCNAME("cvGetWindowHandle"); - - AutoLock lock(getWindowMutex()); - - if (window_name == 0) - CV_Error(Error::StsNullPtr, "NULL window name"); - - auto window = icvFindWindowByName(window_name); - if (!window) - CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name)); - - return (void*)window->hwnd; -} - -// FIXIT: result is not safe to use -CV_IMPL const char* cvGetWindowName(void* window_handle) -{ - CV_FUNCNAME("cvGetWindowName"); - - AutoLock lock(getWindowMutex()); - - if (window_handle == 0) - CV_Error(Error::StsNullPtr, "NULL window handle"); - - auto window = icvWindowByHWND((HWND)window_handle); - if (!window) - CV_Error_(Error::StsNullPtr, ("NULL window: '%p'", window_handle)); - - return window->name.c_str(); -} - - -CV_IMPL void -cvSetPreprocessFuncWin32_(const void* callback) -{ - hg_on_preprocess = (CvWin32WindowCallback)callback; -} - -CV_IMPL void -cvSetPostprocessFuncWin32_(const void* callback) -{ - hg_on_postprocess = (CvWin32WindowCallback)callback; -} - - namespace cv { namespace impl { @@ -2789,7 +2724,6 @@ public: auto window_ptr = window_.lock(); CV_Assert(window_ptr); CvWindow& window = *window_ptr; - // see cvGetWindowProperty switch ((WindowPropertyFlags)prop) { case WND_PROP_FULLSCREEN: @@ -2827,7 +2761,6 @@ public: auto window_ptr = window_.lock(); CV_Assert(window_ptr); CvWindow& window = *window_ptr; - // see cvSetWindowProperty switch ((WindowPropertyFlags)prop) { case WND_PROP_FULLSCREEN: @@ -3007,7 +2940,7 @@ public: void destroyAllWindows() CV_OVERRIDE { - cvDestroyAllWindows(); + destroyAllWindowsImpl(); } // namedWindow @@ -3024,7 +2957,7 @@ public: int waitKeyEx(int delay) CV_OVERRIDE { - return cvWaitKey(delay); + return waitKeyImpl(delay); } int pollKey() CV_OVERRIDE { diff --git a/modules/highgui/src/window_wayland.cpp b/modules/highgui/src/window_wayland.cpp index 69231c0072..a18ea6a72d 100644 --- a/modules/highgui/src/window_wayland.cpp +++ b/modules/highgui/src/window_wayland.cpp @@ -1442,18 +1442,18 @@ cv::Rect cv_wl_titlebar::draw(void *data, cv::Size const &size, bool force) { cv::putText( buf_, window_->get_title(), origin, title_.face, title_.scale, - CV_RGB(0xff, 0xff, 0xff), title_.thickness, CV_AA + CV_RGB(0xff, 0xff, 0xff), title_.thickness, cv::LINE_AA ); } buf_(cv::Rect(btn_min_.tl(), cv::Size(titlebar_min_width, size.height))) = bg_color_; - cv::line(buf_, btn_cls.tl(), btn_cls.br(), line_color_, 1, CV_AA); + cv::line(buf_, btn_cls.tl(), btn_cls.br(), line_color_, 1, cv::LINE_AA); cv::line(buf_, btn_cls.tl() + cv::Point(btn_cls.width, 0), btn_cls.br() - cv::Point(btn_cls.width, 0), - line_color_, 1, CV_AA); - cv::rectangle(buf_, btn_max.tl(), btn_max.br(), line_color_, 1, CV_AA); + line_color_, 1, cv::LINE_AA); + cv::rectangle(buf_, btn_max.tl(), btn_max.br(), line_color_, 1, cv::LINE_AA); cv::line(buf_, cv::Point(btn_min_.x + 8, btn_min_.height / 2), - cv::Point(btn_min_.x + btn_min_.width - 8, btn_min_.height / 2), line_color_, 1, CV_AA); - cv::line(buf_, cv::Point(0, 0), cv::Point(buf_.size().width, 0), border_color_, 1, CV_AA); + cv::Point(btn_min_.x + btn_min_.width - 8, btn_min_.height / 2), line_color_, 1, cv::LINE_AA); + cv::line(buf_, cv::Point(0, 0), cv::Point(buf_.size().width, 0), border_color_, 1, cv::LINE_AA); write_mat_to_xrgb8888(buf_, data); last_size_ = size; @@ -1475,7 +1475,7 @@ cv_wl_viewer::cv_wl_viewer(cv_wl_window *window, int flags) void cv_wl_viewer::set_image(cv::Mat const &image) { if (image.type() == CV_8UC1) { cv::Mat bgr; - cv::cvtColor(image, bgr, CV_GRAY2BGR); + cv::cvtColor(image, bgr, cv::COLOR_GRAY2BGR); image_ = bgr.clone(); } else { image_ = image.clone(); @@ -1509,7 +1509,7 @@ void cv_wl_viewer::get_preferred_height_for_width(int width, int &minimum, int & minimum = natural = image_.size().height; } else { natural = static_cast(width * aspect_ratio(image_.size())); - minimum = (flags_ & CV_WINDOW_FREERATIO ? 0 : natural); + minimum = (flags_ & cv::WINDOW_FREERATIO ? 0 : natural); } } @@ -1548,11 +1548,11 @@ cv::Rect cv_wl_viewer::draw(void *data, cv::Size const &size, bool force) { CV_Assert(image_.size() == size); write_mat_to_xrgb8888(image_, data); } else { - if (flags_ & CV_WINDOW_FREERATIO) { + if (flags_ & cv::WINDOW_FREERATIO) { cv::Mat resized; cv::resize(image_, resized, size); write_mat_to_xrgb8888(resized, data); - } else /* CV_WINDOW_KEEPRATIO */ { + } else /* cv::WINDOW_KEEPRATIO */ { auto rect = cv::Rect(cv::Point(0, 0), size); if (aspect_ratio(size) >= aspect_ratio(image_.size())) { rect.height = static_cast(image_.size().height * ((double) rect.width / image_.size().width)); @@ -1657,12 +1657,12 @@ cv::Rect cv_wl_trackbar::draw(void *data, cv::Size const &size, bool force) { data_, (name_ + ": " + std::to_string(slider_.value)), bar_.text_orig, bar_.fontface, bar_.fontscale, - CV_RGB(0x00, 0x00, 0x00), bar_.font_thickness, CV_AA); + CV_RGB(0x00, 0x00, 0x00), bar_.font_thickness, cv::LINE_AA); - cv::line(data_, bar_.left, bar_.right, color_.bg, bar_.thickness + 3, CV_AA); - cv::line(data_, bar_.left, bar_.right, color_.fg, bar_.thickness, CV_AA); - cv::circle(data_, slider_.pos, slider_.radius, color_.fg, -1, CV_AA); - cv::circle(data_, slider_.pos, slider_.radius, color_.bg, 1, CV_AA); + cv::line(data_, bar_.left, bar_.right, color_.bg, bar_.thickness + 3, cv::LINE_AA); + cv::line(data_, bar_.left, bar_.right, color_.fg, bar_.thickness, cv::LINE_AA); + cv::circle(data_, slider_.pos, slider_.radius, color_.fg, -1, cv::LINE_AA); + cv::circle(data_, slider_.pos, slider_.radius, color_.bg, 1, cv::LINE_AA); write_mat_to_xrgb8888(data_, data); damage = cv::Rect(cv::Point(0, 0), size); @@ -2310,57 +2310,33 @@ protected: std::shared_ptr CvWlCore::sInstance = nullptr; -CV_IMPL int cvStartWindowThread() { - return 0; -} - -CV_IMPL int cvNamedWindow(const char *name, int flags) { +int namedWindowImpl(const char *name, int flags) { return CvWlCore::getInstance().create_window(name, flags); } -CV_IMPL void cvDestroyWindow(const char *name) { +void destroyWindowImpl(const char *name) { CvWlCore::getInstance().destroy_window(name); } -CV_IMPL void cvDestroyAllWindows() { +void destroyAllWindowsImpl() { CvWlCore::getInstance().destroy_all_windows(); } -CV_IMPL void *cvGetWindowHandle(const char *name) { - return CvWlCore::getInstance().get_window_handle(name); -} - -CV_IMPL const char *cvGetWindowName(void *window_handle) { - return CvWlCore::getInstance().get_window_name(window_handle).c_str(); -} - -CV_IMPL void cvMoveWindow(const char *name, int x, int y) { +void moveWindowImpl(const char *name, int x, int y) { CV_UNUSED(name); CV_UNUSED(x); CV_UNUSED(y); CV_LOG_ONCE_WARNING(nullptr, "Function not implemented: User cannot move window surfaces in Wayland"); } -CV_IMPL void cvResizeWindow(const char *name, int width, int height) { +void resizeWindowImpl(const char *name, int width, int height) { if (auto window = CvWlCore::getInstance().get_window(name)) window->show(cv::Size(width, height)); else throw_system_error("Could not get window name", errno) } -CV_IMPL int cvCreateTrackbar(const char *name_bar, const char *window_name, int *value, int count, - CvTrackbarCallback on_change) { - CV_UNUSED(name_bar); - CV_UNUSED(window_name); - CV_UNUSED(value); - CV_UNUSED(count); - CV_UNUSED(on_change); - CV_LOG_ONCE_WARNING(nullptr, "Not implemented, use cvCreateTrackbar2"); - - return 0; -} - -CV_IMPL int cvCreateTrackbar2(const char *trackbar_name, const char *window_name, int *val, int count, +int createTrackbar2Impl(const char *trackbar_name, const char *window_name, int *val, int count, CvTrackbarCallback2 on_notify, void *userdata) { if (auto window = CvWlCore::getInstance().get_window(window_name)) window->create_trackbar(trackbar_name, val, count, on_notify, userdata); @@ -2368,7 +2344,7 @@ CV_IMPL int cvCreateTrackbar2(const char *trackbar_name, const char *window_name return 0; } -CV_IMPL int cvGetTrackbarPos(const char *trackbar_name, const char *window_name) { +int getTrackbarPosImpl(const char *trackbar_name, const char *window_name) { if (auto window = CvWlCore::getInstance().get_window(window_name)) { auto trackbar_ptr = window->get_trackbar(trackbar_name); if (auto trackbar = trackbar_ptr.lock()) @@ -2378,7 +2354,7 @@ CV_IMPL int cvGetTrackbarPos(const char *trackbar_name, const char *window_name) return -1; } -CV_IMPL void cvSetTrackbarPos(const char *trackbar_name, const char *window_name, int pos) { +void setTrackbarPosImpl(const char *trackbar_name, const char *window_name, int pos) { if (auto window = CvWlCore::getInstance().get_window(window_name)) { auto trackbar_ptr = window->get_trackbar(trackbar_name); if (auto trackbar = trackbar_ptr.lock()) @@ -2386,7 +2362,7 @@ CV_IMPL void cvSetTrackbarPos(const char *trackbar_name, const char *window_name } } -CV_IMPL void cvSetTrackbarMax(const char *trackbar_name, const char *window_name, int maxval) { +void setTrackbarMaxImpl(const char *trackbar_name, const char *window_name, int maxval) { if (auto window = CvWlCore::getInstance().get_window(window_name)) { auto trackbar_ptr = window->get_trackbar(trackbar_name); if (auto trackbar = trackbar_ptr.lock()) @@ -2394,18 +2370,18 @@ CV_IMPL void cvSetTrackbarMax(const char *trackbar_name, const char *window_name } } -CV_IMPL void cvSetTrackbarMin(const char *trackbar_name, const char *window_name, int minval) { +void setTrackbarMinImpl(const char *trackbar_name, const char *window_name, int minval) { CV_UNUSED(trackbar_name); CV_UNUSED(window_name); CV_UNUSED(minval); } -CV_IMPL void cvSetMouseCallback(const char *window_name, CvMouseCallback on_mouse, void *param) { +void setMouseCallbackImpl(const char *window_name, CvMouseCallback on_mouse, void *param) { if (auto window = CvWlCore::getInstance().get_window(window_name)) window->set_mouse_callback(on_mouse, param); } -CV_IMPL void cvShowImage(const char *name, const CvArr *arr) { +void showImageImpl(const char *name, const CvArr *arr) { auto cv_core = CvWlCore::getInstance(); auto window = cv_core.get_window(name); if (!window) { @@ -2423,7 +2399,7 @@ void setWindowTitle_WAYLAND(const cv::String &winname, const cv::String &title) window->set_title(title); } -CV_IMPL int cvWaitKey(int delay) { +int waitKeyImpl(int delay) { int key = -1; auto limit = ch::duration_cast(ch::milliseconds(delay)); auto start_time = ch::duration_cast( @@ -2462,13 +2438,13 @@ CV_IMPL int cvWaitKey(int delay) { } #ifdef HAVE_OPENGL -CV_IMPL void cvSetOpenGlDrawCallback(const char *, CvOpenGlDrawCallback, void *) { +void setOpenGLDrawCallbackImpl(const char *, CvOpenGlDrawCallback, void *) { } -CV_IMPL void cvSetOpenGlContext(const char *) { +void setOpenGLContextImpl(const char *) { } -CV_IMPL void cvUpdateWindow(const char *) { +void updateWindowImpl(const char *) { } #endif // HAVE_OPENGL diff --git a/modules/highgui/src/window_winrt.cpp b/modules/highgui/src/window_winrt.cpp index af771bd00b..ee9b3ae7a3 100644 --- a/modules/highgui/src/window_winrt.cpp +++ b/modules/highgui/src/window_winrt.cpp @@ -56,9 +56,9 @@ void cv::winrt_initContainer(::Windows::UI::Xaml::Controls::Panel^ _container) /********************************** API Implementation *********************************************************/ -CV_IMPL void cvShowImage(const char* name, const CvArr* arr) +void showImageImpl(const char* name, const CvArr* arr) { - CV_FUNCNAME("cvShowImage"); + CV_FUNCNAME("showImageImpl"); __BEGIN__; @@ -75,7 +75,7 @@ CV_IMPL void cvShowImage(const char* name, const CvArr* arr) CV_CALL(image = cvGetMat(arr, &stub)); //TODO: use approach from window_w32.cpp or cv::Mat(.., .., CV_8UC4) - // and cvtColor(.., .., CV_BGR2BGRA) to convert image here + // and cvtColor(.., .., cv::COLOR_BGR2BGRA) to convert image here // than beforehand. window->updateImage(image); @@ -84,9 +84,9 @@ CV_IMPL void cvShowImage(const char* name, const CvArr* arr) __END__; } -CV_IMPL int cvNamedWindow(const char* name, int flags) +int namedWindowImpl(const char* name, int flags) { - CV_FUNCNAME("cvNamedWindow"); + CV_FUNCNAME("namedWindowImpl"); if (!name) CV_ERROR(CV_StsNullPtr, "NULL name"); @@ -96,9 +96,9 @@ CV_IMPL int cvNamedWindow(const char* name, int flags) return CV_OK; } -CV_IMPL void cvDestroyWindow(const char* name) +void destroyWindowImpl(const char* name) { - CV_FUNCNAME("cvDestroyWindow"); + CV_FUNCNAME("destroyWindowImpl"); if (!name) CV_ERROR(CV_StsNullPtr, "NULL name string"); @@ -106,15 +106,15 @@ CV_IMPL void cvDestroyWindow(const char* name) HighguiBridge::getInstance().destroyWindow(name); } -CV_IMPL void cvDestroyAllWindows() +void destroyAllWindowsImpl() { HighguiBridge::getInstance().destroyAllWindows(); } -CV_IMPL int cvCreateTrackbar2(const char* trackbar_name, const char* window_name, +int createTrackbar2Impl(const char* trackbar_name, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata) { - CV_FUNCNAME("cvCreateTrackbar2"); + CV_FUNCNAME("createTrackbar2Impl"); int pos = 0; @@ -136,9 +136,9 @@ CV_IMPL int cvCreateTrackbar2(const char* trackbar_name, const char* window_name return CV_OK; } -CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos) +void setTrackbarPosImpl(const char* trackbar_name, const char* window_name, int pos) { - CV_FUNCNAME("cvSetTrackbarPos"); + CV_FUNCNAME("setTrackbarPosImpl"); CvTrackbar* trackbar = 0; @@ -153,9 +153,9 @@ CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name trackbar->setPosition(pos); } -CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval) +void setTrackbarMaxImpl(const char* trackbar_name, const char* window_name, int maxval) { - CV_FUNCNAME("cvSetTrackbarMax"); + CV_FUNCNAME("setTrackbarMaxImpl"); if (maxval >= 0) { @@ -169,9 +169,9 @@ CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name } } -CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval) +void setTrackbarMinImpl(const char* trackbar_name, const char* window_name, int minval) { - CV_FUNCNAME("cvSetTrackbarMin"); + CV_FUNCNAME("setTrackbarMinImpl"); if (minval >= 0) { @@ -185,11 +185,11 @@ CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name } } -CV_IMPL int cvGetTrackbarPos(const char* trackbar_name, const char* window_name) +int getTrackbarPosImpl(const char* trackbar_name, const char* window_name) { int pos = -1; - CV_FUNCNAME("cvGetTrackbarPos"); + CV_FUNCNAME("getTrackbarPosImpl"); if (trackbar_name == 0 || window_name == 0) CV_ERROR(CV_StsNullPtr, "NULL trackbar or window name"); @@ -204,9 +204,9 @@ CV_IMPL int cvGetTrackbarPos(const char* trackbar_name, const char* window_name) /********************************** Not YET implemented API ****************************************************/ -CV_IMPL int cvWaitKey(int delay) +int waitKeyImpl(int delay) { - CV_WINRT_NO_GUI_ERROR("cvWaitKey"); + CV_WINRT_NO_GUI_ERROR("waitKeyImpl"); // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724411(v=vs.85).aspx int time0 = GetTickCount64(); @@ -222,11 +222,11 @@ CV_IMPL int cvWaitKey(int delay) } } -CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param) +void setMouseCallbackImpl(const char* window_name, CvMouseCallback on_mouse, void* param) { - CV_WINRT_NO_GUI_ERROR("cvSetMouseCallback"); + CV_WINRT_NO_GUI_ERROR("setMouseCallbackImpl"); - CV_FUNCNAME("cvSetMouseCallback"); + CV_FUNCNAME("setMouseCallbackImpl"); if (!window_name) CV_ERROR(CV_StsNullPtr, "NULL window name"); @@ -240,32 +240,14 @@ CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mous /********************************** Disabled or not supported API **********************************************/ -CV_IMPL void cvMoveWindow(const char* name, int x, int y) +void moveWindowImpl(const char* name, int x, int y) { - CV_WINRT_NO_GUI_ERROR("cvMoveWindow"); + CV_WINRT_NO_GUI_ERROR("moveWindowImpl"); } -CV_IMPL void cvResizeWindow(const char* name, int width, int height) +void resizeWindowImpl(const char* name, int width, int height) { - CV_WINRT_NO_GUI_ERROR("cvResizeWindow"); -} - -CV_IMPL int cvInitSystem(int, char**) -{ - CV_WINRT_NO_GUI_ERROR("cvInitSystem"); - return CV_StsNotImplemented; -} - -CV_IMPL void* cvGetWindowHandle(const char*) -{ - CV_WINRT_NO_GUI_ERROR("cvGetWindowHandle"); - return (void*) CV_StsNotImplemented; -} - -CV_IMPL const char* cvGetWindowName(void*) -{ - CV_WINRT_NO_GUI_ERROR("cvGetWindowName"); - return (const char*) CV_StsNotImplemented; + CV_WINRT_NO_GUI_ERROR("resizeWindowImpl"); } void cvSetModeWindow_WinRT(const char* name, double prop_value) { @@ -276,8 +258,3 @@ double cvGetModeWindow_WinRT(const char* name) { CV_WINRT_NO_GUI_ERROR("cvGetModeWindow"); return CV_StsNotImplemented; } - -CV_IMPL int cvStartWindowThread() { - CV_WINRT_NO_GUI_ERROR("cvStartWindowThread"); - return CV_StsNotImplemented; -} diff --git a/modules/highgui/src/window_winrt_bridge.hpp b/modules/highgui/src/window_winrt_bridge.hpp index 25f4aef8ed..d3039e18e5 100644 --- a/modules/highgui/src/window_winrt_bridge.hpp +++ b/modules/highgui/src/window_winrt_bridge.hpp @@ -167,7 +167,7 @@ private: class CvWindow { public: - CvWindow(cv::String name, int flag = CV_WINDOW_NORMAL); + CvWindow(cv::String name, int flag = cv::WINDOW_NORMAL); ~CvWindow(); /** @brief NOTE: prototype. diff --git a/modules/imgproc/doc/pics/polar_remap_doc.svg b/modules/imgproc/doc/pics/polar_remap_doc.svg index 7d7a2f43b1..d6c4951e7e 100644 --- a/modules/imgproc/doc/pics/polar_remap_doc.svg +++ b/modules/imgproc/doc/pics/polar_remap_doc.svg @@ -2351,7 +2351,7 @@ v/yr//0n63/XHTrw/wG8XoGIn8Sc7QAAAABJRU5ErkJggg== x="1408.5438" y="1445.6154" id="tspan10807" - style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:17.5px;line-height:1.25;font-family:serif;-inkscape-font-specification:'serif Italic'">CV_WARP_FILL_OUTLIERS + style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:17.5px;line-height:1.25;font-family:serif;-inkscape-font-specification:'serif Italic'">cv::WARP_FILL_OUTLIERS CV_WARP_FILL_OUTLIERS + style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:17.5px;line-height:1.25;font-family:serif;-inkscape-font-specification:'serif Italic'">cv::WARP_FILL_OUTLIERS CV_WARP_FILL_OUTLIERS + style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:17.5px;line-height:1.25;font-family:serif;-inkscape-font-specification:'serif Italic'">cv::WARP_FILL_OUTLIERS ptr will point to pt1 (or pt2, see left_to_right description) location in -the image. Returns the number of pixels on the line between the ending points. -@see cv::LineIterator -*/ -CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, - CvLineIterator* line_iterator, - int connectivity CV_DEFAULT(8), - int left_to_right CV_DEFAULT(0)); - -#define CV_NEXT_LINE_POINT( line_iterator ) \ -{ \ - int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ - (line_iterator).err += (line_iterator).minus_delta + \ - ((line_iterator).plus_delta & _line_iterator_mask); \ - (line_iterator).ptr += (line_iterator).minus_step + \ - ((line_iterator).plus_step & _line_iterator_mask); \ -} - - -#define CV_FONT_HERSHEY_SIMPLEX 0 -#define CV_FONT_HERSHEY_PLAIN 1 -#define CV_FONT_HERSHEY_DUPLEX 2 -#define CV_FONT_HERSHEY_COMPLEX 3 -#define CV_FONT_HERSHEY_TRIPLEX 4 -#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 -#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 -#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 - -#define CV_FONT_ITALIC 16 - -#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX - - -/** Font structure */ -typedef struct CvFont -{ - const char* nameFont; //Qt:nameFont - CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) - int font_face; //Qt: bool italic /** =CV_FONT_* */ - const int* ascii; //!< font data and metrics - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; //!< slope coefficient: 0 - normal, >0 - italic - int thickness; //!< Qt: weight /** letters thickness */ - float dx; //!< horizontal interval between letters - int line_type; //!< Qt: PointSize -} -CvFont; - -/** @brief Initializes font structure (OpenCV 1.x API). - -The function initializes the font structure that can be passed to text rendering functions. - -@param font Pointer to the font structure initialized by the function -@param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. -@param hscale Horizontal scale. If equal to 1.0f , the characters have the original width -depending on the font type. If equal to 0.5f , the characters are of half the original width. -@param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending -on the font type. If equal to 0.5f , the characters are of half the original height. -@param shear Approximate tangent of the character slope relative to the vertical line. A zero -value means a non-italic font, 1.0f means about a 45 degree slope, etc. -@param thickness Thickness of the text strokes -@param line_type Type of the strokes, see line description - -@sa cvPutText - */ -CVAPI(void) cvInitFont( CvFont* font, int font_face, - double hscale, double vscale, - double shear CV_DEFAULT(0), - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8)); - -CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) -{ - CvFont font; - cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); - return font; -} - -/** @brief Renders text stroke with specified font and color at specified location. - CvFont should be initialized with cvInitFont -@see cvInitFont, cvGetTextSize, cvFont, cv::putText -*/ -CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, - const CvFont* font, CvScalar color ); - - -/** @brief Unpacks color value - -if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels -(depending on arrtype) of destination scalar are set to the same value = _color_ -*/ -CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); - -/** @brief Returns the polygon points which make up the given ellipse. - -The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial -sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than -0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total -number of points stored into 'pts' is returned by this function. -@see cv::ellipse2Poly -*/ -CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, - int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); - -/** @brief Draws contour outlines or filled interiors on the image -@see cv::drawContours -*/ -CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, - CvScalar external_color, CvScalar hole_color, - int max_level, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - CvPoint offset CV_DEFAULT(cvPoint(0,0))); - -/** @} */ - -#ifdef __cplusplus -} -#endif - #endif diff --git a/modules/imgproc/include/opencv2/imgproc/types_c.h b/modules/imgproc/include/opencv2/imgproc/types_c.h index d3e55f576f..1c0a17a7e6 100644 --- a/modules/imgproc/include/opencv2/imgproc/types_c.h +++ b/modules/imgproc/include/opencv2/imgproc/types_c.h @@ -45,615 +45,4 @@ #include "opencv2/core/core_c.h" -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup imgproc_c - @{ -*/ - -/** Connected component structure */ -typedef struct CvConnectedComp -{ - double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; - } - operator cv::Moments() const - { - return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); - } -#endif -} -CvMoments; - -#ifdef __cplusplus -} // extern "C" - -CV_INLINE CvMoments cvMoments() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMoments self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMoments(); -#endif -} - -CV_INLINE CvMoments cvMoments(const cv::Moments& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - double am00 = std::abs(m.m00); - CvMoments self = { - m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, - m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03, - am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0 - }; - return self; -#else - return CvMoments(m); -#endif -} - -extern "C" { -#endif // __cplusplus - -/** Hu invariants */ -typedef struct CvHuMoments -{ - double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ -} -CvHuMoments; - -/** Template matching methods */ -enum -{ - CV_TM_SQDIFF =0, - CV_TM_SQDIFF_NORMED =1, - CV_TM_CCORR =2, - CV_TM_CCORR_NORMED =3, - CV_TM_CCOEFF =4, - CV_TM_CCOEFF_NORMED =5 -}; - -typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); - -/** Contour retrieval modes */ -enum -{ - CV_RETR_EXTERNAL=0, - CV_RETR_LIST=1, - CV_RETR_CCOMP=2, - CV_RETR_TREE=3, - CV_RETR_FLOODFILL=4 -}; - -/** Contour approximation methods */ -enum -{ - CV_CHAIN_CODE=0, - CV_CHAIN_APPROX_NONE=1, - CV_CHAIN_APPROX_SIMPLE=2, - CV_CHAIN_APPROX_TC89_L1=3, - CV_CHAIN_APPROX_TC89_KCOS=4, - CV_LINK_RUNS=5 -}; - -/* -Internal structure that is used for sequential retrieving contours from the image. -It supports both hierarchical and plane variants of Suzuki algorithm. -*/ -typedef struct _CvContourScanner* CvContourScanner; - -/** Freeman chain reader state */ -typedef struct CvChainPtReader -{ - CV_SEQ_READER_FIELDS() - char code; - CvPoint pt; - schar deltas[8][2]; -} -CvChainPtReader; - -/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ -#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ - ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ - (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ - (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ - (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) - - -/** Contour approximation algorithms */ -enum -{ - CV_POLY_APPROX_DP = 0 -}; - -/** Shape matching methods */ -enum -{ - CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] - CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] - CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] -}; - -/** Shape orientation */ -enum -{ - CV_CLOCKWISE =1, - CV_COUNTER_CLOCKWISE =2 -}; - - -/** Convexity defect */ -typedef struct CvConvexityDefect -{ - CvPoint* start; /**< point of the contour where the defect begins */ - CvPoint* end; /**< point of the contour where the defect ends */ - CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ - float depth; /**< distance between the farthest point and the convex hull */ -} CvConvexityDefect; - - -/** Histogram comparison methods */ -enum -{ - CV_COMP_CORREL =0, - CV_COMP_CHISQR =1, - CV_COMP_INTERSECT =2, - CV_COMP_BHATTACHARYYA =3, - CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, - CV_COMP_CHISQR_ALT =4, - CV_COMP_KL_DIV =5 -}; - -/** Mask size for distance transform */ -enum -{ - CV_DIST_MASK_3 =3, - CV_DIST_MASK_5 =5, - CV_DIST_MASK_PRECISE =0 -}; - -/** Content of output label array: connected components or pixels */ -enum -{ - CV_DIST_LABEL_CCOMP = 0, - CV_DIST_LABEL_PIXEL = 1 -}; - -/** Distance types for Distance Transform and M-estimators */ -enum -{ - CV_DIST_USER =-1, /**< User defined distance */ - CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ - CV_DIST_L2 =2, /**< the simple euclidean distance */ - CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ - CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ - CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ - CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ - CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ - CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ - CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ - CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ - CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ - CV_THRESH_MASK =7, - CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values */ - CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values, but not - with CV_THRESH_OTSU */ -}; - -/** Adaptive threshold methods */ -enum -{ - CV_ADAPTIVE_THRESH_MEAN_C =0, - CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 -}; - -/** FloodFill flags */ -enum -{ - CV_FLOODFILL_FIXED_RANGE =(1 << 16), - CV_FLOODFILL_MASK_ONLY =(1 << 17) -}; - - -/** Canny edge detector flags */ -enum -{ - CV_CANNY_L2_GRADIENT =(1 << 31) -}; - -/** Variants of a Hough transform */ -enum -{ - CV_HOUGH_STANDARD =0, - CV_HOUGH_PROBABILISTIC =1, - CV_HOUGH_MULTI_SCALE =2, - CV_HOUGH_GRADIENT =3 -}; - - -/* Fast search data structures */ -struct CvFeatureTree; -struct CvLSH; -struct CvLSHOperations; - -/** @} */ - -#ifdef __cplusplus -} -#endif - #endif diff --git a/modules/imgproc/misc/java/test/ImgprocTest.java b/modules/imgproc/misc/java/test/ImgprocTest.java index 6f18c91c93..873292bc65 100644 --- a/modules/imgproc/misc/java/test/ImgprocTest.java +++ b/modules/imgproc/misc/java/test/ImgprocTest.java @@ -357,7 +357,7 @@ public class ImgprocTest extends OpenCVTestCase { H1.put(0, 0, 1, 2, 3); H2.put(0, 0, 4, 5, 6); - double distance = Imgproc.compareHist(H1, H2, Imgproc.CV_COMP_CORREL); + double distance = Imgproc.compareHist(H1, H2, Imgproc.HISTCMP_CORREL); assertEquals(1., distance, EPS); } @@ -636,7 +636,7 @@ public class ImgprocTest extends OpenCVTestCase { Mat dstLables = getMat(CvType.CV_32SC1, 0); Mat labels = new Mat(); - Imgproc.distanceTransformWithLabels(gray128, dst, labels, Imgproc.CV_DIST_L2, 3); + Imgproc.distanceTransformWithLabels(gray128, dst, labels, Imgproc.DIST_L2, 3); assertMatEqual(dstLables, labels); assertMatEqual(getMat(CvType.CV_32FC1, 8192), dst, EPS); @@ -813,7 +813,7 @@ public class ImgprocTest extends OpenCVTestCase { Mat linePoints = new Mat(4, 1, CvType.CV_32FC1); linePoints.put(0, 0, 0.53198653, 0.84675282, 2.5, 3.75); - Imgproc.fitLine(points, dst, Imgproc.CV_DIST_L12, 0, 0.01, 0.01); + Imgproc.fitLine(points, dst, Imgproc.DIST_L12, 0, 0.01, 0.01); assertMatEqual(linePoints, dst, EPS); } @@ -1040,7 +1040,7 @@ public class ImgprocTest extends OpenCVTestCase { Mat img = new Mat(sz, sz, CvType.CV_8U, new Scalar(128)); Mat circles = new Mat(); - Imgproc.HoughCircles(img, circles, Imgproc.CV_HOUGH_GRADIENT, 2, img.rows() / 4); + Imgproc.HoughCircles(img, circles, Imgproc.HOUGH_GRADIENT, 2, img.rows() / 4); assertEquals(0, circles.cols()); } @@ -1054,7 +1054,7 @@ public class ImgprocTest extends OpenCVTestCase { int radius = Math.min(img.cols() / 4, img.rows() / 4); Imgproc.circle(img, center, radius, colorBlack, 3); - Imgproc.HoughCircles(img, circles, Imgproc.CV_HOUGH_GRADIENT, 2, img.rows() / 4); + Imgproc.HoughCircles(img, circles, Imgproc.HOUGH_GRADIENT, 2, img.rows() / 4); assertEquals(1, circles.cols()); } @@ -1308,7 +1308,7 @@ public class ImgprocTest extends OpenCVTestCase { contour1.put(0, 0, 1, 1, 5, 1, 4, 3, 6, 2); contour2.put(0, 0, 1, 1, 6, 1, 4, 1, 2, 5); - double distance = Imgproc.matchShapes(contour1, contour2, Imgproc.CV_CONTOURS_MATCH_I1, 1); + double distance = Imgproc.matchShapes(contour1, contour2, Imgproc.CONTOURS_MATCH_I1, 1); assertEquals(2.81109697365334, distance, EPS); } diff --git a/modules/imgproc/perf/opencl/perf_matchTemplate.cpp b/modules/imgproc/perf/opencl/perf_matchTemplate.cpp index 735735f002..3079771aad 100644 --- a/modules/imgproc/perf/opencl/perf_matchTemplate.cpp +++ b/modules/imgproc/perf/opencl/perf_matchTemplate.cpp @@ -60,7 +60,7 @@ OCL_PERF_TEST_P(CV_TM_CCORRFixture, matchTemplate, declare.in(src, templ, WARMUP_RNG).out(dst); - OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR); + OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, cv::TM_CCORR); SANITY_CHECK(dst, 1e-4); } @@ -78,7 +78,7 @@ OCL_PERF_TEST_P(CV_TM_CCORR_NORMEDFixture, matchTemplate, declare.in(src, templ, WARMUP_RNG).out(dst); - OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, CV_TM_CCORR_NORMED); + OCL_TEST_CYCLE() cv::matchTemplate(src, templ, dst, cv::TM_CCORR_NORMED); SANITY_CHECK(dst, 3e-2); } diff --git a/modules/imgproc/perf/perf_houghcircles.cpp b/modules/imgproc/perf/perf_houghcircles.cpp index ba4fab8f99..a5ca36dbc0 100644 --- a/modules/imgproc/perf/perf_houghcircles.cpp +++ b/modules/imgproc/perf/perf_houghcircles.cpp @@ -26,7 +26,7 @@ PERF_TEST(PerfHoughCircles, Basic) TEST_CYCLE() { - HoughCircles(img, circles, CV_HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); + HoughCircles(img, circles, cv::HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); } SANITY_CHECK_NOTHING(); @@ -50,7 +50,7 @@ PERF_TEST(PerfHoughCircles2, ManySmallCircles) TEST_CYCLE() { - HoughCircles(img, circles, CV_HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); + HoughCircles(img, circles, cv::HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); } SANITY_CHECK_NOTHING(); @@ -76,7 +76,7 @@ PERF_TEST(PerfHoughCircles4f, Basic) TEST_CYCLE() { - HoughCircles(img, circles, CV_HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); + HoughCircles(img, circles, cv::HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); } SANITY_CHECK_NOTHING(); diff --git a/modules/imgproc/src/_geom.h b/modules/imgproc/src/_geom.h index bfde73d6d5..cdbbfef3cc 100644 --- a/modules/imgproc/src/_geom.h +++ b/modules/imgproc/src/_geom.h @@ -42,16 +42,6 @@ #ifndef _CV_GEOM_H_ #define _CV_GEOM_H_ -/* Finds distance between two points */ -CV_INLINE float icvDistanceL2_32f( CvPoint2D32f pt1, CvPoint2D32f pt2 ) -{ - float dx = pt2.x - pt1.x; - float dy = pt2.y - pt1.y; - - return std::sqrt( dx*dx + dy*dy ); -} - - /* curvature: 0 - 1-curvature, 1 - k-cosine curvature. */ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, CvMemStorage* storage, int method ); diff --git a/modules/imgproc/src/accum.cpp b/modules/imgproc/src/accum.cpp index fbd5223c13..edb1be4df1 100644 --- a/modules/imgproc/src/accum.cpp +++ b/modules/imgproc/src/accum.cpp @@ -644,42 +644,5 @@ void cv::accumulateWeighted( InputArray _src, InputOutputArray _dst, } -CV_IMPL void -cvAcc( const void* arr, void* sumarr, const void* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(arr), dst = cv::cvarrToMat(sumarr), mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::accumulate( src, dst, mask ); -} - -CV_IMPL void -cvSquareAcc( const void* arr, void* sumarr, const void* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(arr), dst = cv::cvarrToMat(sumarr), mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::accumulateSquare( src, dst, mask ); -} - -CV_IMPL void -cvMultiplyAcc( const void* arr1, const void* arr2, - void* sumarr, const void* maskarr ) -{ - cv::Mat src1 = cv::cvarrToMat(arr1), src2 = cv::cvarrToMat(arr2); - cv::Mat dst = cv::cvarrToMat(sumarr), mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::accumulateProduct( src1, src2, dst, mask ); -} - -CV_IMPL void -cvRunningAvg( const void* arr, void* sumarr, double alpha, const void* maskarr ) -{ - cv::Mat src = cv::cvarrToMat(arr), dst = cv::cvarrToMat(sumarr), mask; - if( maskarr ) - mask = cv::cvarrToMat(maskarr); - cv::accumulateWeighted( src, dst, alpha, mask ); -} /* End of file. */ diff --git a/modules/imgproc/src/approx.cpp b/modules/imgproc/src/approx.cpp index efbc6d33a5..d30437020c 100644 --- a/modules/imgproc/src/approx.cpp +++ b/modules/imgproc/src/approx.cpp @@ -53,6 +53,38 @@ typedef struct _CvPtInfo } _CvPtInfo; +static const CvPoint icvCodeDeltas[8] = + { {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1} }; + +/** Freeman chain reader state */ +typedef struct CvChainPtReader +{ + CV_SEQ_READER_FIELDS() + char code; + CvPoint pt; + schar deltas[8][2]; +} +CvChainPtReader; + +static void cvStartReadChainPoints( CvChain * chain, CvChainPtReader * reader ) +{ + int i; + + if( !chain || !reader ) + CV_Error( CV_StsNullPtr, "" ); + + if( chain->elem_size != 1 || chain->header_size < (int)sizeof(CvChain)) + CV_Error( CV_StsBadSize, "" ); + + cvStartReadSeq( (CvSeq *) chain, (CvSeqReader *) reader, 0 ); + + reader->pt = chain->origin; + for( i = 0; i < 8; i++ ) + { + reader->deltas[i][0] = (schar) icvCodeDeltas[i].x; + reader->deltas[i][1] = (schar) icvCodeDeltas[i].y; + } +} /* curvature: 0 - 1-curvature, 1 - k-cosine curvature. */ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, @@ -103,9 +135,9 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, /* calc 1-curvature */ s = abs_diff[reader.code - prev_code + 7]; - if( method <= CV_CHAIN_APPROX_SIMPLE ) + if( method <= cv::CHAIN_APPROX_SIMPLE ) { - if( method == CV_CHAIN_APPROX_NONE || s != 0 ) + if( method == cv::CHAIN_APPROX_NONE || s != 0 ) { CV_WRITE_SEQ_ELEM( pt, writer ); } @@ -121,7 +153,7 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, //CV_Assert( pt.x == chain->origin.x && pt.y == chain->origin.y ); - if( method <= CV_CHAIN_APPROX_SIMPLE ) + if( method <= cv::CHAIN_APPROX_SIMPLE ) return cvEndWriteSeq( &writer ); current->next = 0; @@ -176,7 +208,7 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, current->k = --k; /* determine cosine curvature if it should be used */ - if( method == CV_CHAIN_APPROX_TC89_KCOS ) + if( method == cv::CHAIN_APPROX_TC89_KCOS ) { /* calc k-cosine curvature */ for( j = k, s = 0; j > 0; j-- ) @@ -288,7 +320,7 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, } while( current != 0 ); - if( method == CV_CHAIN_APPROX_TC89_KCOS ) + if( method == cv::CHAIN_APPROX_TC89_KCOS ) goto copy_vect; /* Pass 4. @@ -374,96 +406,6 @@ copy_vect: return cvEndWriteSeq( &writer ); } - -/*Applies some approximation algorithm to chain-coded contour(s) and - converts it/them to polygonal representation */ -CV_IMPL CvSeq* -cvApproxChains( CvSeq* src_seq, - CvMemStorage* storage, - int method, - double /*parameter*/, - int minimal_perimeter, - int recursive ) -{ - CvSeq *prev_contour = 0, *parent = 0; - CvSeq *dst_seq = 0; - - if( !src_seq || !storage ) - CV_Error( CV_StsNullPtr, "" ); - if( method > CV_CHAIN_APPROX_TC89_KCOS || method <= 0 || minimal_perimeter < 0 ) - CV_Error( CV_StsOutOfRange, "" ); - - while( src_seq != 0 ) - { - int len = src_seq->total; - - if( len >= minimal_perimeter ) - { - CvSeq *contour = 0; - - switch( method ) - { - case CV_CHAIN_APPROX_NONE: - case CV_CHAIN_APPROX_SIMPLE: - case CV_CHAIN_APPROX_TC89_L1: - case CV_CHAIN_APPROX_TC89_KCOS: - contour = icvApproximateChainTC89( (CvChain *) src_seq, sizeof( CvContour ), storage, method ); - break; - default: - CV_Error( CV_StsOutOfRange, "" ); - } - - if( contour->total > 0 ) - { - cvBoundingRect( contour, 1 ); - - contour->v_prev = parent; - contour->h_prev = prev_contour; - - if( prev_contour ) - prev_contour->h_next = contour; - else if( parent ) - parent->v_next = contour; - prev_contour = contour; - if( !dst_seq ) - dst_seq = prev_contour; - } - else /* if resultant contour has zero length, skip it */ - { - len = -1; - } - } - - if( !recursive ) - break; - - if( src_seq->v_next && len >= minimal_perimeter ) - { - CV_Assert( prev_contour != 0 ); - parent = prev_contour; - prev_contour = 0; - src_seq = src_seq->v_next; - } - else - { - while( src_seq->h_next == 0 ) - { - src_seq = src_seq->v_prev; - if( src_seq == 0 ) - break; - prev_contour = parent; - if( parent ) - parent = parent->v_prev; - } - if( src_seq ) - src_seq = src_seq->h_next; - } - } - - return dst_seq; -} - - /****************************************************************************************\ * Polygonal Approximation * \****************************************************************************************/ @@ -708,156 +650,3 @@ void cv::approxPolyDP( InputArray _curve, OutputArray _approxCurve, Mat(nout, 1, CV_MAKETYPE(depth, 2), buf).copyTo(_approxCurve); } - - -CV_IMPL CvSeq* -cvApproxPoly( const void* array, int header_size, - CvMemStorage* storage, int method, - double parameter, int parameter2 ) -{ - cv::AutoBuffer _buf; - cv::AutoBuffer stack(100); - CvSeq* dst_seq = 0; - CvSeq *prev_contour = 0, *parent = 0; - CvContour contour_header; - CvSeq* src_seq = 0; - CvSeqBlock block; - int recursive = 0; - - if( CV_IS_SEQ( array )) - { - src_seq = (CvSeq*)array; - if( !CV_IS_SEQ_POLYLINE( src_seq )) - CV_Error( CV_StsBadArg, "Unsupported sequence type" ); - - recursive = parameter2; - - if( !storage ) - storage = src_seq->storage; - } - else - { - src_seq = cvPointSeqFromMat( - CV_SEQ_KIND_CURVE | (parameter2 ? CV_SEQ_FLAG_CLOSED : 0), - array, &contour_header, &block ); - } - - if( !storage ) - CV_Error( CV_StsNullPtr, "NULL storage pointer " ); - - if( header_size < 0 ) - CV_Error( CV_StsOutOfRange, "header_size is negative. " - "Pass 0 to make the destination header_size == input header_size" ); - - if( header_size == 0 ) - header_size = src_seq->header_size; - - if( !CV_IS_SEQ_POLYLINE( src_seq )) - { - if( CV_IS_SEQ_CHAIN( src_seq )) - { - CV_Error( CV_StsBadArg, "Input curves are not polygonal. " - "Use cvApproxChains first" ); - } - else - { - CV_Error( CV_StsBadArg, "Input curves have unknown type" ); - } - } - - if( header_size == 0 ) - header_size = src_seq->header_size; - - if( header_size < (int)sizeof(CvContour) ) - CV_Error( CV_StsBadSize, "New header size must be non-less than sizeof(CvContour)" ); - - if( method != CV_POLY_APPROX_DP ) - CV_Error( CV_StsOutOfRange, "Unknown approximation method" ); - - while( src_seq != 0 ) - { - CvSeq *contour = 0; - - switch (method) - { - case CV_POLY_APPROX_DP: - if( parameter < 0 ) - CV_Error( CV_StsOutOfRange, "Accuracy must be non-negative" ); - - CV_Assert( CV_SEQ_ELTYPE(src_seq) == CV_32SC2 || - CV_SEQ_ELTYPE(src_seq) == CV_32FC2 ); - - { - int npoints = src_seq->total, nout = 0; - _buf.allocate(npoints*2); - cv::Point *src = _buf.data(), *dst = src + npoints; - bool closed = CV_IS_SEQ_CLOSED(src_seq); - - if( src_seq->first->next == src_seq->first ) - src = (cv::Point*)src_seq->first->data; - else - cvCvtSeqToArray(src_seq, src); - - if( CV_SEQ_ELTYPE(src_seq) == CV_32SC2 ) - nout = cv::approxPolyDP_(src, npoints, dst, closed, parameter, stack); - else if( CV_SEQ_ELTYPE(src_seq) == CV_32FC2 ) - nout = cv::approxPolyDP_((cv::Point2f*)src, npoints, - (cv::Point2f*)dst, closed, parameter, stack); - else - CV_Error( CV_StsUnsupportedFormat, "" ); - - contour = cvCreateSeq( src_seq->flags, header_size, - src_seq->elem_size, storage ); - cvSeqPushMulti(contour, dst, nout); - } - break; - default: - CV_Error( CV_StsBadArg, "Invalid approximation method" ); - } - - CV_Assert( contour ); - - if( header_size >= (int)sizeof(CvContour)) - cvBoundingRect( contour, 1 ); - - contour->v_prev = parent; - contour->h_prev = prev_contour; - - if( prev_contour ) - prev_contour->h_next = contour; - else if( parent ) - parent->v_next = contour; - prev_contour = contour; - if( !dst_seq ) - dst_seq = prev_contour; - - if( !recursive ) - break; - - if( src_seq->v_next ) - { - CV_Assert( prev_contour != 0 ); - parent = prev_contour; - prev_contour = 0; - src_seq = src_seq->v_next; - } - else - { - while( src_seq->h_next == 0 ) - { - src_seq = src_seq->v_prev; - if( src_seq == 0 ) - break; - prev_contour = parent; - if( parent ) - parent = parent->v_prev; - } - if( src_seq ) - src_seq = src_seq->h_next; - } - } - - return dst_seq; -} - -/* End of file. */ diff --git a/modules/imgproc/src/canny.cpp b/modules/imgproc/src/canny.cpp index f6da61e7c1..8f65ba8c15 100644 --- a/modules/imgproc/src/canny.cpp +++ b/modules/imgproc/src/canny.cpp @@ -835,9 +835,10 @@ void Canny( InputArray _src, OutputArray _dst, _dst.create(size, CV_8U); + // backward compatibility + const int CV_CANNY_L2_GRADIENT = (1 << 31); if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT) { - // backward compatibility aperture_size &= ~CV_CANNY_L2_GRADIENT; L2gradient = true; } diff --git a/modules/imgproc/src/color.cpp b/modules/imgproc/src/color.cpp index cc4dd13c92..d12253a184 100644 --- a/modules/imgproc/src/color.cpp +++ b/modules/imgproc/src/color.cpp @@ -356,14 +356,3 @@ void cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) } } } //namespace cv - - -CV_IMPL void -cvCvtColor( const CvArr* srcarr, CvArr* dstarr, int code ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0; - CV_Assert( src.depth() == dst.depth() ); - - cv::cvtColor(src, dst, code, dst.channels()); - CV_Assert( dst.data == dst0.data ); -} diff --git a/modules/imgproc/src/contours.cpp b/modules/imgproc/src/contours.cpp index d8823206f2..25c34f0829 100644 --- a/modules/imgproc/src/contours.cpp +++ b/modules/imgproc/src/contours.cpp @@ -50,62 +50,395 @@ using namespace cv; (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) -static const CvPoint icvCodeDeltas[8] = - { {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1} }; +static const CvPoint icvCodeDeltas[8] = { + {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1} +}; -CV_IMPL void -cvStartReadChainPoints( CvChain * chain, CvChainPtReader * reader ) + +namespace cv { - int i; - if( !chain || !reader ) - CV_Error( CV_StsNullPtr, "" ); - - if( chain->elem_size != 1 || chain->header_size < (int)sizeof(CvChain)) - CV_Error( CV_StsBadSize, "" ); - - cvStartReadSeq( (CvSeq *) chain, (CvSeqReader *) reader, 0 ); - - reader->pt = chain->origin; - for( i = 0; i < 8; i++ ) - { - reader->deltas[i][0] = (schar) icvCodeDeltas[i].x; - reader->deltas[i][1] = (schar) icvCodeDeltas[i].y; - } -} - - -/* retrieves next point of the chain curve and updates reader */ -CV_IMPL CvPoint -cvReadChainPoint( CvChainPtReader * reader ) +// Calculates bounding rectangle of a point set or retrieves already calculated +static Rect pointSetBoundingRect( const Mat& points ) { - if( !reader ) - CV_Error( CV_StsNullPtr, "" ); + int npoints = points.checkVector(2); + int depth = points.depth(); + CV_Assert(npoints >= 0 && (depth == CV_32F || depth == CV_32S)); - cv::Point2i pt = reader->pt; + int xmin = 0, ymin = 0, xmax = -1, ymax = -1, i; + bool is_float = depth == CV_32F; - schar *ptr = reader->ptr; - if (ptr) + if( npoints == 0 ) + return Rect(); + +#if CV_SIMD + const int64_t* pts = points.ptr(); + + if( !is_float ) { - int code = *ptr++; - - if( ptr >= reader->block_max ) + v_int32 minval, maxval; + minval = maxval = v_reinterpret_as_s32(vx_setall_s64(*pts)); //min[0]=pt.x, min[1]=pt.y, min[2]=pt.x, min[3]=pt.y + for( i = 1; i <= npoints - v_int32::nlanes/2; i+= v_int32::nlanes/2 ) { - cvChangeSeqBlock( (CvSeqReader *) reader, 1 ); - ptr = reader->ptr; + v_int32 ptXY2 = v_reinterpret_as_s32(vx_load(pts + i)); + minval = v_min(ptXY2, minval); + maxval = v_max(ptXY2, maxval); + } + minval = v_min(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval)))); + maxval = v_max(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval)))); + if( i <= npoints - v_int32::nlanes/4 ) + { + v_int32 ptXY = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(vx_load_low(pts + i)))); + minval = v_min(ptXY, minval); + maxval = v_max(ptXY, maxval); + i += v_int64::nlanes/2; + } + for(int j = 16; j < CV_SIMD_WIDTH; j*=2) + { + minval = v_min(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval)))); + maxval = v_max(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval)))); + } + xmin = minval.get0(); + xmax = maxval.get0(); + ymin = v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval))).get0(); + ymax = v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval))).get0(); +#if CV_SIMD_WIDTH > 16 + if( i < npoints ) + { + v_int32x4 minval2, maxval2; + minval2 = maxval2 = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); + for( i++; i < npoints; i++ ) + { + v_int32x4 ptXY = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); + minval2 = v_min(ptXY, minval2); + maxval2 = v_max(ptXY, maxval2); + } + xmin = min(xmin, minval2.get0()); + xmax = max(xmax, maxval2.get0()); + ymin = min(ymin, v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval2))).get0()); + ymax = max(ymax, v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval2))).get0()); + } +#endif + } + else + { + v_float32 minval, maxval; + minval = maxval = v_reinterpret_as_f32(vx_setall_s64(*pts)); //min[0]=pt.x, min[1]=pt.y, min[2]=pt.x, min[3]=pt.y + for( i = 1; i <= npoints - v_float32::nlanes/2; i+= v_float32::nlanes/2 ) + { + v_float32 ptXY2 = v_reinterpret_as_f32(vx_load(pts + i)); + minval = v_min(ptXY2, minval); + maxval = v_max(ptXY2, maxval); + } + minval = v_min(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval)))); + maxval = v_max(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval)))); + if( i <= npoints - v_float32::nlanes/4 ) + { + v_float32 ptXY = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(vx_load_low(pts + i)))); + minval = v_min(ptXY, minval); + maxval = v_max(ptXY, maxval); + i += v_float32::nlanes/4; + } + for(int j = 16; j < CV_SIMD_WIDTH; j*=2) + { + minval = v_min(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval)))); + maxval = v_max(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval)))); + } + xmin = cvFloor(minval.get0()); + xmax = cvFloor(maxval.get0()); + ymin = cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval))).get0()); + ymax = cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval))).get0()); +#if CV_SIMD_WIDTH > 16 + if( i < npoints ) + { + v_float32x4 minval2, maxval2; + minval2 = maxval2 = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); + for( i++; i < npoints; i++ ) + { + v_float32x4 ptXY = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); + minval2 = v_min(ptXY, minval2); + maxval2 = v_max(ptXY, maxval2); + } + xmin = min(xmin, cvFloor(minval2.get0())); + xmax = max(xmax, cvFloor(maxval2.get0())); + ymin = min(ymin, cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval2))).get0())); + ymax = max(ymax, cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval2))).get0())); + } +#endif + } +#else + const Point* pts = points.ptr(); + Point pt = pts[0]; + + if( !is_float ) + { + xmin = xmax = pt.x; + ymin = ymax = pt.y; + + for( i = 1; i < npoints; i++ ) + { + pt = pts[i]; + + if( xmin > pt.x ) + xmin = pt.x; + + if( xmax < pt.x ) + xmax = pt.x; + + if( ymin > pt.y ) + ymin = pt.y; + + if( ymax < pt.y ) + ymax = pt.y; + } + } + else + { + Cv32suf v; + // init values + xmin = xmax = CV_TOGGLE_FLT(pt.x); + ymin = ymax = CV_TOGGLE_FLT(pt.y); + + for( i = 1; i < npoints; i++ ) + { + pt = pts[i]; + pt.x = CV_TOGGLE_FLT(pt.x); + pt.y = CV_TOGGLE_FLT(pt.y); + + if( xmin > pt.x ) + xmin = pt.x; + + if( xmax < pt.x ) + xmax = pt.x; + + if( ymin > pt.y ) + ymin = pt.y; + + if( ymax < pt.y ) + ymax = pt.y; } - reader->ptr = ptr; - reader->code = (schar)code; - CV_Assert( (code & ~7) == 0 ); - reader->pt.x = pt.x + icvCodeDeltas[code].x; - reader->pt.y = pt.y + icvCodeDeltas[code].y; + v.i = CV_TOGGLE_FLT(xmin); xmin = cvFloor(v.f); + v.i = CV_TOGGLE_FLT(ymin); ymin = cvFloor(v.f); + // because right and bottom sides of the bounding rectangle are not inclusive + // (note +1 in width and height calculation below), cvFloor is used here instead of cvCeil + v.i = CV_TOGGLE_FLT(xmax); xmax = cvFloor(v.f); + v.i = CV_TOGGLE_FLT(ymax); ymax = cvFloor(v.f); } +#endif - return cvPoint(pt); + return Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1); } +static Rect maskBoundingRect( const Mat& img ) +{ + CV_Assert( img.depth() <= CV_8S && img.channels() == 1 ); + + Size size = img.size(); + int xmin = size.width, ymin = -1, xmax = -1, ymax = -1, i, j, k; + + for( i = 0; i < size.height; i++ ) + { + const uchar* _ptr = img.ptr(i); + const uchar* ptr = (const uchar*)alignPtr(_ptr, 4); + int have_nz = 0, k_min, offset = (int)(ptr - _ptr); + j = 0; + offset = MIN(offset, size.width); + for( ; j < offset; j++ ) + if( _ptr[j] ) + { + have_nz = 1; + break; + } + if( j < offset ) + { + if( j < xmin ) + xmin = j; + if( j > xmax ) + xmax = j; + } + if( offset < size.width ) + { + xmin -= offset; + xmax -= offset; + size.width -= offset; + j = 0; + for( ; j <= xmin - 4; j += 4 ) + if( *((int*)(ptr+j)) ) + break; + for( ; j < xmin; j++ ) + if( ptr[j] ) + { + xmin = j; + if( j > xmax ) + xmax = j; + have_nz = 1; + break; + } + k_min = MAX(j-1, xmax); + k = size.width - 1; + for( ; k > k_min && (k&3) != 3; k-- ) + if( ptr[k] ) + break; + if( k > k_min && (k&3) == 3 ) + { + for( ; k > k_min+3; k -= 4 ) + if( *((int*)(ptr+k-3)) ) + break; + } + for( ; k > k_min; k-- ) + if( ptr[k] ) + { + xmax = k; + have_nz = 1; + break; + } + if( !have_nz ) + { + j &= ~3; + for( ; j <= k - 3; j += 4 ) + if( *((int*)(ptr+j)) ) + break; + for( ; j <= k; j++ ) + if( ptr[j] ) + { + have_nz = 1; + break; + } + } + xmin += offset; + xmax += offset; + size.width += offset; + } + if( have_nz ) + { + if( ymin < 0 ) + ymin = i; + ymax = i; + } + } + + if( xmin >= size.width ) + xmin = ymin = 0; + return Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1); +} + +} // namespace cv:: + +cv::Rect cv::boundingRect(InputArray array) +{ + CV_INSTRUMENT_REGION(); + + Mat m = array.getMat(); + return m.depth() <= CV_8U ? maskBoundingRect(m) : pointSetBoundingRect(m); +} + +// utility function for cvBoundingRect +static CvSeq* cvPointSeqFromMat( int seq_kind, const CvArr* arr, + CvContour* contour_header, CvSeqBlock* block ) +{ + CV_Assert( arr != 0 && contour_header != 0 && block != 0 ); + + int eltype; + CvMat hdr; + CvMat* mat = (CvMat*)arr; + + if( !CV_IS_MAT( mat )) + CV_Error( CV_StsBadArg, "Input array is not a valid matrix" ); + + if( CV_MAT_CN(mat->type) == 1 && mat->width == 2 ) + mat = cvReshape(mat, &hdr, 2); + + eltype = CV_MAT_TYPE( mat->type ); + if( eltype != CV_32SC2 && eltype != CV_32FC2 ) + CV_Error( CV_StsUnsupportedFormat, + "The matrix can not be converted to point sequence because of " + "inappropriate element type" ); + + if( (mat->width != 1 && mat->height != 1) || !CV_IS_MAT_CONT(mat->type)) + CV_Error( CV_StsBadArg, + "The matrix converted to point sequence must be " + "1-dimensional and continuous" ); + + cvMakeSeqHeaderForArray( + (seq_kind & (CV_SEQ_KIND_MASK|CV_SEQ_FLAG_CLOSED)) | eltype, + sizeof(CvContour), CV_ELEM_SIZE(eltype), mat->data.ptr, + mat->width*mat->height, (CvSeq*)contour_header, block ); + + return (CvSeq*)contour_header; +} + +/* Calculates bounding rectangle of a point set or retrieves already calculated */ +static CvRect cvBoundingRect( CvArr* array, int update ) +{ + cv::Rect rect; + CvContour contour_header; + CvSeq* ptseq = 0; + CvSeqBlock block; + + CvMat stub, *mat = 0; + int calculate = update; + + if( CV_IS_SEQ( array )) + { + ptseq = (CvSeq*)array; + if( !CV_IS_SEQ_POINT_SET( ptseq )) + CV_Error( CV_StsBadArg, "Unsupported sequence type" ); + + if( ptseq->header_size < (int)sizeof(CvContour)) + { + update = 0; + calculate = 1; + } + } + else + { + mat = cvGetMat( array, &stub ); + if( CV_MAT_TYPE(mat->type) == CV_32SC2 || + CV_MAT_TYPE(mat->type) == CV_32FC2 ) + { + ptseq = cvPointSeqFromMat(CV_SEQ_KIND_GENERIC, mat, &contour_header, &block); + mat = 0; + } + else if( CV_MAT_TYPE(mat->type) != CV_8UC1 && + CV_MAT_TYPE(mat->type) != CV_8SC1 ) + CV_Error( CV_StsUnsupportedFormat, + "The image/matrix format is not supported by the function" ); + update = 0; + calculate = 1; + } + + if( !calculate ) + return ((CvContour*)ptseq)->rect; + + if( mat ) + { + rect = cvRect(cv::maskBoundingRect(cv::cvarrToMat(mat))); + } + else if( ptseq->total ) + { + cv::AutoBuffer abuf; + rect = cvRect(cv::pointSetBoundingRect(cv::cvarrToMat(ptseq, false, false, 0, &abuf))); + } + if( update ) + ((CvContour*)ptseq)->rect = cvRect(rect); + return cvRect(rect); +} + +static double cvThreshold( const void* srcarr, void* dstarr, double thresh, double maxval, int type ) +{ + cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), dst0 = dst; + + CV_Assert( src.size == dst.size && src.channels() == dst.channels() && + (src.depth() == dst.depth() || dst.depth() == CV_8U)); + + thresh = cv::threshold( src, dst, thresh, maxval, type ); + if( dst0.data != dst.data ) + dst.convertTo( dst0, dst0.depth() ); + return thresh; +} + /****************************************************************************************\ * Raster->Chain Tree (Suzuki algorithms) * \****************************************************************************************/ @@ -170,6 +503,13 @@ typedef struct _CvContourScanner } _CvContourScanner; +/* +Internal structure that is used for sequential retrieving contours from the image. +It supports both hierarchical and plane variants of Suzuki algorithm. +*/ +typedef struct _CvContourScanner* CvContourScanner; + + #define _CV_FIND_CONTOURS_FLAGS_EXTERNAL_ONLY 1 #define _CV_FIND_CONTOURS_FLAGS_HIERARCHIC 2 @@ -187,23 +527,23 @@ cvStartFindContours_Impl( void* _img, CvMemStorage* storage, CvMat stub, *mat = cvGetMat( _img, &stub ); - if( CV_MAT_TYPE(mat->type) == CV_32SC1 && mode == CV_RETR_CCOMP ) - mode = CV_RETR_FLOODFILL; + if( CV_MAT_TYPE(mat->type) == CV_32SC1 && mode == cv::RETR_CCOMP ) + mode = cv::RETR_FLOODFILL; - if( !((CV_IS_MASK_ARR( mat ) && mode < CV_RETR_FLOODFILL) || - (CV_MAT_TYPE(mat->type) == CV_32SC1 && mode == CV_RETR_FLOODFILL)) ) + if( !((CV_IS_MASK_ARR( mat ) && mode < cv::RETR_FLOODFILL) || + (CV_MAT_TYPE(mat->type) == CV_32SC1 && mode == cv::RETR_FLOODFILL)) ) CV_Error( CV_StsUnsupportedFormat, - "[Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL " + "[Start]FindContours supports only CV_8UC1 images when mode != cv::RETR_FLOODFILL " "otherwise supports CV_32SC1 images only" ); CvSize size = cvSize( mat->width, mat->height ); int step = mat->step; uchar* img = (uchar*)(mat->data.ptr); - if( method < 0 || method > CV_CHAIN_APPROX_TC89_KCOS ) + if( method < 0 || method > cv::CHAIN_APPROX_TC89_KCOS ) CV_Error( CV_StsOutOfRange, "" ); - if( header_size < (int) (method == CV_CHAIN_CODE ? sizeof( CvChain ) : sizeof( CvContour ))) + if( header_size < (int) (method == cv::CHAIN_CODE ? sizeof( CvChain ) : sizeof( CvContour ))) CV_Error( CV_StsBadSize, "" ); CvContourScanner scanner = (CvContourScanner)cvAlloc( sizeof( *scanner )); @@ -233,10 +573,10 @@ cvStartFindContours_Impl( void* _img, CvMemStorage* storage, scanner->approx_method2 = scanner->approx_method1 = method; - if( method == CV_CHAIN_APPROX_TC89_L1 || method == CV_CHAIN_APPROX_TC89_KCOS ) - scanner->approx_method1 = CV_CHAIN_CODE; + if( method == cv::CHAIN_APPROX_TC89_L1 || method == cv::CHAIN_APPROX_TC89_KCOS ) + scanner->approx_method1 = cv::CHAIN_CODE; - if( scanner->approx_method1 == CV_CHAIN_CODE ) + if( scanner->approx_method1 == cv::CHAIN_CODE ) { scanner->seq_type1 = CV_SEQ_CHAIN_CONTOUR; scanner->header_size1 = scanner->approx_method1 == scanner->approx_method2 ? @@ -253,7 +593,7 @@ cvStartFindContours_Impl( void* _img, CvMemStorage* storage, scanner->header_size2 = header_size; - if( scanner->approx_method2 == CV_CHAIN_CODE ) + if( scanner->approx_method2 == cv::CHAIN_CODE ) { scanner->seq_type2 = scanner->seq_type1; scanner->elem_size2 = scanner->elem_size1; @@ -264,20 +604,20 @@ cvStartFindContours_Impl( void* _img, CvMemStorage* storage, scanner->elem_size2 = sizeof( CvPoint ); } - scanner->seq_type1 = scanner->approx_method1 == CV_CHAIN_CODE ? + scanner->seq_type1 = scanner->approx_method1 == cv::CHAIN_CODE ? CV_SEQ_CHAIN_CONTOUR : CV_SEQ_POLYGON; - scanner->seq_type2 = scanner->approx_method2 == CV_CHAIN_CODE ? + scanner->seq_type2 = scanner->approx_method2 == cv::CHAIN_CODE ? CV_SEQ_CHAIN_CONTOUR : CV_SEQ_POLYGON; cvSaveMemStoragePos( storage, &(scanner->initial_pos) ); - if( method > CV_CHAIN_APPROX_SIMPLE ) + if( method > cv::CHAIN_APPROX_SIMPLE ) { scanner->storage1 = cvCreateChildMemStorage( scanner->storage2 ); } - if( mode > CV_RETR_LIST ) + if( mode > cv::RETR_LIST ) { scanner->cinfo_storage = cvCreateChildMemStorage( scanner->storage2 ); scanner->cinfo_set = cvCreateSet( 0, sizeof( CvSet ), sizeof( _CvContourInfo ), @@ -304,155 +644,11 @@ cvStartFindContours_Impl( void* _img, CvMemStorage* storage, /* converts all pixels to 0 or 1 */ if( CV_MAT_TYPE(mat->type) != CV_32S ) - cvThreshold( mat, mat, 0, 1, CV_THRESH_BINARY ); + cvThreshold( mat, mat, 0, 1, cv::THRESH_BINARY ); return scanner; } -CV_IMPL CvContourScanner -cvStartFindContours( void* _img, CvMemStorage* storage, - int header_size, int mode, - int method, CvPoint offset ) -{ - return cvStartFindContours_Impl(_img, storage, header_size, mode, method, offset, 1); -} - -/* - Final stage of contour processing. - Three variants possible: - 1. Contour, which was retrieved using border following, is added to - the contour tree. It is the case when the icvSubstituteContour function - was not called after retrieving the contour. - - 2. New contour, assigned by icvSubstituteContour function, is added to the - tree. The retrieved contour itself is removed from the storage. - Here two cases are possible: - 2a. If one deals with plane variant of algorithm - (hierarchical structure is not reconstructed), - the contour is removed completely. - 2b. In hierarchical case, the header of the contour is not removed. - It's marked as "link to contour" and h_next pointer of it is set to - new, substituting contour. - - 3. The similar to 2, but when NULL pointer was assigned by - icvSubstituteContour function. In this case, the function removes - retrieved contour completely if plane case and - leaves header if hierarchical (but doesn't mark header as "link"). - ------------------------------------------------------------------------ - The 1st variant can be used to retrieve and store all the contours from the image - (with optional conversion from chains to contours using some approximation from - restricted set of methods). Some characteristics of contour can be computed in the - same pass. - - The usage scheme can look like: - - icvContourScanner scanner; - CvMemStorage* contour_storage; - CvSeq* first_contour; - CvStatus result; - - ... - - icvCreateMemStorage( &contour_storage, block_size/0 ); - - ... - - cvStartFindContours - ( img, contour_storage, - header_size, approx_method, - [external_only,] - &scanner ); - - for(;;) - { - [CvSeq* contour;] - result = icvFindNextContour( &scanner, &contour/0 ); - - if( result != CV_OK ) break; - - // calculate some characteristics - ... - } - - if( result < 0 ) goto error_processing; - - cvEndFindContours( &scanner, &first_contour ); - ... - - ----------------------------------------------------------------- - - Second variant is more complex and can be used when someone wants store not - the retrieved contours but transformed ones. (e.g. approximated with some - non-default algorithm ). - - The scheme can be the as following: - - icvContourScanner scanner; - CvMemStorage* contour_storage; - CvMemStorage* temp_storage; - CvSeq* first_contour; - CvStatus result; - - ... - - icvCreateMemStorage( &contour_storage, block_size/0 ); - icvCreateMemStorage( &temp_storage, block_size/0 ); - - ... - - icvStartFindContours8uC1R - ( , temp_storage, - header_size, approx_method, - [retrival_mode], - &scanner ); - - for(;;) - { - CvSeq* temp_contour; - CvSeq* new_contour; - result = icvFindNextContour( scanner, &temp_contour ); - - if( result != CV_OK ) break; - - ( temp_contour, contour_storage, - &new_contour, ); - - icvSubstituteContour( scanner, new_contour ); - ... - } - - if( result < 0 ) goto error_processing; - - cvEndFindContours( &scanner, &first_contour ); - ... - - ---------------------------------------------------------------------------- - Third method to retrieve contours may be applied if contours are irrelevant - themselves but some characteristics of them are used only. - The usage is similar to second except slightly different internal loop - - for(;;) - { - CvSeq* temp_contour; - result = icvFindNextContour( &scanner, &temp_contour ); - - if( result != CV_OK ) break; - - // calculate some characteristics of temp_contour - - icvSubstituteContour( scanner, 0 ); - ... - } - - new_storage variable is not needed here. - - Note, that the second and the third methods can interleave. I.e. it is possible to - retain contours that satisfy with some criteria and reject others. - In hierarchic case the resulting tree is the part of original tree with - some nodes absent. But in the resulting tree the contour1 is a child - (may be indirect) of contour2 iff in the original tree the contour1 - is a child (may be indirect) of contour2. -*/ static void icvEndProcessContour( CvContourScanner scanner ) { @@ -483,23 +679,6 @@ icvEndProcessContour( CvContourScanner scanner ) } } -/* replaces one contour with another */ -CV_IMPL void -cvSubstituteContour( CvContourScanner scanner, CvSeq * new_contour ) -{ - _CvContourInfo *l_cinfo; - - if( !scanner ) - CV_Error( CV_StsNullPtr, "" ); - - l_cinfo = scanner->l_cinfo; - if( l_cinfo && l_cinfo->contour && l_cinfo->contour != new_contour ) - { - l_cinfo->contour = new_contour; - scanner->subst_flag = 1; - } -} - static const int MAX_SIZE = 16; /* @@ -523,7 +702,7 @@ icvFetchContour( schar *ptr, int prev_s = -1, s, s_end; int method = _method - 1; - CV_DbgAssert( (unsigned) _method <= CV_CHAIN_APPROX_SIMPLE ); + CV_DbgAssert( (unsigned) _method <= cv::CHAIN_APPROX_SIMPLE ); /* initialize local state */ CV_INIT_3X3_DELTAS( deltas, step, 1 ); @@ -612,7 +791,7 @@ icvFetchContour( schar *ptr, cvEndWriteSeq( &writer ); - if( _method != CV_CHAIN_CODE ) + if( _method != cv::CHAIN_CODE ) cvBoundingRect( contour, 1 ); CV_DbgAssert( (writer.seq->total == 0 && writer.seq->first == 0) || @@ -721,7 +900,7 @@ icvFetchContourEx( schar* ptr, int prev_s = -1, s, s_end; int method = _method - 1; - CV_DbgAssert( (unsigned) _method <= CV_CHAIN_APPROX_SIMPLE ); + CV_DbgAssert( (unsigned) _method <= cv::CHAIN_APPROX_SIMPLE ); CV_DbgAssert( 1 < nbd && nbd < 128 ); /* initialize local state */ @@ -826,7 +1005,7 @@ icvFetchContourEx( schar* ptr, cvEndWriteSeq( &writer ); - if( _method != CV_CHAIN_CODE ) + if( _method != cv::CHAIN_CODE ) ((CvContour*)contour)->rect = cvRect(rect); CV_DbgAssert( (writer.seq->total == 0 && writer.seq->first == 0) || @@ -915,7 +1094,7 @@ icvFetchContourEx_32s( int* ptr, const int nbd0 = ccomp_val | new_flag; const int nbd1 = nbd0 | right_flag; - CV_DbgAssert( (unsigned) _method <= CV_CHAIN_APPROX_SIMPLE ); + CV_DbgAssert( (unsigned) _method <= cv::CHAIN_APPROX_SIMPLE ); /* initialize local state */ CV_INIT_3X3_DELTAS( deltas, step, 1 ); @@ -1016,7 +1195,7 @@ icvFetchContourEx_32s( int* ptr, cvEndWriteSeq( &writer ); - if( _method != CV_CHAIN_CODE ) + if( _method != cv::CHAIN_CODE ) ((CvContour*)contour)->rect = cvRect(rect); CV_DbgAssert( (writer.seq->total == 0 && writer.seq->first == 0) || @@ -1028,8 +1207,7 @@ icvFetchContourEx_32s( int* ptr, } -CvSeq * -cvFindNextContour( CvContourScanner scanner ) +static CvSeq * cvFindNextContour( CvContourScanner scanner ) { if( !scanner ) CV_Error( CV_StsNullPtr, "" ); @@ -1053,7 +1231,7 @@ cvFindNextContour( CvContourScanner scanner ) int prev = img[x - 1]; int new_mask = -2; - if( mode == CV_RETR_FLOODFILL ) + if( mode == cv::RETR_FLOODFILL ) { prev = ((int*)img)[x - 1]; new_mask = INT_MIN / 2; @@ -1065,7 +1243,7 @@ cvFindNextContour( CvContourScanner scanner ) int* img_i = 0; int p = 0; - if( mode == CV_RETR_FLOODFILL ) + if( mode == cv::RETR_FLOODFILL ) { img0_i = (int*)img0; img_i = (int*)img; @@ -1137,7 +1315,7 @@ cvFindNextContour( CvContourScanner scanner ) origin.x = x - is_hole; /* find contour parent */ - if( mode <= 1 || (!is_hole && (mode == CV_RETR_CCOMP || mode == CV_RETR_FLOODFILL)) || lnbd.x <= 0 ) + if( mode <= 1 || (!is_hole && (mode == cv::RETR_CCOMP || mode == cv::RETR_FLOODFILL)) || lnbd.x <= 0 ) { par_info = &(scanner->frame_info); } @@ -1309,8 +1487,7 @@ cvFindNextContour( CvContourScanner scanner ) The function add to tree the last retrieved/substituted contour, releases temp_storage, restores state of dst_storage (if needed), and returns pointer to root of the contour tree */ -CV_IMPL CvSeq * -cvEndFindContours( CvContourScanner * _scanner ) +static CvSeq * cvEndFindContours( CvContourScanner * _scanner ) { CvContourScanner scanner; CvSeq *first = 0; @@ -1752,11 +1929,11 @@ cvFindContours_Impl( void* img, CvMemStorage* storage, *firstContour = 0; - if( method == CV_LINK_RUNS ) + if( method == cv::LINK_RUNS ) { if( offset.x != 0 || offset.y != 0 ) CV_Error( CV_StsOutOfRange, - "Nonzero offset is not supported in CV_LINK_RUNS yet" ); + "Nonzero offset is not supported in cv::LINK_RUNS yet" ); count = icvFindContoursInInterval( img, storage, firstContour, cntHeaderSize ); } @@ -1787,35 +1964,6 @@ cvFindContours_Impl( void* img, CvMemStorage* storage, return count; } -/*F/////////////////////////////////////////////////////////////////////////////////////// -// Name: cvFindContours -// Purpose: -// Finds all the contours on the bi-level image. -// Context: -// Parameters: -// img - source image. -// Non-zero pixels are considered as 1-pixels -// and zero pixels as 0-pixels. -// step - full width of source image in bytes. -// size - width and height of the image in pixels -// storage - pointer to storage where will the output contours be placed. -// header_size - header size of resulting contours -// mode - mode of contour retrieval. -// method - method of approximation that is applied to contours -// first_contour - pointer to first contour pointer -// Returns: -// CV_OK or error code -// Notes: -//F*/ -CV_IMPL int -cvFindContours( void* img, CvMemStorage* storage, - CvSeq** firstContour, int cntHeaderSize, - int mode, - int method, CvPoint offset ) -{ - return cvFindContours_Impl(img, storage, firstContour, cntHeaderSize, mode, method, offset, 1); -} - void cv::findContours( InputArray _image, OutputArrayOfArrays _contours, OutputArray _hierarchy, int mode, int method, Point offset ) { @@ -1829,7 +1977,7 @@ void cv::findContours( InputArray _image, OutputArrayOfArrays _contours, Mat image0 = _image.getMat(), image; Point offset0(0, 0); - if(method != CV_LINK_RUNS) + if(method != cv::LINK_RUNS) { offset0 = Point(-1, -1); copyMakeBorder(image0, image, 1, 1, 1, 1, BORDER_CONSTANT | BORDER_ISOLATED, Scalar(0)); diff --git a/modules/imgproc/src/convhull.cpp b/modules/imgproc/src/convhull.cpp index 27c70d2ad9..cb1b649b54 100644 --- a/modules/imgproc/src/convhull.cpp +++ b/modules/imgproc/src/convhull.cpp @@ -455,140 +455,3 @@ bool isContourConvex( InputArray _contour ) } } - -CV_IMPL CvSeq* -cvConvexHull2( const CvArr* array, void* hull_storage, - int orientation, int return_points ) -{ - CvMat* mat = 0; - CvContour contour_header; - CvSeq hull_header; - CvSeqBlock block, hullblock; - CvSeq* ptseq = 0; - CvSeq* hullseq = 0; - - if( CV_IS_SEQ( array )) - { - ptseq = (CvSeq*)array; - if( !CV_IS_SEQ_POINT_SET( ptseq )) - CV_Error( CV_StsBadArg, "Unsupported sequence type" ); - if( hull_storage == 0 ) - hull_storage = ptseq->storage; - } - else - { - ptseq = cvPointSeqFromMat( CV_SEQ_KIND_GENERIC, array, &contour_header, &block ); - } - - bool isStorage = isStorageOrMat(hull_storage); - - if(isStorage) - { - if( return_points ) - { - hullseq = cvCreateSeq(CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE(ptseq)| - CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX, - sizeof(CvContour), sizeof(CvPoint),(CvMemStorage*)hull_storage ); - } - else - { - hullseq = cvCreateSeq( - CV_SEQ_KIND_CURVE|CV_SEQ_ELTYPE_PPOINT| - CV_SEQ_FLAG_CLOSED|CV_SEQ_FLAG_CONVEX, - sizeof(CvContour), sizeof(CvPoint*), (CvMemStorage*)hull_storage ); - } - } - else - { - mat = (CvMat*)hull_storage; - - if( (mat->cols != 1 && mat->rows != 1) || !CV_IS_MAT_CONT(mat->type)) - CV_Error( CV_StsBadArg, - "The hull matrix should be continuous and have a single row or a single column" ); - - if( mat->cols + mat->rows - 1 < ptseq->total ) - CV_Error( CV_StsBadSize, "The hull matrix size might be not enough to fit the hull" ); - - if( CV_MAT_TYPE(mat->type) != CV_SEQ_ELTYPE(ptseq) && - CV_MAT_TYPE(mat->type) != CV_32SC1 ) - CV_Error( CV_StsUnsupportedFormat, - "The hull matrix must have the same type as input or 32sC1 (integers)" ); - - hullseq = cvMakeSeqHeaderForArray( - CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED, - sizeof(hull_header), CV_ELEM_SIZE(mat->type), mat->data.ptr, - mat->cols + mat->rows - 1, &hull_header, &hullblock ); - cvClearSeq( hullseq ); - } - - int hulltype = CV_SEQ_ELTYPE(hullseq); - int total = ptseq->total; - if( total == 0 ) - { - if( !isStorage ) - CV_Error( CV_StsBadSize, - "Point sequence can not be empty if the output is matrix" ); - return 0; - } - - cv::AutoBuffer _ptbuf; - cv::Mat h0; - cv::convexHull(cv::cvarrToMat(ptseq, false, false, 0, &_ptbuf), h0, - orientation == CV_CLOCKWISE, CV_MAT_CN(hulltype) == 2); - - - if( hulltype == CV_SEQ_ELTYPE_PPOINT ) - { - const int* idx = h0.ptr(); - int ctotal = (int)h0.total(); - for( int i = 0; i < ctotal; i++ ) - { - void* ptr = cvGetSeqElem(ptseq, idx[i]); - cvSeqPush( hullseq, &ptr ); - } - } - else - cvSeqPushMulti(hullseq, h0.ptr(), (int)h0.total()); - - if (isStorage) - { - return hullseq; - } - else - { - if( mat->rows > mat->cols ) - mat->rows = hullseq->total; - else - mat->cols = hullseq->total; - return 0; - } -} - - -CV_IMPL int -cvCheckContourConvexity( const CvArr* array ) -{ - CvContour contour_header; - CvSeqBlock block; - CvSeq* contour = (CvSeq*)array; - - if( CV_IS_SEQ(contour) ) - { - if( !CV_IS_SEQ_POINT_SET(contour)) - CV_Error( CV_StsUnsupportedFormat, - "Input sequence must be polygon (closed 2d curve)" ); - } - else - { - contour = cvPointSeqFromMat(CV_SEQ_KIND_CURVE| - CV_SEQ_FLAG_CLOSED, array, &contour_header, &block ); - } - - if( contour->total == 0 ) - return -1; - - cv::AutoBuffer _buf; - return cv::isContourConvex(cv::cvarrToMat(contour, false, false, 0, &_buf)) ? 1 : 0; -} - -/* End of file. */ diff --git a/modules/imgproc/src/corner.cpp b/modules/imgproc/src/corner.cpp index f2bd9843f7..31078b9bed 100644 --- a/modules/imgproc/src/corner.cpp +++ b/modules/imgproc/src/corner.cpp @@ -735,25 +735,3 @@ void cv::preCornerDetect( InputArray _src, OutputArray _dst, int ksize, int bord } } } - -CV_IMPL void -cvCornerMinEigenVal( const CvArr* srcarr, CvArr* dstarr, - int block_size, int aperture_size ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.size() == dst.size() && dst.type() == CV_32FC1 ); - cv::cornerMinEigenVal( src, dst, block_size, aperture_size, cv::BORDER_REPLICATE ); -} - -CV_IMPL void -cvCornerEigenValsAndVecs( const void* srcarr, void* dstarr, - int block_size, int aperture_size ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.rows == dst.rows && src.cols*6 == dst.cols*dst.channels() && dst.depth() == CV_32F ); - cv::cornerEigenValsAndVecs( src, dst, block_size, aperture_size, cv::BORDER_REPLICATE ); -} - -/* End of file */ diff --git a/modules/imgproc/src/distransform.cpp b/modules/imgproc/src/distransform.cpp index ccc39795ea..c0bd53bf7f 100644 --- a/modules/imgproc/src/distransform.cpp +++ b/modules/imgproc/src/distransform.cpp @@ -732,20 +732,20 @@ void cv::distanceTransform( InputArray _src, OutputArray _dst, OutputArray _labe _labels.create(src.size(), CV_32S); labels = _labels.getMat(); - maskSize = CV_DIST_MASK_5; + maskSize = cv::DIST_MASK_5; } float _mask[5] = {0}; - if( maskSize != CV_DIST_MASK_3 && maskSize != CV_DIST_MASK_5 && maskSize != CV_DIST_MASK_PRECISE ) + if( maskSize != cv::DIST_MASK_3 && maskSize != cv::DIST_MASK_5 && maskSize != cv::DIST_MASK_PRECISE ) CV_Error( CV_StsBadSize, "Mask size should be 3 or 5 or 0 (precise)" ); - if( distType == CV_DIST_C || distType == CV_DIST_L1 ) - maskSize = !need_labels ? CV_DIST_MASK_3 : CV_DIST_MASK_5; - else if( distType == CV_DIST_L2 && need_labels ) - maskSize = CV_DIST_MASK_5; + if( distType == cv::DIST_C || distType == cv::DIST_L1 ) + maskSize = !need_labels ? cv::DIST_MASK_3 : cv::DIST_MASK_5; + else if( distType == cv::DIST_L2 && need_labels ) + maskSize = cv::DIST_MASK_5; - if( maskSize == CV_DIST_MASK_PRECISE ) + if( maskSize == cv::DIST_MASK_PRECISE ) { #ifdef HAVE_IPP @@ -781,19 +781,19 @@ void cv::distanceTransform( InputArray _src, OutputArray _dst, OutputArray _labe return; } - CV_Assert( distType == CV_DIST_C || distType == CV_DIST_L1 || distType == CV_DIST_L2 ); + CV_Assert( distType == cv::DIST_C || distType == cv::DIST_L1 || distType == cv::DIST_L2 ); - getDistanceTransformMask( (distType == CV_DIST_C ? 0 : - distType == CV_DIST_L1 ? 1 : 2) + maskSize*10, _mask ); + getDistanceTransformMask( (distType == cv::DIST_C ? 0 : + distType == cv::DIST_L1 ? 1 : 2) + maskSize*10, _mask ); Size size = src.size(); - int border = maskSize == CV_DIST_MASK_3 ? 1 : 2; + int border = maskSize == cv::DIST_MASK_3 ? 1 : 2; Mat temp( size.height + border*2, size.width + border*2, CV_32SC1 ); if( !need_labels ) { - if( maskSize == CV_DIST_MASK_3 ) + if( maskSize == cv::DIST_MASK_3 ) { #if defined (HAVE_IPP) && (IPP_VERSION_X100 >= 700) && 0 // disabled: https://github.com/opencv/opencv/issues/15904 CV_IPP_CHECK() @@ -832,7 +832,7 @@ void cv::distanceTransform( InputArray _src, OutputArray _dst, OutputArray _labe { labels.setTo(Scalar::all(0)); - if( labelType == CV_DIST_LABEL_CCOMP ) + if( labelType == cv::DIST_LABEL_CCOMP ) { Mat zpix = src == 0; connectedComponents(zpix, labels, 8, CV_32S, CCL_WU); @@ -860,27 +860,9 @@ void cv::distanceTransform( InputArray _src, OutputArray _dst, { CV_INSTRUMENT_REGION(); - if (distanceType == CV_DIST_L1 && dstType==CV_8U) + if (distanceType == cv::DIST_L1 && dstType==CV_8U) distanceTransform_L1_8U(_src, _dst); else distanceTransform(_src, _dst, noArray(), distanceType, maskSize, DIST_LABEL_PIXEL); } - -CV_IMPL void -cvDistTransform( const void* srcarr, void* dstarr, - int distType, int maskSize, - const float * /*mask*/, - void* labelsarr, int labelType ) -{ - cv::Mat src = cv::cvarrToMat(srcarr); - const cv::Mat dst = cv::cvarrToMat(dstarr); - const cv::Mat labels = cv::cvarrToMat(labelsarr); - - cv::distanceTransform(src, dst, labelsarr ? cv::_OutputArray(labels) : cv::_OutputArray(), - distType, maskSize, labelType); - -} - - -/* End of file. */ diff --git a/modules/imgproc/src/drawing.cpp b/modules/imgproc/src/drawing.cpp index 7eefd313c7..1a4303e22a 100644 --- a/modules/imgproc/src/drawing.cpp +++ b/modules/imgproc/src/drawing.cpp @@ -1111,7 +1111,7 @@ FillConvexPoly( Mat& img, const Point2l* v, int npts, const void* color, int lin Point2l p0; int delta1, delta2; - if( line_type < CV_AA ) + if( line_type < cv::LINE_AA ) delta1 = delta2 = XY_ONE >> 1; else delta1 = XY_ONE - 1, delta2 = 0; @@ -1181,7 +1181,7 @@ FillConvexPoly( Mat& img, const Point2l* v, int npts, const void* color, int lin do { - if( line_type < CV_AA || y < (int)ymax || y == (int)ymin ) + if( line_type < cv::LINE_AA || y < (int)ymax || y == (int)ymin ) { for( i = 0; i < 2; i++ ) { @@ -1277,7 +1277,7 @@ CollectPolyEdges( Mat& img, const Point2l* v, int count, std::vector& pt1.x = (pt1.x + offset.x) << (XY_SHIFT - shift); pt1.y = (pt1.y + delta) >> shift; - if( line_type < CV_AA ) + if( line_type < cv::LINE_AA ) { t0.y = pt0.y; t1.y = pt1.y; t0.x = (pt0.x + (XY_ONE >> 1)) >> XY_SHIFT; @@ -1632,7 +1632,7 @@ ThickLine( Mat& img, Point2l p0, Point2l p1, const void* color, if( thickness <= 1 ) { - if( line_type < CV_AA ) + if( line_type < cv::LINE_AA ) { if( line_type == 1 || line_type == 4 || shift == 0 ) { @@ -1678,7 +1678,7 @@ ThickLine( Mat& img, Point2l p0, Point2l p1, const void* color, { if( flags & (i+1) ) { - if( line_type < CV_AA ) + if( line_type < cv::LINE_AA ) { Point center; center.x = (int)((p0.x + (XY_ONE>>1)) >> XY_SHIFT); @@ -1796,7 +1796,7 @@ void line( InputOutputArray _img, Point pt1, Point pt2, const Scalar& color, Mat img = _img.getMat(); - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; CV_Assert( 0 < thickness && thickness <= MAX_THICKNESS ); @@ -1835,7 +1835,7 @@ void rectangle( InputOutputArray _img, Point pt1, Point pt2, Mat img = _img.getMat(); - if( lineType == CV_AA && img.depth() != CV_8U ) + if( lineType == cv::LINE_AA && img.depth() != CV_8U ) lineType = 8; CV_Assert( thickness <= MAX_THICKNESS ); @@ -1885,7 +1885,7 @@ void circle( InputOutputArray _img, Point center, int radius, Mat img = _img.getMat(); - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; CV_Assert( radius >= 0 && thickness <= MAX_THICKNESS && @@ -1917,7 +1917,7 @@ void ellipse( InputOutputArray _img, Point center, Size axes, Mat img = _img.getMat(); - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; CV_Assert( axes.width >= 0 && axes.height >= 0 && @@ -1947,7 +1947,7 @@ void ellipse(InputOutputArray _img, const RotatedRect& box, const Scalar& color, Mat img = _img.getMat(); - if( lineType == CV_AA && img.depth() != CV_8U ) + if( lineType == cv::LINE_AA && img.depth() != CV_8U ) lineType = 8; CV_Assert( box.size.width >= 0 && box.size.height >= 0 && @@ -1978,7 +1978,7 @@ void fillConvexPoly( InputOutputArray _img, const Point* pts, int npts, if( !pts || npts <= 0 ) return; - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; double buf[4]; @@ -1996,7 +1996,7 @@ void fillPoly( InputOutputArray _img, const Point** pts, const int* npts, int nc Mat img = _img.getMat(); - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; CV_Assert( pts && npts && ncontours >= 0 && 0 <= shift && shift <= XY_SHIFT ); @@ -2027,7 +2027,7 @@ void polylines( InputOutputArray _img, const Point* const* pts, const int* npts, Mat img = _img.getMat(); - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; CV_Assert( pts && npts && ncontours >= 0 && @@ -2143,6 +2143,12 @@ static void addChildContour(InputArrayOfArrays contours, } } +void +cvDrawContours( void* _img, CvSeq* contour, + CvScalar _externalColor, CvScalar _holeColor, + int maxLevel, int thickness, + int line_type, CvPoint _offset ); + void cv::drawContours( InputOutputArray _image, InputArrayOfArrays _contours, int contourIdx, const Scalar& color, int thickness, int lineType, InputArray _hierarchy, @@ -2232,7 +2238,7 @@ static const int CodeDeltas[8][2] = #define CV_ADJUST_EDGE_COUNT( count, seq ) \ ((count) -= ((count) == (seq)->total && !CV_IS_SEQ_CLOSED(seq))) -CV_IMPL void +void cvDrawContours( void* _img, CvSeq* contour, CvScalar _externalColor, CvScalar _holeColor, int maxLevel, int thickness, @@ -2247,7 +2253,7 @@ cvDrawContours( void* _img, CvSeq* contour, cv::Point offset = _offset; double ext_buf[4], hole_buf[4]; - if( line_type == CV_AA && img.depth() != CV_8U ) + if( line_type == cv::LINE_AA && img.depth() != CV_8U ) line_type = 8; if( !contour ) @@ -2352,169 +2358,3 @@ cvDrawContours( void* _img, CvSeq* contour, if( h_next && contour0 ) contour0->h_next = h_next; } - -CV_IMPL CvScalar -cvColorToScalar( double packed_color, int type ) -{ - cv::Scalar scalar; - - if( CV_MAT_DEPTH( type ) == CV_8U ) - { - int icolor = cvRound( packed_color ); - if( CV_MAT_CN( type ) > 1 ) - { - scalar.val[0] = icolor & 255; - scalar.val[1] = (icolor >> 8) & 255; - scalar.val[2] = (icolor >> 16) & 255; - scalar.val[3] = (icolor >> 24) & 255; - } - else - { - scalar.val[0] = cv::saturate_cast( icolor ); - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - } - } - else if( CV_MAT_DEPTH( type ) == CV_8S ) - { - int icolor = cvRound( packed_color ); - if( CV_MAT_CN( type ) > 1 ) - { - scalar.val[0] = (char)icolor; - scalar.val[1] = (char)(icolor >> 8); - scalar.val[2] = (char)(icolor >> 16); - scalar.val[3] = (char)(icolor >> 24); - } - else - { - scalar.val[0] = cv::saturate_cast( icolor ); - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - } - } - else - { - int cn = CV_MAT_CN( type ); - switch( cn ) - { - case 1: - scalar.val[0] = packed_color; - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - break; - case 2: - scalar.val[0] = scalar.val[1] = packed_color; - scalar.val[2] = scalar.val[3] = 0; - break; - case 3: - scalar.val[0] = scalar.val[1] = scalar.val[2] = packed_color; - scalar.val[3] = 0; - break; - default: - scalar.val[0] = scalar.val[1] = - scalar.val[2] = scalar.val[3] = packed_color; - break; - } - } - - return cvScalar(scalar); -} - -CV_IMPL int -cvInitLineIterator( const CvArr* img, CvPoint pt1, CvPoint pt2, - CvLineIterator* iterator, int connectivity, - int left_to_right ) -{ - CV_Assert( iterator != 0 ); - cv::LineIterator li(cv::cvarrToMat(img), pt1, pt2, connectivity, left_to_right!=0); - - iterator->err = li.err; - iterator->minus_delta = li.minusDelta; - iterator->plus_delta = li.plusDelta; - iterator->minus_step = li.minusStep; - iterator->plus_step = li.plusStep; - iterator->ptr = li.ptr; - - return li.count; -} - -CV_IMPL void -cvLine( CvArr* _img, CvPoint pt1, CvPoint pt2, CvScalar color, - int thickness, int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - cv::line( img, pt1, pt2, color, thickness, line_type, shift ); -} - -CV_IMPL void -cvRectangle( CvArr* _img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness, - int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - cv::rectangle( img, pt1, pt2, color, thickness, line_type, shift ); -} - -CV_IMPL void -cvCircle( CvArr* _img, CvPoint center, int radius, - CvScalar color, int thickness, int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - cv::circle( img, center, radius, color, thickness, line_type, shift ); -} - -CV_IMPL void -cvEllipse( CvArr* _img, CvPoint center, CvSize axes, - double angle, double start_angle, double end_angle, - CvScalar color, int thickness, int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - cv::ellipse( img, center, axes, angle, start_angle, end_angle, - color, thickness, line_type, shift ); -} - -CV_IMPL void -cvFillPoly( CvArr* _img, CvPoint **pts, const int *npts, int ncontours, - CvScalar color, int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - - cv::fillPoly( img, (const cv::Point**)pts, npts, ncontours, color, line_type, shift ); -} - -CV_IMPL void -cvPolyLine( CvArr* _img, CvPoint **pts, const int *npts, - int ncontours, int closed, CvScalar color, - int thickness, int line_type, int shift ) -{ - cv::Mat img = cv::cvarrToMat(_img); - - cv::polylines( img, (const cv::Point**)pts, npts, ncontours, - closed != 0, color, thickness, line_type, shift ); -} - -CV_IMPL void -cvPutText( CvArr* _img, const char *text, CvPoint org, const CvFont *_font, CvScalar color ) -{ - cv::Mat img = cv::cvarrToMat(_img); - CV_Assert( text != 0 && _font != 0); - cv::putText( img, text, org, _font->font_face, (_font->hscale+_font->vscale)*0.5, - color, _font->thickness, _font->line_type, - CV_IS_IMAGE(_img) && ((IplImage*)_img)->origin != 0 ); -} - - -CV_IMPL void -cvInitFont( CvFont *font, int font_face, double hscale, double vscale, - double shear, int thickness, int line_type ) -{ - CV_Assert( font != 0 && hscale > 0 && vscale > 0 && thickness >= 0 ); - - font->ascii = 0; - font->font_face = font_face; - font->hscale = (float)hscale; - font->vscale = (float)vscale; - font->thickness = thickness; - font->shear = (float)shear; - font->greek = font->cyrillic = 0; - font->line_type = line_type; -} - -/* End of file. */ diff --git a/modules/imgproc/src/emd.cpp b/modules/imgproc/src/emd.cpp index 3e065b0404..15899c6abe 100644 --- a/modules/imgproc/src/emd.cpp +++ b/modules/imgproc/src/emd.cpp @@ -113,6 +113,8 @@ typedef struct CvEMDState } CvEMDState; +typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); + /* static function declaration */ static int icvInitEMD( const float *signature1, int size1, const float *signature2, int size2, @@ -145,7 +147,7 @@ static float icvDistL1( const float *x, const float *y, void *user_param ); static float icvDistC( const float *x, const float *y, void *user_param ); /* The main function */ -CV_IMPL float cvCalcEMD2( const CvArr* signature_arr1, +static float cvCalcEMD2( const CvArr* signature_arr1, const CvArr* signature_arr2, int dist_type, CvDistanceFunction dist_func, @@ -232,13 +234,13 @@ CV_IMPL float cvCalcEMD2( const CvArr* signature_arr1, user_param = (void *) (size_t)dims; switch (dist_type) { - case CV_DIST_L1: + case cv::DIST_L1: dist_func = icvDistL1; break; - case CV_DIST_L2: + case cv::DIST_L2: dist_func = icvDistL2; break; - case CV_DIST_C: + case cv::DIST_C: dist_func = icvDistC; break; default: diff --git a/modules/imgproc/src/filter.dispatch.cpp b/modules/imgproc/src/filter.dispatch.cpp index 6a0280e03b..83daf02c48 100644 --- a/modules/imgproc/src/filter.dispatch.cpp +++ b/modules/imgproc/src/filter.dispatch.cpp @@ -1613,16 +1613,3 @@ void sepFilter2D(InputArray _src, OutputArray _dst, int ddepth, } } // namespace - -CV_IMPL void -cvFilter2D( const CvArr* srcarr, CvArr* dstarr, const CvMat* _kernel, CvPoint anchor ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - cv::Mat kernel = cv::cvarrToMat(_kernel); - - CV_Assert( src.size() == dst.size() && src.channels() == dst.channels() ); - - cv::filter2D( src, dst, dst.depth(), kernel, anchor, 0, cv::BORDER_REPLICATE ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/floodfill.cpp b/modules/imgproc/src/floodfill.cpp index 8595011d48..0d1886591b 100644 --- a/modules/imgproc/src/floodfill.cpp +++ b/modules/imgproc/src/floodfill.cpp @@ -628,25 +628,3 @@ int cv::floodFill( InputOutputArray _image, Point seedPoint, Mat mask; return floodFill(_image, mask, seedPoint, newVal, rect, loDiff, upDiff, flags); } - - -CV_IMPL void -cvFloodFill( CvArr* arr, CvPoint seed_point, - CvScalar newVal, CvScalar lo_diff, CvScalar up_diff, - CvConnectedComp* comp, int flags, CvArr* maskarr ) -{ - if( comp ) - memset( comp, 0, sizeof(*comp) ); - - cv::Mat img = cv::cvarrToMat(arr), mask = cv::cvarrToMat(maskarr); - int area = cv::floodFill(img, mask, seed_point, newVal, - comp ? (cv::Rect*)&comp->rect : 0, - lo_diff, up_diff, flags ); - if( comp ) - { - comp->area = area; - comp->value = newVal; - } -} - -/* End of file. */ diff --git a/modules/imgproc/src/histogram.cpp b/modules/imgproc/src/histogram.cpp index 1fbb9aae51..7001249775 100644 --- a/modules/imgproc/src/histogram.cpp +++ b/modules/imgproc/src/histogram.cpp @@ -47,6 +47,8 @@ #include "opencv2/core/utils/tls.hpp" +void cvSetHistBinRanges( CvHistogram* hist, float** ranges, int uniform ); + namespace cv { @@ -2045,17 +2047,17 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) const int len = it.planes[0].rows*it.planes[0].cols*H1.channels(); j = 0; - if( (method == CV_COMP_CHISQR) || (method == CV_COMP_CHISQR_ALT)) + if( (method == cv::HISTCMP_CHISQR) || (method == cv::HISTCMP_CHISQR_ALT)) { for( ; j < len; j++ ) { double a = h1[j] - h2[j]; - double b = (method == CV_COMP_CHISQR) ? h1[j] : h1[j] + h2[j]; + double b = (method == cv::HISTCMP_CHISQR) ? h1[j] : h1[j] + h2[j]; if( fabs(b) > DBL_EPSILON ) result += a*a/b; } } - else if( method == CV_COMP_CORREL ) + else if( method == cv::HISTCMP_CORREL ) { #if CV_SIMD_64F v_float64 v_s1 = vx_setzero_f64(); @@ -2091,7 +2093,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) s22 += v_reduce_sum(v_s22); s1 += v_reduce_sum(v_s1); s2 += v_reduce_sum(v_s2); -#elif CV_SIMD && 0 //Disable vectorization for CV_COMP_CORREL if f64 is unsupported due to low precision +#elif CV_SIMD && 0 //Disable vectorization for cv::HISTCMP_CORREL if f64 is unsupported due to low precision v_float32 v_s1 = vx_setzero_f32(); v_float32 v_s2 = vx_setzero_f32(); v_float32 v_s11 = vx_setzero_f32(); @@ -2126,7 +2128,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) s22 += b*b; } } - else if( method == CV_COMP_INTERSECT ) + else if( method == cv::HISTCMP_INTERSECT ) { #if CV_SIMD_64F v_float64 v_result = vx_setzero_f64(); @@ -2148,7 +2150,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) for( ; j < len; j++ ) result += std::min(h1[j], h2[j]); } - else if( method == CV_COMP_BHATTACHARYYA ) + else if( method == cv::HISTCMP_BHATTACHARYYA ) { #if CV_SIMD_64F v_float64 v_s1 = vx_setzero_f64(); @@ -2174,7 +2176,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) s1 += v_reduce_sum(v_s1); s2 += v_reduce_sum(v_s2); result += v_reduce_sum(v_result); -#elif CV_SIMD && 0 //Disable vectorization for CV_COMP_BHATTACHARYYA if f64 is unsupported due to low precision +#elif CV_SIMD && 0 //Disable vectorization for cv::HISTCMP_BHATTACHARYYA if f64 is unsupported due to low precision v_float32 v_s1 = vx_setzero_f32(); v_float32 v_s2 = vx_setzero_f32(); v_float32 v_result = vx_setzero_f32(); @@ -2199,7 +2201,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) s2 += b; } } - else if( method == CV_COMP_KL_DIV ) + else if( method == cv::HISTCMP_KL_DIV ) { for( ; j < len; j++ ) { @@ -2218,9 +2220,9 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) CV_Error( CV_StsBadArg, "Unknown comparison method" ); } - if( method == CV_COMP_CHISQR_ALT ) + if( method == cv::HISTCMP_CHISQR_ALT ) result *= 2; - else if( method == CV_COMP_CORREL ) + else if( method == cv::HISTCMP_CORREL ) { size_t total = H1.total(); double scale = 1./total; @@ -2228,7 +2230,7 @@ double cv::compareHist( InputArray _H1, InputArray _H2, int method ) double denom2 = (s11 - s1*s1*scale)*(s22 - s2*s2*scale); result = std::abs(denom2) > DBL_EPSILON ? num/std::sqrt(denom2) : 1.; } - else if( method == CV_COMP_BHATTACHARYYA ) + else if( method == cv::HISTCMP_BHATTACHARYYA ) { s1 *= s2; s1 = fabs(s1) > FLT_EPSILON ? 1./std::sqrt(s1) : 1.; @@ -2251,14 +2253,14 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) CV_Assert( H1.size(i) == H2.size(i) ); const SparseMat *PH1 = &H1, *PH2 = &H2; - if( PH1->nzcount() > PH2->nzcount() && method != CV_COMP_CHISQR && method != CV_COMP_CHISQR_ALT && method != CV_COMP_KL_DIV ) + if( PH1->nzcount() > PH2->nzcount() && method != cv::HISTCMP_CHISQR && method != cv::HISTCMP_CHISQR_ALT && method != cv::HISTCMP_KL_DIV ) std::swap(PH1, PH2); SparseMatConstIterator it = PH1->begin(); int N1 = (int)PH1->nzcount(), N2 = (int)PH2->nzcount(); - if( (method == CV_COMP_CHISQR) || (method == CV_COMP_CHISQR_ALT) ) + if( (method == cv::HISTCMP_CHISQR) || (method == cv::HISTCMP_CHISQR_ALT) ) { for( i = 0; i < N1; i++, ++it ) { @@ -2267,12 +2269,12 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) const SparseMat::Node* node = it.node(); float v2 = PH2->value(node->idx, (size_t*)&node->hashval); double a = v1 - v2; - double b = (method == CV_COMP_CHISQR) ? v1 : v1 + v2; + double b = (method == cv::HISTCMP_CHISQR) ? v1 : v1 + v2; if( fabs(b) > DBL_EPSILON ) result += a*a/b; } } - else if( method == CV_COMP_CORREL ) + else if( method == cv::HISTCMP_CORREL ) { double s1 = 0, s2 = 0, s11 = 0, s12 = 0, s22 = 0; @@ -2303,7 +2305,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) double denom2 = (s11 - s1*s1*scale)*(s22 - s2*s2*scale); result = std::abs(denom2) > DBL_EPSILON ? num/std::sqrt(denom2) : 1.; } - else if( method == CV_COMP_INTERSECT ) + else if( method == cv::HISTCMP_INTERSECT ) { for( i = 0; i < N1; i++, ++it ) { @@ -2315,7 +2317,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) result += std::min(v1, v2); } } - else if( method == CV_COMP_BHATTACHARYYA ) + else if( method == cv::HISTCMP_BHATTACHARYYA ) { double s1 = 0, s2 = 0; @@ -2340,7 +2342,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) s1 = fabs(s1) > FLT_EPSILON ? 1./std::sqrt(s1) : 1.; result = std::sqrt(std::max(1. - result*s1, 0.)); } - else if( method == CV_COMP_KL_DIV ) + else if( method == cv::HISTCMP_KL_DIV ) { for( i = 0; i < N1; i++, ++it ) { @@ -2356,536 +2358,15 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) else CV_Error( CV_StsBadArg, "Unknown comparison method" ); - if( method == CV_COMP_CHISQR_ALT ) + if( method == cv::HISTCMP_CHISQR_ALT ) result *= 2; return result; } -const int CV_HIST_DEFAULT_TYPE = CV_32F; - -/* Creates new histogram */ -CvHistogram * -cvCreateHist( int dims, int *sizes, CvHistType type, float** ranges, int uniform ) -{ - CvHistogram *hist = 0; - - if( (unsigned)dims > CV_MAX_DIM ) - CV_Error( CV_BadOrder, "Number of dimensions is out of range" ); - - if( !sizes ) - CV_Error( CV_HeaderIsNull, "Null pointer" ); - - hist = (CvHistogram *)cvAlloc( sizeof( CvHistogram )); - hist->type = CV_HIST_MAGIC_VAL + ((int)type & 1); - if (uniform) hist->type|= CV_HIST_UNIFORM_FLAG; - hist->thresh2 = 0; - hist->bins = 0; - if( type == CV_HIST_ARRAY ) - { - hist->bins = cvInitMatNDHeader( &hist->mat, dims, sizes, - CV_HIST_DEFAULT_TYPE ); - cvCreateData( hist->bins ); - } - else if( type == CV_HIST_SPARSE ) - hist->bins = cvCreateSparseMat( dims, sizes, CV_HIST_DEFAULT_TYPE ); - else - CV_Error( CV_StsBadArg, "Invalid histogram type" ); - - if( ranges ) - cvSetHistBinRanges( hist, ranges, uniform ); - - return hist; -} - - -/* Creates histogram wrapping header for given array */ -CV_IMPL CvHistogram* -cvMakeHistHeaderForArray( int dims, int *sizes, CvHistogram *hist, - float *data, float **ranges, int uniform ) -{ - if( !hist ) - CV_Error( CV_StsNullPtr, "Null histogram header pointer" ); - - if( !data ) - CV_Error( CV_StsNullPtr, "Null data pointer" ); - - hist->thresh2 = 0; - hist->type = CV_HIST_MAGIC_VAL; - hist->bins = cvInitMatNDHeader( &hist->mat, dims, sizes, CV_HIST_DEFAULT_TYPE, data ); - - if( ranges ) - { - if( !uniform ) - CV_Error( CV_StsBadArg, "Only uniform bin ranges can be used here " - "(to avoid memory allocation)" ); - cvSetHistBinRanges( hist, ranges, uniform ); - } - - return hist; -} - - -CV_IMPL void -cvReleaseHist( CvHistogram **hist ) -{ - if( !hist ) - CV_Error( CV_StsNullPtr, "" ); - - if( *hist ) - { - CvHistogram* temp = *hist; - - if( !CV_IS_HIST(temp)) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - *hist = 0; - - if( CV_IS_SPARSE_HIST( temp )) - cvReleaseSparseMat( (CvSparseMat**)&temp->bins ); - else - { - cvReleaseData( temp->bins ); - temp->bins = 0; - } - - if( temp->thresh2 ) - cvFree( &temp->thresh2 ); - cvFree( &temp ); - } -} - -CV_IMPL void -cvClearHist( CvHistogram *hist ) -{ - if( !CV_IS_HIST(hist) ) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - cvZero( hist->bins ); -} - - -// Clears histogram bins that are below than threshold -CV_IMPL void -cvThreshHist( CvHistogram* hist, double thresh ) -{ - if( !CV_IS_HIST(hist) ) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - - if( !CV_IS_SPARSE_MAT(hist->bins) ) - { - CvMat mat; - cvGetMat( hist->bins, &mat, 0, 1 ); - cvThreshold( &mat, &mat, thresh, 0, CV_THRESH_TOZERO ); - } - else - { - CvSparseMat* mat = (CvSparseMat*)hist->bins; - CvSparseMatIterator iterator; - CvSparseNode *node; - - for( node = cvInitSparseMatIterator( mat, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - float* val = (float*)CV_NODE_VAL( mat, node ); - if( *val <= thresh ) - *val = 0; - } - } -} - - -// Normalizes histogram (make sum of the histogram bins == factor) -CV_IMPL void -cvNormalizeHist( CvHistogram* hist, double factor ) -{ - double sum = 0; - - if( !CV_IS_HIST(hist) ) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - - if( !CV_IS_SPARSE_HIST(hist) ) - { - CvMat mat; - cvGetMat( hist->bins, &mat, 0, 1 ); - sum = cvSum( &mat ).val[0]; - if( fabs(sum) < DBL_EPSILON ) - sum = 1; - cvScale( &mat, &mat, factor/sum, 0 ); - } - else - { - CvSparseMat* mat = (CvSparseMat*)hist->bins; - CvSparseMatIterator iterator; - CvSparseNode *node; - float scale; - - for( node = cvInitSparseMatIterator( mat, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - sum += *(float*)CV_NODE_VAL(mat,node); - } - - if( fabs(sum) < DBL_EPSILON ) - sum = 1; - scale = (float)(factor/sum); - - for( node = cvInitSparseMatIterator( mat, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - *(float*)CV_NODE_VAL(mat,node) *= scale; - } - } -} - - -// Retrieves histogram global min, max and their positions -CV_IMPL void -cvGetMinMaxHistValue( const CvHistogram* hist, - float *value_min, float* value_max, - int* idx_min, int* idx_max ) -{ - double minVal, maxVal; - int dims, size[CV_MAX_DIM]; - - if( !CV_IS_HIST(hist) ) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - - dims = cvGetDims( hist->bins, size ); - - if( !CV_IS_SPARSE_HIST(hist) ) - { - CvMat mat; - CvPoint minPt = {0, 0}, maxPt = {0, 0}; - - cvGetMat( hist->bins, &mat, 0, 1 ); - cvMinMaxLoc( &mat, &minVal, &maxVal, &minPt, &maxPt ); - - if( dims == 1 ) - { - if( idx_min ) - *idx_min = minPt.y + minPt.x; - if( idx_max ) - *idx_max = maxPt.y + maxPt.x; - } - else if( dims == 2 ) - { - if( idx_min ) - idx_min[0] = minPt.y, idx_min[1] = minPt.x; - if( idx_max ) - idx_max[0] = maxPt.y, idx_max[1] = maxPt.x; - } - else if( idx_min || idx_max ) - { - int imin = minPt.y*mat.cols + minPt.x; - int imax = maxPt.y*mat.cols + maxPt.x; - - for(int i = dims - 1; i >= 0; i-- ) - { - if( idx_min ) - { - int t = imin / size[i]; - idx_min[i] = imin - t*size[i]; - imin = t; - } - - if( idx_max ) - { - int t = imax / size[i]; - idx_max[i] = imax - t*size[i]; - imax = t; - } - } - } - } - else - { - CvSparseMat* mat = (CvSparseMat*)hist->bins; - CvSparseMatIterator iterator; - CvSparseNode *node; - int minv = INT_MAX; - int maxv = INT_MIN; - CvSparseNode* minNode = 0; - CvSparseNode* maxNode = 0; - const int *_idx_min = 0, *_idx_max = 0; - Cv32suf m; - - for( node = cvInitSparseMatIterator( mat, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - int value = *(int*)CV_NODE_VAL(mat,node); - value = CV_TOGGLE_FLT(value); - if( value < minv ) - { - minv = value; - minNode = node; - } - - if( value > maxv ) - { - maxv = value; - maxNode = node; - } - } - - if( minNode ) - { - _idx_min = CV_NODE_IDX(mat,minNode); - _idx_max = CV_NODE_IDX(mat,maxNode); - m.i = CV_TOGGLE_FLT(minv); minVal = m.f; - m.i = CV_TOGGLE_FLT(maxv); maxVal = m.f; - } - else - { - minVal = maxVal = 0; - } - - for(int i = 0; i < dims; i++ ) - { - if( idx_min ) - idx_min[i] = _idx_min ? _idx_min[i] : -1; - if( idx_max ) - idx_max[i] = _idx_max ? _idx_max[i] : -1; - } - } - - if( value_min ) - *value_min = (float)minVal; - - if( value_max ) - *value_max = (float)maxVal; -} - - -// Compares two histograms using one of a few methods -CV_IMPL double -cvCompareHist( const CvHistogram* hist1, - const CvHistogram* hist2, - int method ) -{ - int i; - int size1[CV_MAX_DIM], size2[CV_MAX_DIM], total = 1; - - if( !CV_IS_HIST(hist1) || !CV_IS_HIST(hist2) ) - CV_Error( CV_StsBadArg, "Invalid histogram header[s]" ); - - if( CV_IS_SPARSE_MAT(hist1->bins) != CV_IS_SPARSE_MAT(hist2->bins)) - CV_Error(CV_StsUnmatchedFormats, "One of histograms is sparse and other is not"); - - if( !CV_IS_SPARSE_MAT(hist1->bins) ) - { - cv::Mat H1 = cv::cvarrToMat(hist1->bins); - cv::Mat H2 = cv::cvarrToMat(hist2->bins); - return cv::compareHist(H1, H2, method); - } - - int dims1 = cvGetDims( hist1->bins, size1 ); - int dims2 = cvGetDims( hist2->bins, size2 ); - - if( dims1 != dims2 ) - CV_Error( CV_StsUnmatchedSizes, - "The histograms have different numbers of dimensions" ); - - for( i = 0; i < dims1; i++ ) - { - if( size1[i] != size2[i] ) - CV_Error( CV_StsUnmatchedSizes, "The histograms have different sizes" ); - total *= size1[i]; - } - - double result = 0; - CvSparseMat* mat1 = (CvSparseMat*)(hist1->bins); - CvSparseMat* mat2 = (CvSparseMat*)(hist2->bins); - CvSparseMatIterator iterator; - CvSparseNode *node1, *node2; - - if( mat1->heap->active_count > mat2->heap->active_count && method != CV_COMP_CHISQR && method != CV_COMP_CHISQR_ALT && method != CV_COMP_KL_DIV ) - { - CvSparseMat* t; - CV_SWAP( mat1, mat2, t ); - } - - if( (method == CV_COMP_CHISQR) || (method == CV_COMP_CHISQR_ALT) ) - { - for( node1 = cvInitSparseMatIterator( mat1, &iterator ); - node1 != 0; node1 = cvGetNextSparseNode( &iterator )) - { - double v1 = *(float*)CV_NODE_VAL(mat1,node1); - uchar* node2_data = cvPtrND( mat2, CV_NODE_IDX(mat1,node1), 0, 0, &node1->hashval ); - double v2 = node2_data ? *(float*)node2_data : 0.f; - double a = v1 - v2; - double b = (method == CV_COMP_CHISQR) ? v1 : v1 + v2; - if( fabs(b) > DBL_EPSILON ) - result += a*a/b; - } - } - else if( method == CV_COMP_CORREL ) - { - double s1 = 0, s11 = 0; - double s2 = 0, s22 = 0; - double s12 = 0; - double num, denom2, scale = 1./total; - - for( node1 = cvInitSparseMatIterator( mat1, &iterator ); - node1 != 0; node1 = cvGetNextSparseNode( &iterator )) - { - double v1 = *(float*)CV_NODE_VAL(mat1,node1); - uchar* node2_data = cvPtrND( mat2, CV_NODE_IDX(mat1,node1), - 0, 0, &node1->hashval ); - if( node2_data ) - { - double v2 = *(float*)node2_data; - s12 += v1*v2; - } - s1 += v1; - s11 += v1*v1; - } - - for( node2 = cvInitSparseMatIterator( mat2, &iterator ); - node2 != 0; node2 = cvGetNextSparseNode( &iterator )) - { - double v2 = *(float*)CV_NODE_VAL(mat2,node2); - s2 += v2; - s22 += v2*v2; - } - - num = s12 - s1*s2*scale; - denom2 = (s11 - s1*s1*scale)*(s22 - s2*s2*scale); - result = fabs(denom2) > DBL_EPSILON ? num/sqrt(denom2) : 1; - } - else if( method == CV_COMP_INTERSECT ) - { - for( node1 = cvInitSparseMatIterator( mat1, &iterator ); - node1 != 0; node1 = cvGetNextSparseNode( &iterator )) - { - float v1 = *(float*)CV_NODE_VAL(mat1,node1); - uchar* node2_data = cvPtrND( mat2, CV_NODE_IDX(mat1,node1), - 0, 0, &node1->hashval ); - if( node2_data ) - { - float v2 = *(float*)node2_data; - if( v1 <= v2 ) - result += v1; - else - result += v2; - } - } - } - else if( method == CV_COMP_BHATTACHARYYA ) - { - double s1 = 0, s2 = 0; - - for( node1 = cvInitSparseMatIterator( mat1, &iterator ); - node1 != 0; node1 = cvGetNextSparseNode( &iterator )) - { - double v1 = *(float*)CV_NODE_VAL(mat1,node1); - uchar* node2_data = cvPtrND( mat2, CV_NODE_IDX(mat1,node1), - 0, 0, &node1->hashval ); - s1 += v1; - if( node2_data ) - { - double v2 = *(float*)node2_data; - result += sqrt(v1 * v2); - } - } - - for( node1 = cvInitSparseMatIterator( mat2, &iterator ); - node1 != 0; node1 = cvGetNextSparseNode( &iterator )) - { - double v2 = *(float*)CV_NODE_VAL(mat2,node1); - s2 += v2; - } - - s1 *= s2; - s1 = fabs(s1) > FLT_EPSILON ? 1./sqrt(s1) : 1.; - result = 1. - result*s1; - result = sqrt(MAX(result,0.)); - } - else if( method == CV_COMP_KL_DIV ) - { - cv::SparseMat sH1, sH2; - ((const CvSparseMat*)hist1->bins)->copyToSparseMat(sH1); - ((const CvSparseMat*)hist2->bins)->copyToSparseMat(sH2); - result = cv::compareHist( sH1, sH2, CV_COMP_KL_DIV ); - } - else - CV_Error( CV_StsBadArg, "Unknown comparison method" ); - - if( method == CV_COMP_CHISQR_ALT ) - result *= 2; - - return result; -} - -// copies one histogram to another -CV_IMPL void -cvCopyHist( const CvHistogram* src, CvHistogram** _dst ) -{ - if( !_dst ) - CV_Error( CV_StsNullPtr, "Destination double pointer is NULL" ); - - CvHistogram* dst = *_dst; - - if( !CV_IS_HIST(src) || (dst && !CV_IS_HIST(dst)) ) - CV_Error( CV_StsBadArg, "Invalid histogram header[s]" ); - - bool eq = false; - int size1[CV_MAX_DIM]; - bool is_sparse = CV_IS_SPARSE_MAT(src->bins); - int dims1 = cvGetDims( src->bins, size1 ); - - if( dst && (is_sparse == CV_IS_SPARSE_MAT(dst->bins))) - { - int size2[CV_MAX_DIM]; - int dims2 = cvGetDims( dst->bins, size2 ); - - if( dims1 == dims2 ) - { - int i; - - for( i = 0; i < dims1; i++ ) - { - if( size1[i] != size2[i] ) - break; - } - - eq = (i == dims1); - } - } - - if( !eq ) - { - cvReleaseHist( _dst ); - dst = cvCreateHist( dims1, size1, !is_sparse ? CV_HIST_ARRAY : CV_HIST_SPARSE, 0, 0 ); - *_dst = dst; - } - - if( CV_HIST_HAS_RANGES( src )) - { - float* ranges[CV_MAX_DIM]; - float** thresh = 0; - - if( CV_IS_UNIFORM_HIST( src )) - { - for( int i = 0; i < dims1; i++ ) - ranges[i] = (float*)src->thresh[i]; - - thresh = ranges; - } - else - { - thresh = src->thresh2; - } - - cvSetHistBinRanges( dst, thresh, CV_IS_UNIFORM_HIST(src)); - } - - cvCopy( src->bins, dst->bins ); -} - - // Sets a value range for every histogram bin -CV_IMPL void -cvSetHistBinRanges( CvHistogram* hist, float** ranges, int uniform ) +void cvSetHistBinRanges( CvHistogram* hist, float** ranges, int uniform ) { int dims, size[CV_MAX_DIM], total = 0; int i, j; @@ -2949,234 +2430,6 @@ cvSetHistBinRanges( CvHistogram* hist, float** ranges, int uniform ) } -CV_IMPL void -cvCalcArrHist( CvArr** img, CvHistogram* hist, int accumulate, const CvArr* mask ) -{ - if( !CV_IS_HIST(hist)) - CV_Error( CV_StsBadArg, "Bad histogram pointer" ); - - if( !img ) - CV_Error( CV_StsNullPtr, "Null double array pointer" ); - - int size[CV_MAX_DIM]; - int i, dims = cvGetDims( hist->bins, size); - bool uniform = CV_IS_UNIFORM_HIST(hist); - - std::vector images(dims); - for( i = 0; i < dims; i++ ) - images[i] = cv::cvarrToMat(img[i]); - - cv::Mat _mask; - if( mask ) - _mask = cv::cvarrToMat(mask); - - const float* uranges[CV_MAX_DIM] = {0}; - const float** ranges = 0; - - if( hist->type & CV_HIST_RANGES_FLAG ) - { - ranges = (const float**)hist->thresh2; - if( uniform ) - { - for( i = 0; i < dims; i++ ) - uranges[i] = &hist->thresh[i][0]; - ranges = uranges; - } - } - - if( !CV_IS_SPARSE_HIST(hist) ) - { - cv::Mat H = cv::cvarrToMat(hist->bins); - cv::calcHist( &images[0], (int)images.size(), 0, _mask, - H, cvGetDims(hist->bins), H.size, ranges, uniform, accumulate != 0 ); - } - else - { - CvSparseMat* sparsemat = (CvSparseMat*)hist->bins; - - if( !accumulate ) - cvZero( hist->bins ); - cv::SparseMat sH; - sparsemat->copyToSparseMat(sH); - cv::calcHist( &images[0], (int)images.size(), 0, _mask, sH, sH.dims(), - sH.dims() > 0 ? sH.hdr->size : 0, ranges, uniform, accumulate != 0, true ); - - if( accumulate ) - cvZero( sparsemat ); - - cv::SparseMatConstIterator it = sH.begin(); - int nz = (int)sH.nzcount(); - for( i = 0; i < nz; i++, ++it ) - { - CV_Assert(it.ptr != NULL); - *(float*)cvPtrND(sparsemat, it.node()->idx, 0, -2) = (float)*(const int*)it.ptr; - } - } -} - - -CV_IMPL void -cvCalcArrBackProject( CvArr** img, CvArr* dst, const CvHistogram* hist ) -{ - if( !CV_IS_HIST(hist)) - CV_Error( CV_StsBadArg, "Bad histogram pointer" ); - - if( !img ) - CV_Error( CV_StsNullPtr, "Null double array pointer" ); - - int size[CV_MAX_DIM]; - int i, dims = cvGetDims( hist->bins, size ); - - bool uniform = CV_IS_UNIFORM_HIST(hist); - const float* uranges[CV_MAX_DIM] = {0}; - const float** ranges = 0; - - if( hist->type & CV_HIST_RANGES_FLAG ) - { - ranges = (const float**)hist->thresh2; - if( uniform ) - { - for( i = 0; i < dims; i++ ) - uranges[i] = &hist->thresh[i][0]; - ranges = uranges; - } - } - - std::vector images(dims); - for( i = 0; i < dims; i++ ) - images[i] = cv::cvarrToMat(img[i]); - - cv::Mat _dst = cv::cvarrToMat(dst); - - CV_Assert( _dst.size() == images[0].size() && _dst.depth() == images[0].depth() ); - - if( !CV_IS_SPARSE_HIST(hist) ) - { - cv::Mat H = cv::cvarrToMat(hist->bins); - cv::calcBackProject( &images[0], (int)images.size(), - 0, H, _dst, ranges, 1, uniform ); - } - else - { - cv::SparseMat sH; - ((const CvSparseMat*)hist->bins)->copyToSparseMat(sH); - cv::calcBackProject( &images[0], (int)images.size(), - 0, sH, _dst, ranges, 1, uniform ); - } -} - - -////////////////////// B A C K P R O J E C T P A T C H ///////////////////////// - -CV_IMPL void -cvCalcArrBackProjectPatch( CvArr** arr, CvArr* dst, CvSize patch_size, CvHistogram* hist, - int method, double norm_factor ) -{ - CvHistogram* model = 0; - - IplImage imgstub[CV_MAX_DIM], *img[CV_MAX_DIM]; - IplROI roi; - CvMat dststub, *dstmat; - int i, dims; - int x, y; - cv::Size size; - - if( !CV_IS_HIST(hist)) - CV_Error( CV_StsBadArg, "Bad histogram pointer" ); - - if( !arr ) - CV_Error( CV_StsNullPtr, "Null double array pointer" ); - - if( norm_factor <= 0 ) - CV_Error( CV_StsOutOfRange, - "Bad normalization factor (set it to 1.0 if unsure)" ); - - if( patch_size.width <= 0 || patch_size.height <= 0 ) - CV_Error( CV_StsBadSize, "The patch width and height must be positive" ); - - dims = cvGetDims( hist->bins ); - if (dims < 1) - CV_Error( CV_StsOutOfRange, "Invalid number of dimensions"); - cvNormalizeHist( hist, norm_factor ); - - for( i = 0; i < dims; i++ ) - { - CvMat stub, *mat; - mat = cvGetMat( arr[i], &stub, 0, 0 ); - img[i] = cvGetImage( mat, &imgstub[i] ); - img[i]->roi = &roi; - } - - dstmat = cvGetMat( dst, &dststub, 0, 0 ); - if( CV_MAT_TYPE( dstmat->type ) != CV_32FC1 ) - CV_Error( CV_StsUnsupportedFormat, "Resultant image must have 32fC1 type" ); - - if( dstmat->cols != img[0]->width - patch_size.width + 1 || - dstmat->rows != img[0]->height - patch_size.height + 1 ) - CV_Error( CV_StsUnmatchedSizes, - "The output map must be (W-w+1 x H-h+1), " - "where the input images are (W x H) each and the patch is (w x h)" ); - - cvCopyHist( hist, &model ); - - size = cvGetMatSize(dstmat); - roi.coi = 0; - roi.width = patch_size.width; - roi.height = patch_size.height; - - for( y = 0; y < size.height; y++ ) - { - for( x = 0; x < size.width; x++ ) - { - double result; - roi.xOffset = x; - roi.yOffset = y; - - cvCalcHist( img, model ); - cvNormalizeHist( model, norm_factor ); - result = cvCompareHist( model, hist, method ); - CV_MAT_ELEM( *dstmat, float, y, x ) = (float)result; - } - } - - cvReleaseHist( &model ); -} - - -// Calculates Bayes probabilistic histograms -CV_IMPL void -cvCalcBayesianProb( CvHistogram** src, int count, CvHistogram** dst ) -{ - int i; - - if( !src || !dst ) - CV_Error( CV_StsNullPtr, "NULL histogram array pointer" ); - - if( count < 2 ) - CV_Error( CV_StsOutOfRange, "Too small number of histograms" ); - - for( i = 0; i < count; i++ ) - { - if( !CV_IS_HIST(src[i]) || !CV_IS_HIST(dst[i]) ) - CV_Error( CV_StsBadArg, "Invalid histogram header" ); - - if( !CV_IS_MATND(src[i]->bins) || !CV_IS_MATND(dst[i]->bins) ) - CV_Error( CV_StsBadArg, "The function supports dense histograms only" ); - } - - cvZero( dst[0]->bins ); - // dst[0] = src[0] + ... + src[count-1] - for( i = 0; i < count; i++ ) - cvAdd( src[i]->bins, dst[0]->bins, dst[0]->bins ); - - cvDiv( 0, dst[0]->bins, dst[0]->bins ); - - // dst[i] = src[i]*(1/dst[0]) - for( i = count - 1; i >= 0; i-- ) - cvMul( src[i]->bins, dst[0]->bins, dst[i]->bins ); -} - - class EqualizeHistCalcHist_Invoker : public cv::ParallelLoopBody { public: diff --git a/modules/imgproc/src/hough.cpp b/modules/imgproc/src/hough.cpp index 360534f695..f848cd3a39 100644 --- a/modules/imgproc/src/hough.cpp +++ b/modules/imgproc/src/hough.cpp @@ -2320,7 +2320,7 @@ static void HoughCircles( InputArray _image, OutputArray _circles, } break; default: - CV_Error( Error::StsBadArg, "Unrecognized method id. Actually only CV_HOUGH_GRADIENT is supported." ); + CV_Error( Error::StsBadArg, "Unrecognized method id. Actually only cv::HOUGH_GRADIENT is supported." ); } } @@ -2332,161 +2332,3 @@ void HoughCircles( InputArray _image, OutputArray _circles, HoughCircles(_image, _circles, method, dp, minDist, param1, param2, minRadius, maxRadius, -1, 3); } } // \namespace cv - - -/* Wrapper function for standard hough transform */ -CV_IMPL CvSeq* -cvHoughLines2( CvArr* src_image, void* lineStorage, int method, - double rho, double theta, int threshold, - double param1, double param2, - double min_theta, double max_theta ) -{ - cv::Mat image = cv::cvarrToMat(src_image); - std::vector l2; - std::vector l4; - - CvMat* mat = 0; - CvSeq* lines = 0; - CvSeq lines_header; - CvSeqBlock lines_block; - int lineType, elemSize; - int linesMax = INT_MAX; - int iparam1, iparam2; - - if( !lineStorage ) - CV_Error(cv::Error::StsNullPtr, "NULL destination" ); - - if( rho <= 0 || theta <= 0 || threshold <= 0 ) - CV_Error( cv::Error::StsOutOfRange, "rho, theta and threshold must be positive" ); - - if( method != CV_HOUGH_PROBABILISTIC ) - { - lineType = CV_32FC2; - elemSize = sizeof(float)*2; - } - else - { - lineType = CV_32SC4; - elemSize = sizeof(int)*4; - } - - bool isStorage = isStorageOrMat(lineStorage); - - if( isStorage ) - { - lines = cvCreateSeq( lineType, sizeof(CvSeq), elemSize, (CvMemStorage*)lineStorage ); - } - else - { - mat = (CvMat*)lineStorage; - - if( !CV_IS_MAT_CONT( mat->type ) || (mat->rows != 1 && mat->cols != 1) ) - CV_Error( CV_StsBadArg, - "The destination matrix should be continuous and have a single row or a single column" ); - - if( CV_MAT_TYPE( mat->type ) != lineType ) - CV_Error( CV_StsBadArg, - "The destination matrix data type is inappropriate, see the manual" ); - - lines = cvMakeSeqHeaderForArray( lineType, sizeof(CvSeq), elemSize, mat->data.ptr, - mat->rows + mat->cols - 1, &lines_header, &lines_block ); - linesMax = lines->total; - cvClearSeq( lines ); - } - - iparam1 = cvRound(param1); - iparam2 = cvRound(param2); - - switch( method ) - { - case CV_HOUGH_STANDARD: - HoughLinesStandard( image, l2, CV_32FC2, (float)rho, - (float)theta, threshold, linesMax, min_theta, max_theta ); - break; - case CV_HOUGH_MULTI_SCALE: - HoughLinesSDiv( image, l2, CV_32FC2, (float)rho, (float)theta, - threshold, iparam1, iparam2, linesMax, min_theta, max_theta ); - break; - case CV_HOUGH_PROBABILISTIC: - HoughLinesProbabilistic( image, (float)rho, (float)theta, - threshold, iparam1, iparam2, l4, linesMax ); - break; - default: - CV_Error( CV_StsBadArg, "Unrecognized method id" ); - } - - int nlines = (int)(l2.size() + l4.size()); - - if( !isStorage ) - { - if( mat->cols > mat->rows ) - mat->cols = nlines; - else - mat->rows = nlines; - } - - if( nlines ) - { - cv::Mat lx = method == CV_HOUGH_STANDARD || method == CV_HOUGH_MULTI_SCALE ? - cv::Mat(nlines, 1, CV_32FC2, &l2[0]) : cv::Mat(nlines, 1, CV_32SC4, &l4[0]); - - if (isStorage) - { - cvSeqPushMulti(lines, lx.ptr(), nlines); - } - else - { - cv::Mat dst(nlines, 1, lx.type(), mat->data.ptr); - lx.copyTo(dst); - } - } - - if( isStorage ) - return lines; - return 0; -} - - -CV_IMPL CvSeq* -cvHoughCircles( CvArr* src_image, void* circle_storage, - int method, double dp, double min_dist, - double param1, double param2, - int min_radius, int max_radius ) -{ - CvSeq* circles = NULL; - int circles_max = INT_MAX; - cv::Mat src = cv::cvarrToMat(src_image), circles_mat; - - if( !circle_storage ) - CV_Error( CV_StsNullPtr, "NULL destination" ); - - bool isStorage = isStorageOrMat(circle_storage); - - if(isStorage) - { - circles = cvCreateSeq( CV_32FC3, sizeof(CvSeq), - sizeof(float)*3, (CvMemStorage*)circle_storage ); - } - else - { - CvSeq circles_header; - CvSeqBlock circles_block; - CvMat *mat = (CvMat*)circle_storage; - - if( !CV_IS_MAT_CONT( mat->type ) || (mat->rows != 1 && mat->cols != 1) || - CV_MAT_TYPE(mat->type) != CV_32FC3 ) - CV_Error( CV_StsBadArg, - "The destination matrix should be continuous and have a single row or a single column" ); - - circles = cvMakeSeqHeaderForArray( CV_32FC3, sizeof(CvSeq), sizeof(float)*3, - mat->data.ptr, mat->rows + mat->cols - 1, &circles_header, &circles_block ); - circles_max = circles->total; - cvClearSeq( circles ); - } - - cv::HoughCircles(src, circles_mat, method, dp, min_dist, param1, param2, min_radius, max_radius, circles_max, 3); - cvSeqPushMulti(circles, circles_mat.data, (int)circles_mat.total()); - return circles; -} - -/* End of file. */ diff --git a/modules/imgproc/src/imgwarp.cpp b/modules/imgproc/src/imgwarp.cpp index d3826bd73f..25107328d7 100644 --- a/modules/imgproc/src/imgwarp.cpp +++ b/modules/imgproc/src/imgwarp.cpp @@ -1395,7 +1395,7 @@ static bool ocl_linearPolar(InputArray _src, OutputArray _dst, size_t h = dsize.height; String buildOptions; unsigned mem_size = 32; - if (flags & CV_WARP_INVERSE_MAP) + if (flags & cv::WARP_INVERSE_MAP) { buildOptions = "-D InverseMap"; } @@ -1410,7 +1410,7 @@ static bool ocl_linearPolar(InputArray _src, OutputArray _dst, ocl::KernelArg ocl_cp_sp = ocl::KernelArg::PtrReadWrite(cp_sp); ocl::KernelArg ocl_r = ocl::KernelArg::PtrReadWrite(r); - if (!(flags & CV_WARP_INVERSE_MAP)) + if (!(flags & cv::WARP_INVERSE_MAP)) { @@ -1441,7 +1441,7 @@ static bool ocl_linearPolar(InputArray _src, OutputArray _dst, size_t globalThreads[2] = { (size_t)dsize.width , (size_t)dsize.height }; size_t localThreads[2] = { mem_size , mem_size }; k.run(2, globalThreads, localThreads, false); - remap(src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); + remap(src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & cv::WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); return true; } static bool ocl_logPolar(InputArray _src, OutputArray _dst, @@ -1464,7 +1464,7 @@ static bool ocl_logPolar(InputArray _src, OutputArray _dst, size_t h = dsize.height; String buildOptions; unsigned mem_size = 32; - if (flags & CV_WARP_INVERSE_MAP) + if (flags & cv::WARP_INVERSE_MAP) { buildOptions = "-D InverseMap"; } @@ -1481,7 +1481,7 @@ static bool ocl_logPolar(InputArray _src, OutputArray _dst, ocl::KernelArg ocl_cp_sp = ocl::KernelArg::PtrReadWrite(cp_sp); ocl::KernelArg ocl_r = ocl::KernelArg::PtrReadWrite(r); - if (!(flags & CV_WARP_INVERSE_MAP)) + if (!(flags & cv::WARP_INVERSE_MAP)) { @@ -1512,7 +1512,7 @@ static bool ocl_logPolar(InputArray _src, OutputArray _dst, size_t globalThreads[2] = { (size_t)dsize.width , (size_t)dsize.height }; size_t localThreads[2] = { mem_size , mem_size }; k.run(2, globalThreads, localThreads, false); - remap(src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); + remap(src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & cv::WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); return true; } #endif @@ -3400,45 +3400,6 @@ cv::Mat cv::getAffineTransform(InputArray _src, InputArray _dst) return getAffineTransform((const Point2f*)src.data, (const Point2f*)dst.data); } -CV_IMPL void -cvWarpAffine( const CvArr* srcarr, CvArr* dstarr, const CvMat* marr, - int flags, CvScalar fillval ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - cv::Mat matrix = cv::cvarrToMat(marr); - CV_Assert( src.type() == dst.type() ); - cv::warpAffine( src, dst, matrix, dst.size(), flags, - (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT, - fillval ); -} - -CV_IMPL void -cvWarpPerspective( const CvArr* srcarr, CvArr* dstarr, const CvMat* marr, - int flags, CvScalar fillval ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - cv::Mat matrix = cv::cvarrToMat(marr); - CV_Assert( src.type() == dst.type() ); - cv::warpPerspective( src, dst, matrix, dst.size(), flags, - (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT, - fillval ); -} - - -CV_IMPL CvMat* -cvGetPerspectiveTransform( const CvPoint2D32f* src, - const CvPoint2D32f* dst, - CvMat* matrix ) -{ - cv::Mat M0 = cv::cvarrToMat(matrix), - M = cv::getPerspectiveTransform((const cv::Point2f*)src, (const cv::Point2f*)dst); - CV_Assert( M.size() == M0.size() ); - M.convertTo(M0, M0.type()); - return matrix; -} - - - /**************************************************************************************** PkLab.net 2018 based on cv::linearPolar from OpenCV by J.L. Blanco, Apr 2009 ****************************************************************************************/ @@ -3462,7 +3423,7 @@ void cv::warpPolar(InputArray _src, OutputArray _dst, Size dsize, mapy.create(dsize, CV_32F); bool semiLog = (flags & WARP_POLAR_LOG) != 0; - if (!(flags & CV_WARP_INVERSE_MAP)) + if (!(flags & cv::WARP_INVERSE_MAP)) { CV_Assert(!dsize.empty()); double Kangle = CV_2PI / dsize.height; @@ -3502,7 +3463,7 @@ void cv::warpPolar(InputArray _src, OutputArray _dst, Size dsize, my[rho] = (float)y; } } - remap(_src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); + remap(_src, _dst, mapx, mapy, flags & cv::INTER_MAX, (flags & cv::WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); } else { @@ -3555,7 +3516,7 @@ void cv::warpPolar(InputArray _src, OutputArray _dst, Size dsize, } } remap(src, _dst, mapx, mapy, flags & cv::INTER_MAX, - (flags & CV_WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); + (flags & cv::WARP_FILL_OUTLIERS) ? cv::BORDER_CONSTANT : cv::BORDER_TRANSPARENT); } } diff --git a/modules/imgproc/src/linefit.cpp b/modules/imgproc/src/linefit.cpp index 3c769ab8a6..ca1db9c7d8 100644 --- a/modules/imgproc/src/linefit.cpp +++ b/modules/imgproc/src/linefit.cpp @@ -331,26 +331,26 @@ static void fitLine2D( const Point2f * points, int count, int dist, switch (dist) { - case CV_DIST_L2: + case cv::DIST_L2: return fitLine2D_wods( points, count, 0, line ); - case CV_DIST_L1: + case cv::DIST_L1: calc_weights = weightL1; break; - case CV_DIST_L12: + case cv::DIST_L12: calc_weights = weightL12; break; - case CV_DIST_FAIR: + case cv::DIST_FAIR: calc_weights_param = weightFair; break; - case CV_DIST_WELSCH: + case cv::DIST_WELSCH: calc_weights_param = weightWelsch; break; - case CV_DIST_HUBER: + case cv::DIST_HUBER: calc_weights_param = weightHuber; break; @@ -475,26 +475,26 @@ static void fitLine3D( Point3f * points, int count, int dist, switch (dist) { - case CV_DIST_L2: + case cv::DIST_L2: return fitLine3D_wods( points, count, 0, line ); - case CV_DIST_L1: + case cv::DIST_L1: calc_weights = weightL1; break; - case CV_DIST_L12: + case cv::DIST_L12: calc_weights = weightL12; break; - case CV_DIST_FAIR: + case cv::DIST_FAIR: calc_weights_param = weightFair; break; - case CV_DIST_WELSCH: + case cv::DIST_WELSCH: calc_weights_param = weightWelsch; break; - case CV_DIST_HUBER: + case cv::DIST_HUBER: calc_weights_param = weightHuber; break; diff --git a/modules/imgproc/src/moments.cpp b/modules/imgproc/src/moments.cpp index 204c8654af..964e78cfb1 100644 --- a/modules/imgproc/src/moments.cpp +++ b/modules/imgproc/src/moments.cpp @@ -709,99 +709,3 @@ void cv::HuMoments( const Moments& m, OutputArray _hu ) CV_Assert( hu.isContinuous() ); HuMoments(m, hu.ptr()); } - - -CV_IMPL void cvMoments( const CvArr* arr, CvMoments* moments, int binary ) -{ - const IplImage* img = (const IplImage*)arr; - cv::Mat src; - if( CV_IS_IMAGE(arr) && img->roi && img->roi->coi > 0 ) - cv::extractImageCOI(arr, src, img->roi->coi-1); - else - src = cv::cvarrToMat(arr); - cv::Moments m = cv::moments(src, binary != 0); - CV_Assert( moments != 0 ); - *moments = cvMoments(m); -} - - -CV_IMPL double cvGetSpatialMoment( CvMoments * moments, int x_order, int y_order ) -{ - int order = x_order + y_order; - - if( !moments ) - CV_Error( CV_StsNullPtr, "" ); - if( (x_order | y_order) < 0 || order > 3 ) - CV_Error( CV_StsOutOfRange, "" ); - - return (&(moments->m00))[order + (order >> 1) + (order > 2) * 2 + y_order]; -} - - -CV_IMPL double cvGetCentralMoment( CvMoments * moments, int x_order, int y_order ) -{ - int order = x_order + y_order; - - if( !moments ) - CV_Error( CV_StsNullPtr, "" ); - if( (x_order | y_order) < 0 || order > 3 ) - CV_Error( CV_StsOutOfRange, "" ); - - return order >= 2 ? (&(moments->m00))[4 + order * 3 + y_order] : - order == 0 ? moments->m00 : 0; -} - - -CV_IMPL double cvGetNormalizedCentralMoment( CvMoments * moments, int x_order, int y_order ) -{ - int order = x_order + y_order; - - double mu = cvGetCentralMoment( moments, x_order, y_order ); - double m00s = moments->inv_sqrt_m00; - - while( --order >= 0 ) - mu *= m00s; - return mu * m00s * m00s; -} - - -CV_IMPL void cvGetHuMoments( CvMoments * mState, CvHuMoments * HuState ) -{ - if( !mState || !HuState ) - CV_Error( CV_StsNullPtr, "" ); - - double m00s = mState->inv_sqrt_m00, m00 = m00s * m00s, s2 = m00 * m00, s3 = s2 * m00s; - - double nu20 = mState->mu20 * s2, - nu11 = mState->mu11 * s2, - nu02 = mState->mu02 * s2, - nu30 = mState->mu30 * s3, - nu21 = mState->mu21 * s3, nu12 = mState->mu12 * s3, nu03 = mState->mu03 * s3; - - double t0 = nu30 + nu12; - double t1 = nu21 + nu03; - - double q0 = t0 * t0, q1 = t1 * t1; - - double n4 = 4 * nu11; - double s = nu20 + nu02; - double d = nu20 - nu02; - - HuState->hu1 = s; - HuState->hu2 = d * d + n4 * nu11; - HuState->hu4 = q0 + q1; - HuState->hu6 = d * (q0 - q1) + n4 * t0 * t1; - - t0 *= q0 - 3 * q1; - t1 *= 3 * q0 - q1; - - q0 = nu30 - 3 * nu12; - q1 = 3 * nu21 - nu03; - - HuState->hu3 = q0 * q0 + q1 * q1; - HuState->hu5 = q0 * t0 + q1 * t1; - HuState->hu7 = q1 * t0 - q0 * t1; -} - - -/* End of file. */ diff --git a/modules/imgproc/src/morph.dispatch.cpp b/modules/imgproc/src/morph.dispatch.cpp index 45ae3994d9..748c5114ca 100644 --- a/modules/imgproc/src/morph.dispatch.cpp +++ b/modules/imgproc/src/morph.dispatch.cpp @@ -1254,112 +1254,3 @@ void morphologyEx( InputArray _src, OutputArray _dst, int op, } } // namespace cv - -CV_IMPL IplConvKernel * -cvCreateStructuringElementEx( int cols, int rows, - int anchorX, int anchorY, - int shape, int *values ) -{ - cv::Size ksize = cv::Size(cols, rows); - cv::Point anchor = cv::Point(anchorX, anchorY); - CV_Assert( cols > 0 && rows > 0 && anchor.inside(cv::Rect(0,0,cols,rows)) && - (shape != CV_SHAPE_CUSTOM || values != 0)); - - int i, size = rows * cols; - int element_size = sizeof(IplConvKernel) + size*sizeof(int); - IplConvKernel *element = (IplConvKernel*)cvAlloc(element_size + 32); - - element->nCols = cols; - element->nRows = rows; - element->anchorX = anchorX; - element->anchorY = anchorY; - element->nShiftR = shape < CV_SHAPE_ELLIPSE ? shape : CV_SHAPE_CUSTOM; - element->values = (int*)(element + 1); - - if( shape == CV_SHAPE_CUSTOM ) - { - for( i = 0; i < size; i++ ) - element->values[i] = values[i]; - } - else - { - cv::Mat elem = cv::getStructuringElement(shape, ksize, anchor); - for( i = 0; i < size; i++ ) - element->values[i] = elem.ptr()[i]; - } - - return element; -} - - -CV_IMPL void -cvReleaseStructuringElement( IplConvKernel ** element ) -{ - if( !element ) - CV_Error( CV_StsNullPtr, "" ); - cvFree( element ); -} - - -static void convertConvKernel( const IplConvKernel* src, cv::Mat& dst, cv::Point& anchor ) -{ - if(!src) - { - anchor = cv::Point(1,1); - dst.release(); - return; - } - anchor = cv::Point(src->anchorX, src->anchorY); - dst.create(src->nRows, src->nCols, CV_8U); - - int i, size = src->nRows*src->nCols; - for( i = 0; i < size; i++ ) - dst.ptr()[i] = (uchar)(src->values[i] != 0); -} - - -CV_IMPL void -cvErode( const CvArr* srcarr, CvArr* dstarr, IplConvKernel* element, int iterations ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), kernel; - CV_Assert( src.size() == dst.size() && src.type() == dst.type() ); - cv::Point anchor; - convertConvKernel( element, kernel, anchor ); - cv::erode( src, dst, kernel, anchor, iterations, cv::BORDER_REPLICATE ); -} - - -CV_IMPL void -cvDilate( const CvArr* srcarr, CvArr* dstarr, IplConvKernel* element, int iterations ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), kernel; - CV_Assert( src.size() == dst.size() && src.type() == dst.type() ); - cv::Point anchor; - convertConvKernel( element, kernel, anchor ); - cv::dilate( src, dst, kernel, anchor, iterations, cv::BORDER_REPLICATE ); -} - - -CV_IMPL void -cvMorphologyEx( const void* srcarr, void* dstarr, void*, - IplConvKernel* element, int op, int iterations ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), kernel; - CV_Assert( src.size() == dst.size() && src.type() == dst.type() ); - cv::Point anchor; - IplConvKernel* temp_element = NULL; - if (!element) - { - temp_element = cvCreateStructuringElementEx(3, 3, 1, 1, CV_SHAPE_RECT); - } else { - temp_element = element; - } - convertConvKernel( temp_element, kernel, anchor ); - if (!element) - { - cvReleaseStructuringElement(&temp_element); - } - cv::morphologyEx( src, dst, op, kernel, anchor, iterations, cv::BORDER_REPLICATE ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/pyramids.cpp b/modules/imgproc/src/pyramids.cpp index 12d7d29d76..c31c26c38f 100644 --- a/modules/imgproc/src/pyramids.cpp +++ b/modules/imgproc/src/pyramids.cpp @@ -1549,21 +1549,3 @@ void cv::buildPyramid( InputArray _src, OutputArrayOfArrays _dst, int maxlevel, for( ; i <= maxlevel; i++ ) pyrDown( _dst.getMatRef(i-1), _dst.getMatRef(i), Size(), borderType ); } - -CV_IMPL void cvPyrDown( const void* srcarr, void* dstarr, int _filter ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( _filter == CV_GAUSSIAN_5x5 && src.type() == dst.type()); - cv::pyrDown( src, dst, dst.size() ); -} - -CV_IMPL void cvPyrUp( const void* srcarr, void* dstarr, int _filter ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - - CV_Assert( _filter == CV_GAUSSIAN_5x5 && src.type() == dst.type()); - cv::pyrUp( src, dst, dst.size() ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/resize.cpp b/modules/imgproc/src/resize.cpp index 90a05085e3..d634f1cc70 100644 --- a/modules/imgproc/src/resize.cpp +++ b/modules/imgproc/src/resize.cpp @@ -4088,15 +4088,3 @@ void cv::resize( InputArray _src, OutputArray _dst, Size dsize, hal::resize(src.type(), src.data, src.step, src.cols, src.rows, dst.data, dst.step, dst.cols, dst.rows, inv_scale_x, inv_scale_y, interpolation); } - - -CV_IMPL void -cvResize( const CvArr* srcarr, CvArr* dstarr, int method ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); - CV_Assert( src.type() == dst.type() ); - cv::resize( src, dst, dst.size(), (double)dst.cols/src.cols, - (double)dst.rows/src.rows, method ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/samplers.cpp b/modules/imgproc/src/samplers.cpp index dd4c448e37..d741017407 100644 --- a/modules/imgproc/src/samplers.cpp +++ b/modules/imgproc/src/samplers.cpp @@ -267,98 +267,6 @@ static void getRectSubPix_8u32f } } -static void -getQuadrangleSubPix_8u32f_CnR( const uchar* src, size_t src_step, Size src_size, - float* dst, size_t dst_step, Size win_size, - const double *matrix, int cn ) -{ - int x, y, k; - double A11 = matrix[0], A12 = matrix[1], A13 = matrix[2]; - double A21 = matrix[3], A22 = matrix[4], A23 = matrix[5]; - - src_step /= sizeof(src[0]); - dst_step /= sizeof(dst[0]); - - for( y = 0; y < win_size.height; y++, dst += dst_step ) - { - double xs = A12*y + A13; - double ys = A22*y + A23; - double xe = A11*(win_size.width-1) + A12*y + A13; - double ye = A21*(win_size.width-1) + A22*y + A23; - - if( (unsigned)(cvFloor(xs)-1) < (unsigned)(src_size.width - 3) && - (unsigned)(cvFloor(ys)-1) < (unsigned)(src_size.height - 3) && - (unsigned)(cvFloor(xe)-1) < (unsigned)(src_size.width - 3) && - (unsigned)(cvFloor(ye)-1) < (unsigned)(src_size.height - 3)) - { - for( x = 0; x < win_size.width; x++ ) - { - int ixs = cvFloor( xs ); - int iys = cvFloor( ys ); - const uchar *ptr = src + src_step*iys; - float a = (float)(xs - ixs), b = (float)(ys - iys), a1 = 1.f - a, b1 = 1.f - b; - float w00 = a1*b1, w01 = a*b1, w10 = a1*b, w11 = a*b; - xs += A11; - ys += A21; - - if( cn == 1 ) - { - ptr += ixs; - dst[x] = ptr[0]*w00 + ptr[1]*w01 + ptr[src_step]*w10 + ptr[src_step+1]*w11; - } - else if( cn == 3 ) - { - ptr += ixs*3; - float t0 = ptr[0]*w00 + ptr[3]*w01 + ptr[src_step]*w10 + ptr[src_step+3]*w11; - float t1 = ptr[1]*w00 + ptr[4]*w01 + ptr[src_step+1]*w10 + ptr[src_step+4]*w11; - float t2 = ptr[2]*w00 + ptr[5]*w01 + ptr[src_step+2]*w10 + ptr[src_step+5]*w11; - - dst[x*3] = t0; - dst[x*3+1] = t1; - dst[x*3+2] = t2; - } - else - { - ptr += ixs*cn; - for( k = 0; k < cn; k++ ) - dst[x*cn+k] = ptr[k]*w00 + ptr[k+cn]*w01 + - ptr[src_step+k]*w10 + ptr[src_step+k+cn]*w11; - } - } - } - else - { - for( x = 0; x < win_size.width; x++ ) - { - int ixs = cvFloor( xs ), iys = cvFloor( ys ); - float a = (float)(xs - ixs), b = (float)(ys - iys), a1 = 1.f - a, b1 = 1.f - b; - float w00 = a1*b1, w01 = a*b1, w10 = a1*b, w11 = a*b; - const uchar *ptr0, *ptr1; - xs += A11; ys += A21; - - if( (unsigned)iys < (unsigned)(src_size.height-1) ) - ptr0 = src + src_step*iys, ptr1 = ptr0 + src_step; - else - ptr0 = ptr1 = src + (iys < 0 ? 0 : src_size.height-1)*src_step; - - if( (unsigned)ixs < (unsigned)(src_size.width-1) ) - { - ptr0 += ixs*cn; ptr1 += ixs*cn; - for( k = 0; k < cn; k++ ) - dst[x*cn + k] = ptr0[k]*w00 + ptr0[k+cn]*w01 + ptr1[k]*w10 + ptr1[k+cn]*w11; - } - else - { - ixs = ixs < 0 ? 0 : src_size.width - 1; - ptr0 += ixs*cn; ptr1 += ixs*cn; - for( k = 0; k < cn; k++ ) - dst[x*cn + k] = ptr0[k]*b1 + ptr1[k]*b; - } - } - } - } -} - } @@ -419,37 +327,3 @@ void cv::getRectSubPix( InputArray _image, Size patchSize, Point2f center, else CV_Error( CV_StsUnsupportedFormat, "Unsupported combination of input and output formats"); } - - -CV_IMPL void -cvGetQuadrangleSubPix( const void* srcarr, void* dstarr, const CvMat* mat ) -{ - const cv::Mat src = cv::cvarrToMat(srcarr), m = cv::cvarrToMat(mat); - cv::Mat dst = cv::cvarrToMat(dstarr); - - CV_Assert( src.channels() == dst.channels() ); - - cv::Size win_size = dst.size(); - double matrix[6] = {0}; - cv::Mat M(2, 3, CV_64F, matrix); - m.convertTo(M, CV_64F); - double dx = (win_size.width - 1)*0.5; - double dy = (win_size.height - 1)*0.5; - matrix[2] -= matrix[0]*dx + matrix[1]*dy; - matrix[5] -= matrix[3]*dx + matrix[4]*dy; - - if( src.depth() == CV_8U && dst.depth() == CV_32F ) - cv::getQuadrangleSubPix_8u32f_CnR( src.ptr(), src.step, src.size(), - dst.ptr(), dst.step, dst.size(), - matrix, src.channels()); - else - { - CV_Assert( src.depth() == dst.depth() ); - cv::warpAffine(src, dst, M, dst.size(), - cv::INTER_LINEAR + cv::WARP_INVERSE_MAP, - cv::BORDER_REPLICATE); - } -} - - -/* End of file. */ diff --git a/modules/imgproc/src/segmentation.cpp b/modules/imgproc/src/segmentation.cpp index 757b0512a0..00f2a00937 100644 --- a/modules/imgproc/src/segmentation.cpp +++ b/modules/imgproc/src/segmentation.cpp @@ -394,7 +394,6 @@ void cv::pyrMeanShiftFiltering( InputArray _src, OutputArray _dst, dst_pyramid[level].create( src_pyramid[level].rows, src_pyramid[level].cols, src_pyramid[level].type() ); cv::pyrDown( src_pyramid[level-1], src_pyramid[level], src_pyramid[level].size() ); - //CV_CALL( cvResize( src_pyramid[level-1], src_pyramid[level], CV_INTER_AREA )); } mask0.create(src0.rows, src0.cols, CV_8UC1); @@ -419,7 +418,6 @@ void cv::pyrMeanShiftFiltering( InputArray _src, OutputArray _dst, m = cv::Mat(size.height, size.width, CV_8UC1, mask0.ptr()); dstep = (int)dst_pyramid[level+1].step; dptr = dst_pyramid[level+1].ptr() + dstep + cn; - //cvResize( dst_pyramid[level+1], dst_pyramid[level], CV_INTER_CUBIC ); cv::pyrUp( dst_pyramid[level+1], dst_pyramid[level], dst_pyramid[level].size() ); m.setTo(cv::Scalar::all(0)); diff --git a/modules/imgproc/src/shapedescr.cpp b/modules/imgproc/src/shapedescr.cpp index 0ac1bec960..6681410dfb 100644 --- a/modules/imgproc/src/shapedescr.cpp +++ b/modules/imgproc/src/shapedescr.cpp @@ -861,659 +861,3 @@ cv::RotatedRect cv::fitEllipseDirect( InputArray _points ) } return box; } - - -namespace cv -{ - -// Calculates bounding rectangle of a point set or retrieves already calculated -static Rect pointSetBoundingRect( const Mat& points ) -{ - int npoints = points.checkVector(2); - int depth = points.depth(); - CV_Assert(npoints >= 0 && (depth == CV_32F || depth == CV_32S)); - - int xmin = 0, ymin = 0, xmax = -1, ymax = -1, i; - bool is_float = depth == CV_32F; - - if( npoints == 0 ) - return Rect(); - -#if CV_SIMD - const int64_t* pts = points.ptr(); - - if( !is_float ) - { - v_int32 minval, maxval; - minval = maxval = v_reinterpret_as_s32(vx_setall_s64(*pts)); //min[0]=pt.x, min[1]=pt.y, min[2]=pt.x, min[3]=pt.y - for( i = 1; i <= npoints - v_int32::nlanes/2; i+= v_int32::nlanes/2 ) - { - v_int32 ptXY2 = v_reinterpret_as_s32(vx_load(pts + i)); - minval = v_min(ptXY2, minval); - maxval = v_max(ptXY2, maxval); - } - minval = v_min(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval)))); - maxval = v_max(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval)))); - if( i <= npoints - v_int32::nlanes/4 ) - { - v_int32 ptXY = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(vx_load_low(pts + i)))); - minval = v_min(ptXY, minval); - maxval = v_max(ptXY, maxval); - i += v_int64::nlanes/2; - } - for(int j = 16; j < CV_SIMD_WIDTH; j*=2) - { - minval = v_min(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval)))); - maxval = v_max(v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval)))); - } - xmin = minval.get0(); - xmax = maxval.get0(); - ymin = v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval))).get0(); - ymax = v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval))).get0(); -#if CV_SIMD_WIDTH > 16 - if( i < npoints ) - { - v_int32x4 minval2, maxval2; - minval2 = maxval2 = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); - for( i++; i < npoints; i++ ) - { - v_int32x4 ptXY = v_reinterpret_as_s32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); - minval2 = v_min(ptXY, minval2); - maxval2 = v_max(ptXY, maxval2); - } - xmin = min(xmin, minval2.get0()); - xmax = max(xmax, maxval2.get0()); - ymin = min(ymin, v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(minval2))).get0()); - ymax = max(ymax, v_reinterpret_as_s32(v_expand_high(v_reinterpret_as_u32(maxval2))).get0()); - } -#endif - } - else - { - v_float32 minval, maxval; - minval = maxval = v_reinterpret_as_f32(vx_setall_s64(*pts)); //min[0]=pt.x, min[1]=pt.y, min[2]=pt.x, min[3]=pt.y - for( i = 1; i <= npoints - v_float32::nlanes/2; i+= v_float32::nlanes/2 ) - { - v_float32 ptXY2 = v_reinterpret_as_f32(vx_load(pts + i)); - minval = v_min(ptXY2, minval); - maxval = v_max(ptXY2, maxval); - } - minval = v_min(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval)))); - maxval = v_max(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval)))); - if( i <= npoints - v_float32::nlanes/4 ) - { - v_float32 ptXY = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(vx_load_low(pts + i)))); - minval = v_min(ptXY, minval); - maxval = v_max(ptXY, maxval); - i += v_float32::nlanes/4; - } - for(int j = 16; j < CV_SIMD_WIDTH; j*=2) - { - minval = v_min(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(minval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval)))); - maxval = v_max(v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(maxval))), v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval)))); - } - xmin = cvFloor(minval.get0()); - xmax = cvFloor(maxval.get0()); - ymin = cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval))).get0()); - ymax = cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval))).get0()); -#if CV_SIMD_WIDTH > 16 - if( i < npoints ) - { - v_float32x4 minval2, maxval2; - minval2 = maxval2 = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); - for( i++; i < npoints; i++ ) - { - v_float32x4 ptXY = v_reinterpret_as_f32(v_expand_low(v_reinterpret_as_u32(v_load_low(pts + i)))); - minval2 = v_min(ptXY, minval2); - maxval2 = v_max(ptXY, maxval2); - } - xmin = min(xmin, cvFloor(minval2.get0())); - xmax = max(xmax, cvFloor(maxval2.get0())); - ymin = min(ymin, cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(minval2))).get0())); - ymax = max(ymax, cvFloor(v_reinterpret_as_f32(v_expand_high(v_reinterpret_as_u32(maxval2))).get0())); - } -#endif - } -#else - const Point* pts = points.ptr(); - Point pt = pts[0]; - - if( !is_float ) - { - xmin = xmax = pt.x; - ymin = ymax = pt.y; - - for( i = 1; i < npoints; i++ ) - { - pt = pts[i]; - - if( xmin > pt.x ) - xmin = pt.x; - - if( xmax < pt.x ) - xmax = pt.x; - - if( ymin > pt.y ) - ymin = pt.y; - - if( ymax < pt.y ) - ymax = pt.y; - } - } - else - { - Cv32suf v; - // init values - xmin = xmax = CV_TOGGLE_FLT(pt.x); - ymin = ymax = CV_TOGGLE_FLT(pt.y); - - for( i = 1; i < npoints; i++ ) - { - pt = pts[i]; - pt.x = CV_TOGGLE_FLT(pt.x); - pt.y = CV_TOGGLE_FLT(pt.y); - - if( xmin > pt.x ) - xmin = pt.x; - - if( xmax < pt.x ) - xmax = pt.x; - - if( ymin > pt.y ) - ymin = pt.y; - - if( ymax < pt.y ) - ymax = pt.y; - } - - v.i = CV_TOGGLE_FLT(xmin); xmin = cvFloor(v.f); - v.i = CV_TOGGLE_FLT(ymin); ymin = cvFloor(v.f); - // because right and bottom sides of the bounding rectangle are not inclusive - // (note +1 in width and height calculation below), cvFloor is used here instead of cvCeil - v.i = CV_TOGGLE_FLT(xmax); xmax = cvFloor(v.f); - v.i = CV_TOGGLE_FLT(ymax); ymax = cvFloor(v.f); - } -#endif - - return Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1); -} - - -static Rect maskBoundingRect( const Mat& img ) -{ - CV_Assert( img.depth() <= CV_8S && img.channels() == 1 ); - - Size size = img.size(); - int xmin = size.width, ymin = -1, xmax = -1, ymax = -1, i, j, k; - - for( i = 0; i < size.height; i++ ) - { - const uchar* _ptr = img.ptr(i); - const uchar* ptr = (const uchar*)alignPtr(_ptr, 4); - int have_nz = 0, k_min, offset = (int)(ptr - _ptr); - j = 0; - offset = MIN(offset, size.width); - for( ; j < offset; j++ ) - if( _ptr[j] ) - { - have_nz = 1; - break; - } - if( j < offset ) - { - if( j < xmin ) - xmin = j; - if( j > xmax ) - xmax = j; - } - if( offset < size.width ) - { - xmin -= offset; - xmax -= offset; - size.width -= offset; - j = 0; - for( ; j <= xmin - 4; j += 4 ) - if( *((int*)(ptr+j)) ) - break; - for( ; j < xmin; j++ ) - if( ptr[j] ) - { - xmin = j; - if( j > xmax ) - xmax = j; - have_nz = 1; - break; - } - k_min = MAX(j-1, xmax); - k = size.width - 1; - for( ; k > k_min && (k&3) != 3; k-- ) - if( ptr[k] ) - break; - if( k > k_min && (k&3) == 3 ) - { - for( ; k > k_min+3; k -= 4 ) - if( *((int*)(ptr+k-3)) ) - break; - } - for( ; k > k_min; k-- ) - if( ptr[k] ) - { - xmax = k; - have_nz = 1; - break; - } - if( !have_nz ) - { - j &= ~3; - for( ; j <= k - 3; j += 4 ) - if( *((int*)(ptr+j)) ) - break; - for( ; j <= k; j++ ) - if( ptr[j] ) - { - have_nz = 1; - break; - } - } - xmin += offset; - xmax += offset; - size.width += offset; - } - if( have_nz ) - { - if( ymin < 0 ) - ymin = i; - ymax = i; - } - } - - if( xmin >= size.width ) - xmin = ymin = 0; - return Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1); -} - -} - -cv::Rect cv::boundingRect(InputArray array) -{ - CV_INSTRUMENT_REGION(); - - Mat m = array.getMat(); - return m.depth() <= CV_8U ? maskBoundingRect(m) : pointSetBoundingRect(m); -} - -////////////////////////////////////////////// C API /////////////////////////////////////////// - -static void -icvMemCopy( double **buf1, double **buf2, double **buf3, int *b_max ) -{ - CV_Assert( (*buf1 != NULL || *buf2 != NULL) && *buf3 != NULL ); - - int bb = *b_max; - if( *buf2 == NULL ) - { - *b_max = 2 * (*b_max); - *buf2 = (double *)cvAlloc( (*b_max) * sizeof( double )); - - memcpy( *buf2, *buf3, bb * sizeof( double )); - - *buf3 = *buf2; - cvFree( buf1 ); - *buf1 = NULL; - } - else - { - *b_max = 2 * (*b_max); - *buf1 = (double *) cvAlloc( (*b_max) * sizeof( double )); - - memcpy( *buf1, *buf3, bb * sizeof( double )); - - *buf3 = *buf1; - cvFree( buf2 ); - *buf2 = NULL; - } -} - - -/* area of a contour sector */ -static double icvContourSecArea( CvSeq * contour, CvSlice slice ) -{ - cv::Point pt; /* pointer to points */ - cv::Point pt_s, pt_e; /* first and last points */ - CvSeqReader reader; /* points reader of contour */ - - int p_max = 2, p_ind; - int lpt, flag, i; - double a00; /* unnormalized moments m00 */ - double xi, yi, xi_1, yi_1, x0, y0, dxy, sk, sk1, t; - double x_s, y_s, nx, ny, dx, dy, du, dv; - double eps = 1.e-5; - double *p_are1, *p_are2, *p_are; - double area = 0; - - CV_Assert( contour != NULL && CV_IS_SEQ_POINT_SET( contour )); - - lpt = cvSliceLength( slice, contour ); - /*if( n2 >= n1 ) - lpt = n2 - n1 + 1; - else - lpt = contour->total - n1 + n2 + 1;*/ - - if( contour->total <= 0 || lpt <= 2 ) - return 0.; - - a00 = x0 = y0 = xi_1 = yi_1 = 0; - sk1 = 0; - flag = 0; - dxy = 0; - p_are1 = (double *) cvAlloc( p_max * sizeof( double )); - - p_are = p_are1; - p_are2 = NULL; - - cvStartReadSeq( contour, &reader, 0 ); - cvSetSeqReaderPos( &reader, slice.start_index ); - { CvPoint pt_s_ = CV_STRUCT_INITIALIZER; CV_READ_SEQ_ELEM(pt_s_, reader); pt_s = pt_s_; } - p_ind = 0; - cvSetSeqReaderPos( &reader, slice.end_index ); - { CvPoint pt_e_ = CV_STRUCT_INITIALIZER; CV_READ_SEQ_ELEM(pt_e_, reader); pt_e = pt_e_; } - -/* normal coefficients */ - nx = pt_s.y - pt_e.y; - ny = pt_e.x - pt_s.x; - cvSetSeqReaderPos( &reader, slice.start_index ); - - while( lpt-- > 0 ) - { - { CvPoint pt_ = CV_STRUCT_INITIALIZER; CV_READ_SEQ_ELEM(pt_, reader); pt = pt_; } - - if( flag == 0 ) - { - xi_1 = (double) pt.x; - yi_1 = (double) pt.y; - x0 = xi_1; - y0 = yi_1; - sk1 = 0; - flag = 1; - } - else - { - xi = (double) pt.x; - yi = (double) pt.y; - -/**************** edges intersection examination **************************/ - sk = nx * (xi - pt_s.x) + ny * (yi - pt_s.y); - if( (fabs( sk ) < eps && lpt > 0) || sk * sk1 < -eps ) - { - if( fabs( sk ) < eps ) - { - dxy = xi_1 * yi - xi * yi_1; - a00 = a00 + dxy; - dxy = xi * y0 - x0 * yi; - a00 = a00 + dxy; - - if( p_ind >= p_max ) - icvMemCopy( &p_are1, &p_are2, &p_are, &p_max ); - - p_are[p_ind] = a00 / 2.; - p_ind++; - a00 = 0; - sk1 = 0; - x0 = xi; - y0 = yi; - dxy = 0; - } - else - { -/* define intersection point */ - dv = yi - yi_1; - du = xi - xi_1; - dx = ny; - dy = -nx; - if( fabs( du ) > eps ) - t = ((yi_1 - pt_s.y) * du + dv * (pt_s.x - xi_1)) / - (du * dy - dx * dv); - else - t = (xi_1 - pt_s.x) / dx; - if( t > eps && t < 1 - eps ) - { - x_s = pt_s.x + t * dx; - y_s = pt_s.y + t * dy; - dxy = xi_1 * y_s - x_s * yi_1; - a00 += dxy; - dxy = x_s * y0 - x0 * y_s; - a00 += dxy; - if( p_ind >= p_max ) - icvMemCopy( &p_are1, &p_are2, &p_are, &p_max ); - - p_are[p_ind] = a00 / 2.; - p_ind++; - - a00 = 0; - sk1 = 0; - x0 = x_s; - y0 = y_s; - dxy = x_s * yi - xi * y_s; - } - } - } - else - dxy = xi_1 * yi - xi * yi_1; - - a00 += dxy; - xi_1 = xi; - yi_1 = yi; - sk1 = sk; - - } - } - - xi = x0; - yi = y0; - dxy = xi_1 * yi - xi * yi_1; - - a00 += dxy; - - if( p_ind >= p_max ) - icvMemCopy( &p_are1, &p_are2, &p_are, &p_max ); - - p_are[p_ind] = a00 / 2.; - p_ind++; - - // common area calculation - area = 0; - for( i = 0; i < p_ind; i++ ) - area += fabs( p_are[i] ); - - if( p_are1 != NULL ) - cvFree( &p_are1 ); - else if( p_are2 != NULL ) - cvFree( &p_are2 ); - - return area; -} - - -/* external contour area function */ -CV_IMPL double -cvContourArea( const void *array, CvSlice slice, int oriented ) -{ - double area = 0; - - CvContour contour_header; - CvSeq* contour = 0; - CvSeqBlock block; - - if( CV_IS_SEQ( array )) - { - contour = (CvSeq*)array; - if( !CV_IS_SEQ_POLYLINE( contour )) - CV_Error( CV_StsBadArg, "Unsupported sequence type" ); - } - else - { - contour = cvPointSeqFromMat( CV_SEQ_KIND_CURVE, array, &contour_header, &block ); - } - - if( cvSliceLength( slice, contour ) == contour->total ) - { - cv::AutoBuffer abuf; - cv::Mat points = cv::cvarrToMat(contour, false, false, 0, &abuf); - return cv::contourArea( points, oriented !=0 ); - } - - if( CV_SEQ_ELTYPE( contour ) != CV_32SC2 ) - CV_Error( CV_StsUnsupportedFormat, - "Only curves with integer coordinates are supported in case of contour slice" ); - area = icvContourSecArea( contour, slice ); - return oriented ? area : fabs(area); -} - - -/* calculates length of a curve (e.g. contour perimeter) */ -CV_IMPL double -cvArcLength( const void *array, CvSlice slice, int is_closed ) -{ - double perimeter = 0; - - int i, j = 0, count; - const int N = 16; - float buf[N]; - CvMat buffer = cvMat( 1, N, CV_32F, buf ); - CvSeqReader reader; - CvContour contour_header; - CvSeq* contour = 0; - CvSeqBlock block; - - if( CV_IS_SEQ( array )) - { - contour = (CvSeq*)array; - if( !CV_IS_SEQ_POLYLINE( contour )) - CV_Error( CV_StsBadArg, "Unsupported sequence type" ); - if( is_closed < 0 ) - is_closed = CV_IS_SEQ_CLOSED( contour ); - } - else - { - is_closed = is_closed > 0; - contour = cvPointSeqFromMat( - CV_SEQ_KIND_CURVE | (is_closed ? CV_SEQ_FLAG_CLOSED : 0), - array, &contour_header, &block ); - } - - if( contour->total > 1 ) - { - int is_float = CV_SEQ_ELTYPE( contour ) == CV_32FC2; - - cvStartReadSeq( contour, &reader, 0 ); - cvSetSeqReaderPos( &reader, slice.start_index ); - count = cvSliceLength( slice, contour ); - - count -= !is_closed && count == contour->total; - - // scroll the reader by 1 point - reader.prev_elem = reader.ptr; - CV_NEXT_SEQ_ELEM( sizeof(CvPoint), reader ); - - for( i = 0; i < count; i++ ) - { - float dx, dy; - - if( !is_float ) - { - CvPoint* pt = (CvPoint*)reader.ptr; - CvPoint* prev_pt = (CvPoint*)reader.prev_elem; - - dx = (float)pt->x - (float)prev_pt->x; - dy = (float)pt->y - (float)prev_pt->y; - } - else - { - CvPoint2D32f* pt = (CvPoint2D32f*)reader.ptr; - CvPoint2D32f* prev_pt = (CvPoint2D32f*)reader.prev_elem; - - dx = pt->x - prev_pt->x; - dy = pt->y - prev_pt->y; - } - - reader.prev_elem = reader.ptr; - CV_NEXT_SEQ_ELEM( contour->elem_size, reader ); - // Bugfix by Axel at rubico.com 2010-03-22, affects closed slices only - // wraparound not handled by CV_NEXT_SEQ_ELEM - if( is_closed && i == count - 2 ) - cvSetSeqReaderPos( &reader, slice.start_index ); - - buffer.data.fl[j] = dx * dx + dy * dy; - if( ++j == N || i == count - 1 ) - { - buffer.cols = j; - cvPow( &buffer, &buffer, 0.5 ); - for( ; j > 0; j-- ) - perimeter += buffer.data.fl[j-1]; - } - } - } - - return perimeter; -} - - -/* Calculates bounding rectangle of a point set or retrieves already calculated */ -CV_IMPL CvRect -cvBoundingRect( CvArr* array, int update ) -{ - cv::Rect rect; - CvContour contour_header; - CvSeq* ptseq = 0; - CvSeqBlock block; - - CvMat stub, *mat = 0; - int calculate = update; - - if( CV_IS_SEQ( array )) - { - ptseq = (CvSeq*)array; - if( !CV_IS_SEQ_POINT_SET( ptseq )) - CV_Error( CV_StsBadArg, "Unsupported sequence type" ); - - if( ptseq->header_size < (int)sizeof(CvContour)) - { - update = 0; - calculate = 1; - } - } - else - { - mat = cvGetMat( array, &stub ); - if( CV_MAT_TYPE(mat->type) == CV_32SC2 || - CV_MAT_TYPE(mat->type) == CV_32FC2 ) - { - ptseq = cvPointSeqFromMat(CV_SEQ_KIND_GENERIC, mat, &contour_header, &block); - mat = 0; - } - else if( CV_MAT_TYPE(mat->type) != CV_8UC1 && - CV_MAT_TYPE(mat->type) != CV_8SC1 ) - CV_Error( CV_StsUnsupportedFormat, - "The image/matrix format is not supported by the function" ); - update = 0; - calculate = 1; - } - - if( !calculate ) - return ((CvContour*)ptseq)->rect; - - if( mat ) - { - rect = cvRect(cv::maskBoundingRect(cv::cvarrToMat(mat))); - } - else if( ptseq->total ) - { - cv::AutoBuffer abuf; - rect = cvRect(cv::pointSetBoundingRect(cv::cvarrToMat(ptseq, false, false, 0, &abuf))); - } - if( update ) - ((CvContour*)ptseq)->rect = cvRect(rect); - return cvRect(rect); -} - -/* End of file. */ diff --git a/modules/imgproc/src/smooth.dispatch.cpp b/modules/imgproc/src/smooth.dispatch.cpp index f593f7bc2d..95a0437812 100644 --- a/modules/imgproc/src/smooth.dispatch.cpp +++ b/modules/imgproc/src/smooth.dispatch.cpp @@ -755,33 +755,3 @@ void GaussianBlur(InputArray _src, OutputArray _dst, Size ksize, } } // namespace - -////////////////////////////////////////////////////////////////////////////////////////// - -CV_IMPL void -cvSmooth( const void* srcarr, void* dstarr, int smooth_type, - int param1, int param2, double param3, double param4 ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0; - - CV_Assert( dst.size() == src.size() && - (smooth_type == CV_BLUR_NO_SCALE || dst.type() == src.type()) ); - - if( param2 <= 0 ) - param2 = param1; - - if( smooth_type == CV_BLUR || smooth_type == CV_BLUR_NO_SCALE ) - cv::boxFilter( src, dst, dst.depth(), cv::Size(param1, param2), cv::Point(-1,-1), - smooth_type == CV_BLUR, cv::BORDER_REPLICATE ); - else if( smooth_type == CV_GAUSSIAN ) - cv::GaussianBlur( src, dst, cv::Size(param1, param2), param3, param4, cv::BORDER_REPLICATE ); - else if( smooth_type == CV_MEDIAN ) - cv::medianBlur( src, dst, param1 ); - else - cv::bilateralFilter( src, dst, param1, param3, param4, cv::BORDER_REPLICATE ); - - if( dst.data != dst0.data ) - CV_Error( CV_StsUnmatchedFormats, "The destination image does not have the proper type" ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/sumpixels.dispatch.cpp b/modules/imgproc/src/sumpixels.dispatch.cpp index b828ec70c0..0506189d7e 100644 --- a/modules/imgproc/src/sumpixels.dispatch.cpp +++ b/modules/imgproc/src/sumpixels.dispatch.cpp @@ -465,30 +465,3 @@ void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth, i } } // namespace - -CV_IMPL void -cvIntegral( const CvArr* image, CvArr* sumImage, - CvArr* sumSqImage, CvArr* tiltedSumImage ) -{ - cv::Mat src = cv::cvarrToMat(image), sum = cv::cvarrToMat(sumImage), sum0 = sum; - cv::Mat sqsum0, sqsum, tilted0, tilted; - cv::Mat *psqsum = 0, *ptilted = 0; - - if( sumSqImage ) - { - sqsum0 = sqsum = cv::cvarrToMat(sumSqImage); - psqsum = &sqsum; - } - - if( tiltedSumImage ) - { - tilted0 = tilted = cv::cvarrToMat(tiltedSumImage); - ptilted = &tilted; - } - cv::integral( src, sum, psqsum ? cv::_OutputArray(*psqsum) : cv::_OutputArray(), - ptilted ? cv::_OutputArray(*ptilted) : cv::_OutputArray(), sum.depth() ); - - CV_Assert( sum.data == sum0.data && sqsum.data == sqsum0.data && tilted.data == tilted0.data ); -} - -/* End of file. */ diff --git a/modules/imgproc/src/templmatch.cpp b/modules/imgproc/src/templmatch.cpp index e37311cb2b..0a5189fdf5 100644 --- a/modules/imgproc/src/templmatch.cpp +++ b/modules/imgproc/src/templmatch.cpp @@ -315,7 +315,7 @@ static bool matchTemplate_CCORR(InputArray _image, InputArray _templ, OutputArra static bool matchTemplate_CCORR_NORMED(InputArray _image, InputArray _templ, OutputArray _result) { - matchTemplate(_image, _templ, _result, CV_TM_CCORR); + matchTemplate(_image, _templ, _result, cv::TM_CCORR); int type = _image.type(), cn = CV_MAT_CN(type); @@ -373,7 +373,7 @@ static bool matchTemplate_SQDIFF(InputArray _image, InputArray _templ, OutputArr return( matchTemplateNaive_SQDIFF(_image, _templ, _result)); else { - matchTemplate(_image, _templ, _result, CV_TM_CCORR); + matchTemplate(_image, _templ, _result, cv::TM_CCORR); int type = _image.type(), cn = CV_MAT_CN(type); @@ -404,7 +404,7 @@ static bool matchTemplate_SQDIFF(InputArray _image, InputArray _templ, OutputArr static bool matchTemplate_SQDIFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result) { - matchTemplate(_image, _templ, _result, CV_TM_CCORR); + matchTemplate(_image, _templ, _result, cv::TM_CCORR); int type = _image.type(), cn = CV_MAT_CN(type); @@ -436,7 +436,7 @@ static bool matchTemplate_SQDIFF_NORMED(InputArray _image, InputArray _templ, Ou static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArray _result) { - matchTemplate(_image, _templ, _result, CV_TM_CCORR); + matchTemplate(_image, _templ, _result, cv::TM_CCORR); UMat image_sums, temp; integral(_image, image_sums, CV_32F); @@ -471,7 +471,7 @@ static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArr static bool matchTemplate_CCOEFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result) { - matchTemplate(_image, _templ, _result, CV_TM_CCORR); + matchTemplate(_image, _templ, _result, cv::TM_CCORR); UMat temp, image_sums, image_sqsums; integral(_image, image_sums, image_sqsums, CV_32F, CV_32F); @@ -796,7 +796,7 @@ static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _ merge(maskChannels.data(), templ.channels(), mask); } - if (method == CV_TM_SQDIFF || method == CV_TM_SQDIFF_NORMED) + if (method == cv::TM_SQDIFF || method == cv::TM_SQDIFF_NORMED) { Mat temp_result(corrSize, CV_32F); Mat img2 = img.mul(img); @@ -810,19 +810,19 @@ static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _ // for normalization. result = -2 * result + temp_result + templ2_mask2_sum; - if (method == CV_TM_SQDIFF_NORMED) + if (method == cv::TM_SQDIFF_NORMED) { sqrt(templ2_mask2_sum * temp_result, temp_result); result /= temp_result; } } - else if (method == CV_TM_CCORR || method == CV_TM_CCORR_NORMED) + else if (method == cv::TM_CCORR || method == cv::TM_CCORR_NORMED) { // If the mul() is ever unnested, declare MatExpr, *not* Mat, to be more efficient. Mat templ_mask2 = templ.mul(mask.mul(mask)); crossCorr(img, templ_mask2, result, Point(0,0), 0, 0); - if (method == CV_TM_CCORR_NORMED) + if (method == cv::TM_CCORR_NORMED) { Mat temp_result(corrSize, CV_32F); Mat img2 = img.mul(img); @@ -834,7 +834,7 @@ static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _ result /= temp_result; } } - else if (method == CV_TM_CCOEFF || method == CV_TM_CCOEFF_NORMED) + else if (method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED) { // Do mul() inline or declare MatExpr where possible, *not* Mat, to be more efficient. @@ -864,7 +864,7 @@ static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _ // transform back, but now with only one channel result -= temp_res.reshape(1, result.rows); } - if (method == CV_TM_CCOEFF_NORMED) + if (method == cv::TM_CCOEFF_NORMED) { // norm(T') double norm_templx = norm(mask.mul(templ - sum(mask.mul(templ)).div(mask_sum)), @@ -905,14 +905,14 @@ static void matchTemplateMask( InputArray _img, InputArray _templ, OutputArray _ static void common_matchTemplate( Mat& img, Mat& templ, Mat& result, int method, int cn ) { - if( method == CV_TM_CCORR ) + if( method == cv::TM_CCORR ) return; - int numType = method == CV_TM_CCORR || method == CV_TM_CCORR_NORMED ? 0 : - method == CV_TM_CCOEFF || method == CV_TM_CCOEFF_NORMED ? 1 : 2; - bool isNormed = method == CV_TM_CCORR_NORMED || - method == CV_TM_SQDIFF_NORMED || - method == CV_TM_CCOEFF_NORMED; + int numType = method == cv::TM_CCORR || method == cv::TM_CCORR_NORMED ? 0 : + method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED ? 1 : 2; + bool isNormed = method == cv::TM_CCORR_NORMED || + method == cv::TM_SQDIFF_NORMED || + method == cv::TM_CCOEFF_NORMED; double invArea = 1./((double)templ.rows * templ.cols); @@ -921,7 +921,7 @@ static void common_matchTemplate( Mat& img, Mat& templ, Mat& result, int method, double *q0 = 0, *q1 = 0, *q2 = 0, *q3 = 0; double templNorm = 0, templSum2 = 0; - if( method == CV_TM_CCOEFF ) + if( method == cv::TM_CCOEFF ) { integral(img, sum, CV_64F); templMean = mean(templ); @@ -933,7 +933,7 @@ static void common_matchTemplate( Mat& img, Mat& templ, Mat& result, int method, templNorm = templSdv[0]*templSdv[0] + templSdv[1]*templSdv[1] + templSdv[2]*templSdv[2] + templSdv[3]*templSdv[3]; - if( templNorm < DBL_EPSILON && method == CV_TM_CCOEFF_NORMED ) + if( templNorm < DBL_EPSILON && method == cv::TM_CCOEFF_NORMED ) { result = Scalar::all(1); return; @@ -1020,7 +1020,7 @@ static void common_matchTemplate( Mat& img, Mat& templ, Mat& result, int method, else if( fabs(num) < t*1.125 ) num = num > 0 ? 1 : -1; else - num = method != CV_TM_SQDIFF_NORMED ? 0 : 1; + num = method != cv::TM_SQDIFF_NORMED ? 0 : 1; } rrow[j] = (float)num; @@ -1116,30 +1116,30 @@ static bool ipp_matchTemplate( Mat& img, Mat& templ, Mat& result, int method) if(templ.size().area()*4 > img.size().area()) return false; - if(method == CV_TM_SQDIFF) + if(method == cv::TM_SQDIFF) { if(ipp_sqrDistance(img, templ, result)) return true; } - else if(method == CV_TM_SQDIFF_NORMED) + else if(method == cv::TM_SQDIFF_NORMED) { if(ipp_crossCorr(img, templ, result, false)) { - common_matchTemplate(img, templ, result, CV_TM_SQDIFF_NORMED, 1); + common_matchTemplate(img, templ, result, cv::TM_SQDIFF_NORMED, 1); return true; } } - else if(method == CV_TM_CCORR) + else if(method == cv::TM_CCORR) { if(ipp_crossCorr(img, templ, result, false)) return true; } - else if(method == CV_TM_CCORR_NORMED) + else if(method == cv::TM_CCORR_NORMED) { if(ipp_crossCorr(img, templ, result, true)) return true; } - else if(method == CV_TM_CCOEFF || method == CV_TM_CCOEFF_NORMED) + else if(method == cv::TM_CCOEFF || method == cv::TM_CCOEFF_NORMED) { if(ipp_crossCorr(img, templ, result, false)) { @@ -1160,7 +1160,7 @@ void cv::matchTemplate( InputArray _img, InputArray _templ, OutputArray _result, CV_INSTRUMENT_REGION(); int type = _img.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); - CV_Assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED ); + CV_Assert( cv::TM_SQDIFF <= method && method <= cv::TM_CCOEFF_NORMED ); CV_Assert( (depth == CV_8U || depth == CV_32F) && type == _templ.type() && _img.dims() <= 2 ); if (!_mask.empty()) diff --git a/modules/imgproc/src/thresh.cpp b/modules/imgproc/src/thresh.cpp index ad83a9a4f6..f411d257a9 100644 --- a/modules/imgproc/src/thresh.cpp +++ b/modules/imgproc/src/thresh.cpp @@ -1545,18 +1545,18 @@ double cv::threshold( InputArray _src, OutputArray _dst, double thresh, double m ocl_threshold(_src, _dst, thresh, maxval, type), thresh) Mat src = _src.getMat(); - int automatic_thresh = (type & ~CV_THRESH_MASK); + int automatic_thresh = (type & ~cv::THRESH_MASK); type &= THRESH_MASK; - CV_Assert( automatic_thresh != (CV_THRESH_OTSU | CV_THRESH_TRIANGLE) ); - if( automatic_thresh == CV_THRESH_OTSU ) + CV_Assert( automatic_thresh != (cv::THRESH_OTSU | cv::THRESH_TRIANGLE) ); + if( automatic_thresh == cv::THRESH_OTSU ) { int src_type = src.type(); CV_CheckType(src_type, src_type == CV_8UC1 || src_type == CV_16UC1, "THRESH_OTSU mode"); thresh = src.type() == CV_8UC1 ? getThreshVal_Otsu_8u( src ) : getThreshVal_Otsu_16u( src ); } - else if( automatic_thresh == CV_THRESH_TRIANGLE ) + else if( automatic_thresh == cv::THRESH_TRIANGLE ) { CV_Assert( src.type() == CV_8UC1 ); thresh = getThreshVal_Triangle_8u( src ); @@ -1711,10 +1711,10 @@ void cv::adaptiveThreshold( InputArray _src, OutputArray _dst, double maxValue, int idelta = type == THRESH_BINARY ? cvCeil(delta) : cvFloor(delta); uchar tab[768]; - if( type == CV_THRESH_BINARY ) + if( type == cv::THRESH_BINARY ) for( i = 0; i < 768; i++ ) tab[i] = (uchar)(i - 255 > -idelta ? imaxval : 0); - else if( type == CV_THRESH_BINARY_INV ) + else if( type == cv::THRESH_BINARY_INV ) for( i = 0; i < 768; i++ ) tab[i] = (uchar)(i - 255 <= -idelta ? imaxval : 0); else @@ -1736,19 +1736,3 @@ void cv::adaptiveThreshold( InputArray _src, OutputArray _dst, double maxValue, ddata[j] = tab[sdata[j] - mdata[j] + 255]; } } - -CV_IMPL double -cvThreshold( const void* srcarr, void* dstarr, double thresh, double maxval, int type ) -{ - cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), dst0 = dst; - - CV_Assert( src.size == dst.size && src.channels() == dst.channels() && - (src.depth() == dst.depth() || dst.depth() == CV_8U)); - - thresh = cv::threshold( src, dst, thresh, maxval, type ); - if( dst0.data != dst.data ) - dst.convertTo( dst0, dst0.depth() ); - return thresh; -} - -/* End of file. */ diff --git a/modules/imgproc/src/utils.cpp b/modules/imgproc/src/utils.cpp index b0dc1b7dbb..43fa709b7f 100644 --- a/modules/imgproc/src/utils.cpp +++ b/modules/imgproc/src/utils.cpp @@ -41,38 +41,5 @@ #include "precomp.hpp" -CV_IMPL CvSeq* cvPointSeqFromMat( int seq_kind, const CvArr* arr, - CvContour* contour_header, CvSeqBlock* block ) -{ - CV_Assert( arr != 0 && contour_header != 0 && block != 0 ); - - int eltype; - CvMat hdr; - CvMat* mat = (CvMat*)arr; - - if( !CV_IS_MAT( mat )) - CV_Error( CV_StsBadArg, "Input array is not a valid matrix" ); - - if( CV_MAT_CN(mat->type) == 1 && mat->width == 2 ) - mat = cvReshape(mat, &hdr, 2); - - eltype = CV_MAT_TYPE( mat->type ); - if( eltype != CV_32SC2 && eltype != CV_32FC2 ) - CV_Error( CV_StsUnsupportedFormat, - "The matrix can not be converted to point sequence because of " - "inappropriate element type" ); - - if( (mat->width != 1 && mat->height != 1) || !CV_IS_MAT_CONT(mat->type)) - CV_Error( CV_StsBadArg, - "The matrix converted to point sequence must be " - "1-dimensional and continuous" ); - - cvMakeSeqHeaderForArray( - (seq_kind & (CV_SEQ_KIND_MASK|CV_SEQ_FLAG_CLOSED)) | eltype, - sizeof(CvContour), CV_ELEM_SIZE(eltype), mat->data.ptr, - mat->width*mat->height, (CvSeq*)contour_header, block ); - - return (CvSeq*)contour_header; -} /* End of file. */ diff --git a/modules/imgproc/test/ocl/test_match_template.cpp b/modules/imgproc/test/ocl/test_match_template.cpp index 3d979e00de..f041e51a6d 100644 --- a/modules/imgproc/test/ocl/test_match_template.cpp +++ b/modules/imgproc/test/ocl/test_match_template.cpp @@ -51,7 +51,7 @@ namespace ocl { ///////////////////////////////////////////// matchTemplate ////////////////////////////////////////////////////////// -CV_ENUM(MatchTemplType, CV_TM_CCORR, CV_TM_CCORR_NORMED, CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED) +CV_ENUM(MatchTemplType, cv::TM_CCORR, cv::TM_CCORR_NORMED, cv::TM_SQDIFF, cv::TM_SQDIFF_NORMED, cv::TM_CCOEFF, cv::TM_CCOEFF_NORMED) PARAM_TEST_CASE(MatchTemplate, MatDepth, Channels, MatchTemplType, bool) { diff --git a/modules/imgproc/test/test_approxpoly.cpp b/modules/imgproc/test/test_approxpoly.cpp index f09475c9fc..482c1f10b3 100644 --- a/modules/imgproc/test/test_approxpoly.cpp +++ b/modules/imgproc/test/test_approxpoly.cpp @@ -55,307 +55,6 @@ namespace opencv_test { namespace { // a subset of vertices of the original contour. // -class CV_ApproxPolyTest : public cvtest::BaseTest -{ -public: - CV_ApproxPolyTest(); - ~CV_ApproxPolyTest(); - void clear(); - //int write_default_params(CvFileStorage* fs); - -protected: - //int read_params( const cv::FileStorage& fs ); - - int check_slice( CvPoint StartPt, CvPoint EndPt, - CvSeqReader* SrcReader, float Eps, - int* j, int Count ); - int check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps ); - - bool get_contour( int /*type*/, CvSeq** Seq, int* d, - CvMemStorage* storage ); - - void run(int); -}; - - -CV_ApproxPolyTest::CV_ApproxPolyTest() -{ -} - - -CV_ApproxPolyTest::~CV_ApproxPolyTest() -{ - clear(); -} - - -void CV_ApproxPolyTest::clear() -{ - cvtest::BaseTest::clear(); -} - - -/*int CV_ApproxPolyTest::write_default_params( CvFileStorage* fs ) -{ - cvtest::BaseTest::write_default_params( fs ); - if( ts->get_testing_mode() != cvtest::TS::TIMING_MODE ) - { - write_param( fs, "test_case_count", test_case_count ); - } - return 0; -} - - -int CV_ApproxPolyTest::read_params( const cv::FileStorage& fs ) -{ - int code = cvtest::BaseTest::read_params( fs ); - if( code < 0 ) - return code; - - test_case_count = cvReadInt( find_param( fs, "test_case_count" ), test_case_count ); - min_log_size = cvtest::clipInt( min_log_size, 1, 10 ); - return 0; -}*/ - - -bool CV_ApproxPolyTest::get_contour( int /*type*/, CvSeq** Seq, int* d, - CvMemStorage* storage ) -{ - RNG& rng = ts->get_rng(); - int max_x = INT_MIN, max_y = INT_MIN, min_x = INT_MAX, min_y = INT_MAX; - int i; - CvSeq* seq; - int total = cvtest::randInt(rng) % 1000 + 1; - Point center; - int radius, angle; - double deg_to_rad = CV_PI/180.; - Point pt; - - center.x = cvtest::randInt( rng ) % 1000; - center.y = cvtest::randInt( rng ) % 1000; - radius = cvtest::randInt( rng ) % 1000; - angle = cvtest::randInt( rng ) % 360; - - seq = cvCreateSeq( CV_SEQ_POLYGON, sizeof(CvContour), sizeof(CvPoint), storage ); - - for( i = 0; i < total; i++ ) - { - int d_radius = cvtest::randInt( rng ) % 10 - 5; - int d_angle = 360/total;//cvtest::randInt( rng ) % 10 - 5; - pt.x = cvRound( center.x + radius*cos(angle*deg_to_rad)); - pt.y = cvRound( center.x - radius*sin(angle*deg_to_rad)); - radius += d_radius; - angle += d_angle; - cvSeqPush( seq, &pt ); - - max_x = MAX( max_x, pt.x ); - max_y = MAX( max_y, pt.y ); - - min_x = MIN( min_x, pt.x ); - min_y = MIN( min_y, pt.y ); - } - - *d = (max_x - min_x)*(max_x - min_x) + (max_y - min_y)*(max_y - min_y); - *Seq = seq; - return true; -} - - -int CV_ApproxPolyTest::check_slice( CvPoint StartPt, CvPoint EndPt, - CvSeqReader* SrcReader, float Eps, - int* _j, int Count ) -{ - /////////// - Point Pt; - /////////// - bool flag; - double dy,dx; - double A,B,C; - double Sq; - double sin_a = 0; - double cos_a = 0; - double d = 0; - double dist; - /////////// - int j, TotalErrors = 0; - - //////////////////////////////// - if( SrcReader == NULL ) - { - CV_Assert( false ); - return 0; - } - - ///////// init line //////////// - flag = true; - - dx = (double)StartPt.x - (double)EndPt.x; - dy = (double)StartPt.y - (double)EndPt.y; - - if( ( dx == 0 ) && ( dy == 0 ) ) flag = false; - else - { - A = -dy; - B = dx; - C = dy * (double)StartPt.x - dx * (double)StartPt.y; - Sq = sqrt( A*A + B*B ); - - sin_a = B/Sq; - cos_a = A/Sq; - d = C/Sq; - } - - /////// find start point and check distance //////// - for( j = *_j; j < Count; j++ ) - { - { CvPoint pt_ = CV_STRUCT_INITIALIZER; CV_READ_SEQ_ELEM(pt_, *SrcReader); Pt = pt_; } - if( StartPt.x == Pt.x && StartPt.y == Pt.y ) break; - else - { - if( flag ) dist = sin_a * Pt.y + cos_a * Pt.x - d; - else dist = sqrt( (double)(EndPt.y - Pt.y)*(EndPt.y - Pt.y) + (EndPt.x - Pt.x)*(EndPt.x - Pt.x) ); - if( dist > Eps ) TotalErrors++; - } - } - - *_j = j; - - (void) TotalErrors; // To avoid -Wunused-but-set-variable warning - //return TotalErrors; - return 0; -} - - -int CV_ApproxPolyTest::check( CvSeq* SrcSeq, CvSeq* DstSeq, float Eps ) -{ - ////////// - CvSeqReader DstReader; - CvSeqReader SrcReader; - CvPoint StartPt = {0, 0}, EndPt = {0, 0}; - /////////// - int TotalErrors = 0; - /////////// - int Count; - int i,j; - - CV_Assert( SrcSeq && DstSeq ); - - ////////// init //////////////////// - Count = SrcSeq->total; - - cvStartReadSeq( DstSeq, &DstReader, 0 ); - cvStartReadSeq( SrcSeq, &SrcReader, 0 ); - - CV_READ_SEQ_ELEM( StartPt, DstReader ); - for( i = 0 ; i < Count ; ) - { - CV_READ_SEQ_ELEM( EndPt, SrcReader ); - i++; - if( StartPt.x == EndPt.x && StartPt.y == EndPt.y ) break; - } - - ///////// start //////////////// - for( i = 1, j = 0 ; i <= DstSeq->total ; ) - { - ///////// read slice //////////// - EndPt.x = StartPt.x; - EndPt.y = StartPt.y; - CV_READ_SEQ_ELEM( StartPt, DstReader ); - i++; - - TotalErrors += check_slice( StartPt, EndPt, &SrcReader, Eps, &j, Count ); - - if( j > Count ) - { - TotalErrors++; - return TotalErrors; - } //if( !flag ) - - } // for( int i = 0 ; i < DstSeq->total ; i++ ) - - return TotalErrors; -} - - -//extern CvTestContourGenerator cvTsTestContours[]; - -void CV_ApproxPolyTest::run( int /*start_from*/ ) -{ - int code = cvtest::TS::OK; - CvMemStorage* storage = 0; - ////////////// Variables //////////////// - int IntervalsCount = 10; - /////////// - //CvTestContourGenerator Cont; - CvSeq* SrcSeq = NULL; - CvSeq* DstSeq; - int iDiam; - float dDiam, Eps, EpsStep; - - for( int i = 0; i < 30; i++ ) - { - CvMemStoragePos pos; - - ts->update_context( this, i, false ); - - ///////////////////// init contour ///////// - dDiam = 0; - while( sqrt(dDiam) / IntervalsCount == 0 ) - { - if( storage != 0 ) - cvReleaseMemStorage(&storage); - - storage = cvCreateMemStorage( 0 ); - if( get_contour( 0, &SrcSeq, &iDiam, storage ) ) - dDiam = (float)iDiam; - } - dDiam = (float)sqrt( dDiam ); - - storage = SrcSeq->storage; - - ////////////////// test ///////////// - EpsStep = dDiam / IntervalsCount ; - for( Eps = EpsStep ; Eps < dDiam ; Eps += EpsStep ) - { - cvSaveMemStoragePos( storage, &pos ); - - ////////// call function //////////// - DstSeq = cvApproxPoly( SrcSeq, SrcSeq->header_size, storage, - CV_POLY_APPROX_DP, Eps ); - - if( DstSeq == NULL ) - { - ts->printf( cvtest::TS::LOG, - "cvApproxPoly returned NULL for contour #%d, epsilon = %g\n", i, Eps ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - goto _exit_; - } // if( DstSeq == NULL ) - - code = check( SrcSeq, DstSeq, Eps ); - if( code != 0 ) - { - ts->printf( cvtest::TS::LOG, - "Incorrect result for the contour #%d approximated with epsilon=%g\n", i, Eps ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - goto _exit_; - } - - cvRestoreMemStoragePos( storage, &pos ); - } // for( Eps = EpsStep ; Eps <= Diam ; Eps += EpsStep ) - - ///////////// free memory /////////////////// - cvReleaseMemStorage(&storage); - } // for( int i = 0; NULL != ( Cont = Contours[i] ) ; i++ ) - -_exit_: - cvReleaseMemStorage(&storage); - - if( code < 0 ) - ts->set_failed_test_info( code ); -} - -TEST(Imgproc_ApproxPoly, accuracy) { CV_ApproxPolyTest test; test.safe_run(); } - //Tests to make sure that unreasonable epsilon (error) //values never get passed to the Douglas-Peucker algorithm. TEST(Imgproc_ApproxPoly, bad_epsilon) diff --git a/modules/imgproc/test/test_canny.cpp b/modules/imgproc/test/test_canny.cpp index e040da61ad..7e4fffbf30 100644 --- a/modules/imgproc/test/test_canny.cpp +++ b/modules/imgproc/test/test_canny.cpp @@ -160,7 +160,7 @@ void CV_CannyTest::run_func() { cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); cv::Canny(cv::cvarrToMat(test_array[INPUT][0]), _out, threshold1, threshold2, - aperture_size + (use_true_gradient ? CV_CANNY_L2_GRADIENT : 0)); + aperture_size, use_true_gradient); } } diff --git a/modules/imgproc/test/test_color.cpp b/modules/imgproc/test/test_color.cpp index 318dae66db..5a4ee5efbb 100644 --- a/modules/imgproc/test/test_color.cpp +++ b/modules/imgproc/test/test_color.cpp @@ -76,7 +76,6 @@ protected: bool inplace; bool custom_inv_transform; int fwd_code, inv_code; - bool test_cpp; int hue_range; bool srgb; }; @@ -97,7 +96,6 @@ CV_ColorCvtBaseTest::CV_ColorCvtBaseTest( bool _custom_inv_transform, bool _allo fwd_code_str = inv_code_str = 0; - test_cpp = false; hue_range = 0; blue_idx = 0; srgb = false; @@ -147,7 +145,6 @@ void CV_ColorCvtBaseTest::get_test_array_types_and_sizes( int test_case_idx, types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_MAKETYPE(depth, cn); inplace = cn == 3 && cvtest::randInt(rng) % 2 != 0; - test_cpp = (cvtest::randInt(rng) & 256) == 0; } @@ -164,20 +161,14 @@ void CV_ColorCvtBaseTest::run_func() CvArr* out0 = test_array[OUTPUT][0]; cv::Mat _out0 = cv::cvarrToMat(out0), _out1 = cv::cvarrToMat(test_array[OUTPUT][1]); - if(!test_cpp) - cvCvtColor( inplace ? out0 : test_array[INPUT][0], out0, fwd_code ); - else - cv::cvtColor( cv::cvarrToMat(inplace ? out0 : test_array[INPUT][0]), _out0, fwd_code, _out0.channels()); + cv::cvtColor( cv::cvarrToMat(inplace ? out0 : test_array[INPUT][0]), _out0, fwd_code, _out0.channels()); if( inplace ) { cvCopy( out0, test_array[OUTPUT][1] ); out0 = test_array[OUTPUT][1]; } - if(!test_cpp) - cvCvtColor( out0, test_array[OUTPUT][1], inv_code ); - else - cv::cvtColor(cv::cvarrToMat(out0), _out1, inv_code, _out1.channels()); + cv::cvtColor(cv::cvarrToMat(out0), _out1, inv_code, _out1.channels()); } @@ -1077,7 +1068,7 @@ double CV_ColorLabTest::get_success_error_level( int /*test_case_idx*/, int i, i { int depth = test_mat[i][j].depth(); // j == 0 is for forward code, j == 1 is for inverse code - return (depth == CV_8U) ? (srgb ? 32 : 8) : + return (depth == CV_8U) ? (srgb ? 37 : 8) : //(depth == CV_16U) ? 32 : // 16u is disabled srgb ? ((j == 0) ? 0.4 : 0.0055) : 1e-3; } @@ -1256,7 +1247,7 @@ double CV_ColorLuvTest::get_success_error_level( int /*test_case_idx*/, int i, i { int depth = test_mat[i][j].depth(); // j == 0 is for forward code, j == 1 is for inverse code - return (depth == CV_8U) ? (srgb ? 36 : 8) : + return (depth == CV_8U) ? (srgb ? 37 : 8) : //(depth == CV_16U) ? 32 : // 16u is disabled 5e-2; } @@ -1730,13 +1721,8 @@ double CV_ColorBayerTest::get_success_error_level( int /*test_case_idx*/, int /* void CV_ColorBayerTest::run_func() { - if(!test_cpp) - cvCvtColor( test_array[INPUT][0], test_array[OUTPUT][0], fwd_code ); - else - { - cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); - cv::cvtColor(cv::cvarrToMat(test_array[INPUT][0]), _out, fwd_code, _out.channels()); - } + cv::Mat _out = cv::cvarrToMat(test_array[OUTPUT][0]); + cv::cvtColor(cv::cvarrToMat(test_array[INPUT][0]), _out, fwd_code, _out.channels()); } diff --git a/modules/imgproc/test/test_contours.cpp b/modules/imgproc/test/test_contours.cpp index 6f4315225e..0d432ecc91 100644 --- a/modules/imgproc/test/test_contours.cpp +++ b/modules/imgproc/test/test_contours.cpp @@ -44,372 +44,6 @@ namespace opencv_test { namespace { -class CV_FindContourTest : public cvtest::BaseTest -{ -public: - enum { NUM_IMG = 4 }; - - CV_FindContourTest(); - ~CV_FindContourTest(); - void clear(); - -protected: - int read_params( const cv::FileStorage& fs ); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void run_func(); - - int min_blob_size, max_blob_size; - int blob_count, max_log_blob_count; - int retr_mode, approx_method; - - int min_log_img_width, max_log_img_width; - int min_log_img_height, max_log_img_height; - Size img_size; - int count, count2; - - IplImage* img[NUM_IMG]; - CvMemStorage* storage; - CvSeq *contours, *contours2, *chain; - - static const bool useVeryWideImages = -#if SIZE_MAX <= 0xffffffff - // 32-bit: don't even try the very wide images - false -#else - // 64-bit: test with very wide images - true -#endif - ; -}; - - -CV_FindContourTest::CV_FindContourTest() -{ - int i; - - test_case_count = useVeryWideImages ? 10 : 300; - min_blob_size = 1; - max_blob_size = 50; - max_log_blob_count = 10; - - min_log_img_width = useVeryWideImages ? 17 : 3; - max_log_img_width = useVeryWideImages ? 17 : 10; - - min_log_img_height = 3; - max_log_img_height = 10; - - for( i = 0; i < NUM_IMG; i++ ) - img[i] = 0; - - storage = 0; -} - - -CV_FindContourTest::~CV_FindContourTest() -{ - clear(); -} - - -void CV_FindContourTest::clear() -{ - int i; - - cvtest::BaseTest::clear(); - - for( i = 0; i < NUM_IMG; i++ ) - cvReleaseImage( &img[i] ); - - cvReleaseMemStorage( &storage ); -} - - -int CV_FindContourTest::read_params( const cv::FileStorage& fs ) -{ - int t; - int code = cvtest::BaseTest::read_params( fs ); - - if( code < 0 ) - return code; - - read( find_param( fs, "min_blob_size" ), min_blob_size, min_blob_size ); - read( find_param( fs, "max_blob_size" ), max_blob_size, max_blob_size ); - read( find_param( fs, "max_log_blob_count" ), max_log_blob_count, max_log_blob_count ); - read( find_param( fs, "min_log_img_width" ), min_log_img_width, min_log_img_width ); - read( find_param( fs, "max_log_img_width" ), max_log_img_width, max_log_img_width ); - read( find_param( fs, "min_log_img_height"), min_log_img_height, min_log_img_height ); - read( find_param( fs, "max_log_img_height"), max_log_img_height, max_log_img_height ); - - min_blob_size = cvtest::clipInt( min_blob_size, 1, 100 ); - max_blob_size = cvtest::clipInt( max_blob_size, 1, 100 ); - - if( min_blob_size > max_blob_size ) - CV_SWAP( min_blob_size, max_blob_size, t ); - - max_log_blob_count = cvtest::clipInt( max_log_blob_count, 1, 10 ); - - min_log_img_width = cvtest::clipInt( min_log_img_width, 1, useVeryWideImages ? 17 : 10 ); - min_log_img_width = cvtest::clipInt( max_log_img_width, 1, useVeryWideImages ? 17 : 10 ); - min_log_img_height = cvtest::clipInt( min_log_img_height, 1, 10 ); - min_log_img_height = cvtest::clipInt( max_log_img_height, 1, 10 ); - - if( min_log_img_width > max_log_img_width ) - std::swap( min_log_img_width, max_log_img_width ); - - if (min_log_img_height > max_log_img_height) - std::swap(min_log_img_height, max_log_img_height); - - return 0; -} - - -static void -cvTsGenerateBlobImage( IplImage* img, int min_blob_size, int max_blob_size, - int blob_count, int min_brightness, int max_brightness, - RNG& rng ) -{ - int i; - Size size; - - CV_Assert(img->depth == IPL_DEPTH_8U && img->nChannels == 1); - - cvZero( img ); - - // keep the border clear - cvSetImageROI( img, cvRect(1,1,img->width-2,img->height-2) ); - size = cvGetSize( img ); - - for( i = 0; i < blob_count; i++ ) - { - Point center; - Size axes; - int angle = cvtest::randInt(rng) % 180; - int brightness = cvtest::randInt(rng) % - (max_brightness - min_brightness) + min_brightness; - center.x = cvtest::randInt(rng) % size.width; - center.y = cvtest::randInt(rng) % size.height; - - axes.width = (cvtest::randInt(rng) % - (max_blob_size - min_blob_size) + min_blob_size + 1)/2; - axes.height = (cvtest::randInt(rng) % - (max_blob_size - min_blob_size) + min_blob_size + 1)/2; - - cvEllipse( img, cvPoint(center), cvSize(axes), angle, 0, 360, cvScalar(brightness), CV_FILLED ); - } - - cvResetImageROI( img ); -} - - -static void -cvTsMarkContours( IplImage* img, int val ) -{ - int i, j; - int step = img->widthStep; - - CV_Assert( img->depth == IPL_DEPTH_8U && img->nChannels == 1 && (val&1) != 0); - - for( i = 1; i < img->height - 1; i++ ) - for( j = 1; j < img->width - 1; j++ ) - { - uchar* t = (uchar*)(img->imageData + img->widthStep*i + j); - if( *t == 1 && (t[-step] == 0 || t[-1] == 0 || t[1] == 0 || t[step] == 0)) - *t = (uchar)val; - } - - cvThreshold( img, img, val - 2, val, CV_THRESH_BINARY ); -} - - -int CV_FindContourTest::prepare_test_case( int test_case_idx ) -{ - RNG& rng = ts->get_rng(); - const int min_brightness = 0, max_brightness = 2; - int i, code = cvtest::BaseTest::prepare_test_case( test_case_idx ); - - if( code < 0 ) - return code; - - clear(); - - blob_count = cvRound(exp(cvtest::randReal(rng)*max_log_blob_count*CV_LOG2)); - - img_size.width = cvRound(exp((cvtest::randReal(rng)* - (max_log_img_width - min_log_img_width) + min_log_img_width)*CV_LOG2)); - img_size.height = cvRound(exp((cvtest::randReal(rng)* - (max_log_img_height - min_log_img_height) + min_log_img_height)*CV_LOG2)); - - approx_method = cvtest::randInt( rng ) % 4 + 1; - retr_mode = cvtest::randInt( rng ) % 4; - - storage = cvCreateMemStorage( 1 << 10 ); - - for( i = 0; i < NUM_IMG; i++ ) - img[i] = cvCreateImage( cvSize(img_size), 8, 1 ); - - cvTsGenerateBlobImage( img[0], min_blob_size, max_blob_size, - blob_count, min_brightness, max_brightness, rng ); - - cvCopy( img[0], img[1] ); - cvCopy( img[0], img[2] ); - - cvTsMarkContours( img[1], 255 ); - - return 1; -} - - -void CV_FindContourTest::run_func() -{ - contours = contours2 = chain = 0; - count = cvFindContours( img[2], storage, &contours, sizeof(CvContour), retr_mode, approx_method ); - - cvZero( img[3] ); - - if( contours && retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - cvDrawContours( img[3], contours, cvScalar(255), cvScalar(255), INT_MAX, -1 ); - - cvCopy( img[0], img[2] ); - - count2 = cvFindContours( img[2], storage, &chain, sizeof(CvChain), retr_mode, CV_CHAIN_CODE ); - - if( chain ) - contours2 = cvApproxChains( chain, storage, approx_method, 0, 0, 1 ); - - cvZero( img[2] ); - - if( contours && retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - cvDrawContours( img[2], contours2, cvScalar(255), cvScalar(255), INT_MAX ); -} - - -// the whole testing is done here, run_func() is not utilized in this test -int CV_FindContourTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - - cvCmpS( img[0], 0, img[0], CV_CMP_GT ); - - if( count != count2 ) - { - ts->printf( cvtest::TS::LOG, "The number of contours retrieved with different " - "approximation methods is not the same\n" - "(%d contour(s) for method %d vs %d contour(s) for method %d)\n", - count, approx_method, count2, CV_CHAIN_CODE ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - - if( retr_mode != CV_RETR_EXTERNAL && approx_method < CV_CHAIN_APPROX_TC89_L1 ) - { - Mat _img[4]; - for( int i = 0; i < 4; i++ ) - _img[i] = cvarrToMat(img[i]); - - code = cvtest::cmpEps2(ts, _img[0], _img[3], 0, true, "Comparing original image with the map of filled contours" ); - - if( code < 0 ) - goto _exit_; - - code = cvtest::cmpEps2( ts, _img[1], _img[2], 0, true, - "Comparing contour outline vs manually produced edge map" ); - - if( code < 0 ) - goto _exit_; - } - - if( contours ) - { - CvTreeNodeIterator iterator1; - CvTreeNodeIterator iterator2; - int count3; - - for(int i = 0; i < 2; i++ ) - { - CvTreeNodeIterator iterator; - cvInitTreeNodeIterator( &iterator, i == 0 ? contours : contours2, INT_MAX ); - - for( count3 = 0; cvNextTreeNode( &iterator ) != 0; count3++ ) - ; - - if( count3 != count ) - { - ts->printf( cvtest::TS::LOG, - "The returned number of retrieved contours (using the approx_method = %d) does not match\n" - "to the actual number of contours in the tree/list (returned %d, actual %d)\n", - i == 0 ? approx_method : 0, count, count3 ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - - cvInitTreeNodeIterator( &iterator1, contours, INT_MAX ); - cvInitTreeNodeIterator( &iterator2, contours2, INT_MAX ); - - for( count3 = 0; count3 < count; count3++ ) - { - CvSeq* seq1 = (CvSeq*)cvNextTreeNode( &iterator1 ); - CvSeq* seq2 = (CvSeq*)cvNextTreeNode( &iterator2 ); - CvSeqReader reader1; - CvSeqReader reader2; - - if( !seq1 || !seq2 ) - { - ts->printf( cvtest::TS::LOG, - "There are NULL pointers in the original contour tree or the " - "tree produced by cvApproxChains\n" ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - cvStartReadSeq( seq1, &reader1 ); - cvStartReadSeq( seq2, &reader2 ); - - if( seq1->total != seq2->total ) - { - ts->printf( cvtest::TS::LOG, - "The original contour #%d has %d points, while the corresponding contour has %d point\n", - count3, seq1->total, seq2->total ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - - for(int i = 0; i < seq1->total; i++ ) - { - CvPoint pt1 = {0, 0}; - CvPoint pt2 = {0, 0}; - - CV_READ_SEQ_ELEM( pt1, reader1 ); - CV_READ_SEQ_ELEM( pt2, reader2 ); - - if( pt1.x != pt2.x || pt1.y != pt2.y ) - { - ts->printf( cvtest::TS::LOG, - "The point #%d in the contour #%d is different from the corresponding point " - "in the approximated chain ((%d,%d) vs (%d,%d)", count3, i, pt1.x, pt1.y, pt2.x, pt2.y ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - goto _exit_; - } - } - } - } - -_exit_: - if( code < 0 ) - { -#if 0 - cvNamedWindow( "test", 0 ); - cvShowImage( "test", img[0] ); - cvWaitKey(); -#endif - ts->set_failed_test_info( code ); - } - - return code; -} - -TEST(Imgproc_FindContours, accuracy) { CV_FindContourTest test; test.safe_run(); } - //rotate/flip a quadrant appropriately static void rot(int n, int *x, int *y, int rx, int ry) { diff --git a/modules/imgproc/test/test_convhull.cpp b/modules/imgproc/test/test_convhull.cpp index fb2c306fb1..1ab4205f44 100644 --- a/modules/imgproc/test/test_convhull.cpp +++ b/modules/imgproc/test/test_convhull.cpp @@ -174,15 +174,12 @@ protected: int dims; bool enable_flt_points; - CvMemStorage* storage; CvSeq* points1; CvMat* points2; void* points; void* result; double low_high_range; Scalar low, high; - - bool test_cpp; }; @@ -191,7 +188,6 @@ CV_BaseShapeDescrTest::CV_BaseShapeDescrTest() points1 = 0; points2 = 0; points = 0; - storage = 0; test_case_count = 500; min_log_size = 0; max_log_size = 10; @@ -199,8 +195,6 @@ CV_BaseShapeDescrTest::CV_BaseShapeDescrTest() low_high_range = 50; dims = 2; enable_flt_points = true; - - test_cpp = false; } @@ -213,7 +207,6 @@ CV_BaseShapeDescrTest::~CV_BaseShapeDescrTest() void CV_BaseShapeDescrTest::clear() { cvtest::BaseTest::clear(); - cvReleaseMemStorage( &storage ); cvReleaseMat( &points2 ); points1 = 0; points = 0; @@ -306,7 +299,6 @@ void CV_BaseShapeDescrTest::generate_point_set( void* pointsSet ) int CV_BaseShapeDescrTest::prepare_test_case( int test_case_idx ) { int size; - int use_storage = 0; int point_type; int i; RNG& rng = ts->get_rng(); @@ -315,26 +307,15 @@ int CV_BaseShapeDescrTest::prepare_test_case( int test_case_idx ) clear(); size = cvRound( exp((cvtest::randReal(rng) * (max_log_size - min_log_size) + min_log_size)*CV_LOG2) ); - use_storage = cvtest::randInt(rng) % 2; point_type = CV_MAKETYPE(cvtest::randInt(rng) % (enable_flt_points ? 2 : 1) ? CV_32F : CV_32S, dims); - if( use_storage ) - { - storage = cvCreateMemStorage( (cvtest::randInt(rng)%10 + 1)*1024 ); - points1 = cvCreateSeq( point_type, sizeof(CvSeq), CV_ELEM_SIZE(point_type), storage ); - cvSeqPushMulti( points1, 0, size ); - points = points1; - } - else - { - int rows = 1, cols = size; - if( cvtest::randInt(rng) % 2 ) - rows = size, cols = 1; + int rows = 1, cols = size; + if( cvtest::randInt(rng) % 2 ) + rows = size, cols = 1; - points2 = cvCreateMat( rows, cols, point_type ); - points = points2; - } + points2 = cvCreateMat( rows, cols, point_type ); + points = points2; for( i = 0; i < 4; i++ ) { @@ -350,8 +331,6 @@ int CV_BaseShapeDescrTest::prepare_test_case( int test_case_idx ) } generate_point_set( points ); - - test_cpp = (cvtest::randInt(rng) & 16) == 0; return 1; } @@ -403,8 +382,7 @@ protected: CvSeq* hull1; CvMat* hull2; - void* hull_storage; - int orientation; + bool clockwise; int return_points; }; @@ -413,8 +391,8 @@ CV_ConvHullTest::CV_ConvHullTest() { hull1 = 0; hull2 = 0; - hull_storage = 0; - orientation = return_points = 0; + return_points = 0; + clockwise = false; } @@ -429,43 +407,30 @@ void CV_ConvHullTest::clear() CV_BaseShapeDescrTest::clear(); cvReleaseMat( &hull2 ); hull1 = 0; - hull_storage = 0; } int CV_ConvHullTest::prepare_test_case( int test_case_idx ) { int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - int use_storage_for_hull = 0; RNG& rng = ts->get_rng(); if( code <= 0 ) return code; - orientation = cvtest::randInt(rng) % 2 ? CV_CLOCKWISE : CV_COUNTER_CLOCKWISE; + clockwise = cvtest::randInt(rng) % 2 != 0; return_points = cvtest::randInt(rng) % 2; - use_storage_for_hull = (cvtest::randInt(rng) % 2) && !test_cpp; - if( use_storage_for_hull ) - { - if( !storage ) - storage = cvCreateMemStorage( (cvtest::randInt(rng)%10 + 1)*1024 ); - hull_storage = storage; - } + int rows, cols; + int sz = points1 ? points1->total : points2->cols + points2->rows - 1; + int point_type = points1 ? CV_SEQ_ELTYPE(points1) : CV_MAT_TYPE(points2->type); + + if( cvtest::randInt(rng) % 2 ) + rows = sz, cols = 1; else - { - int rows, cols; - int sz = points1 ? points1->total : points2->cols + points2->rows - 1; - int point_type = points1 ? CV_SEQ_ELTYPE(points1) : CV_MAT_TYPE(points2->type); + rows = 1, cols = sz; - if( cvtest::randInt(rng) % 2 ) - rows = sz, cols = 1; - else - rows = 1, cols = sz; - - hull2 = cvCreateMat( rows, cols, return_points ? point_type : CV_32SC1 ); - hull_storage = hull2; - } + hull2 = cvCreateMat( rows, cols, return_points ? point_type : CV_32SC1 ); return code; } @@ -473,39 +438,33 @@ int CV_ConvHullTest::prepare_test_case( int test_case_idx ) void CV_ConvHullTest::run_func() { - if(!test_cpp) - hull1 = cvConvexHull2( points, hull_storage, orientation, return_points ); - else + cv::Mat _points = cv::cvarrToMat(points); + size_t n = 0; + if( !return_points ) { - cv::Mat _points = cv::cvarrToMat(points); - bool clockwise = orientation == CV_CLOCKWISE; - size_t n = 0; - if( !return_points ) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - else if(_points.type() == CV_32SC2) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - else if(_points.type() == CV_32FC2) - { - std::vector _hull; - cv::convexHull(_points, _hull, clockwise); - n = _hull.size(); - memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); - } - if(hull2->rows > hull2->cols) - hull2->rows = (int)n; - else - hull2->cols = (int)n; + std::vector _hull; + cv::convexHull(_points, _hull, clockwise); + n = _hull.size(); + memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); } + else if(_points.type() == CV_32SC2) + { + std::vector _hull; + cv::convexHull(_points, _hull, clockwise); + n = _hull.size(); + memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); + } + else if(_points.type() == CV_32FC2) + { + std::vector _hull; + cv::convexHull(_points, _hull, clockwise); + n = _hull.size(); + memcpy(hull2->data.ptr, &_hull[0], n*sizeof(_hull[0])); + } + if(hull2->rows > hull2->cols) + hull2->rows = (int)n; + else + hull2->cols = (int)n; } @@ -589,7 +548,7 @@ int CV_ConvHullTest::validate_test_results( int test_case_idx ) float dx0 = pt1.x - pt0.x, dy0 = pt1.y - pt0.y; float dx1 = pt2.x - pt1.x, dy1 = pt2.y - pt1.y; double t = (double)dx0*dy1 - (double)dx1*dy0; - if( (t < 0) ^ (orientation != CV_COUNTER_CLOCKWISE) ) + if( (t < 0) ^ clockwise ) { ts->printf( cvtest::TS::LOG, "The convex hull is not convex or has a wrong orientation (vtx %d)\n", i ); code = cvtest::TS::FAIL_INVALID_OUTPUT; @@ -1056,115 +1015,6 @@ TEST(Imgproc_minEnclosingCircle, regression_16051) { EXPECT_NEAR(2.1024551f, radius, 1e-3); } -/****************************************************************************************\ -* Perimeter Test * -\****************************************************************************************/ - -class CV_PerimeterTest : public CV_BaseShapeDescrTest -{ -public: - CV_PerimeterTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvSlice slice; - int is_closed; - double result; -}; - - -CV_PerimeterTest::CV_PerimeterTest() -{ -} - - -int CV_PerimeterTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - RNG& rng = ts->get_rng(); - int total; - - if( code < 0 ) - return code; - - is_closed = cvtest::randInt(rng) % 2; - - if( points1 ) - { - points1->flags |= CV_SEQ_KIND_CURVE; - if( is_closed ) - points1->flags |= CV_SEQ_FLAG_CLOSED; - total = points1->total; - } - else - total = points2->cols + points2->rows - 1; - - if( (cvtest::randInt(rng) % 3) && !test_cpp ) - { - slice.start_index = cvtest::randInt(rng) % total; - slice.end_index = cvtest::randInt(rng) % total; - } - else - slice = CV_WHOLE_SEQ; - - return 1; -} - - -void CV_PerimeterTest::run_func() -{ - if(!test_cpp) - result = cvArcLength( points, slice, points1 ? -1 : is_closed ); - else - result = cv::arcLength(cv::cvarrToMat(points), - !points1 ? is_closed != 0 : (points1->flags & CV_SEQ_FLAG_CLOSED) != 0); -} - - -int CV_PerimeterTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, len = slice.end_index - slice.start_index, total = points2->cols + points2->rows - 1; - double result0 = 0; - Point2f prev_pt, pt; - CvPoint2D32f *ptr; - - if( len < 0 ) - len += total; - - len = MIN( len, total ); - //len -= !is_closed && len == total; - - ptr = (CvPoint2D32f*)points2->data.fl; - prev_pt = ptr[(is_closed ? slice.start_index+len-1 : slice.start_index) % total]; - - for( i = 0; i < len + (len < total && (!is_closed || len==1)); i++ ) - { - pt = ptr[(i + slice.start_index) % total]; - double dx = pt.x - prev_pt.x, dy = pt.y - prev_pt.y; - result0 += sqrt(dx*dx + dy*dy); - prev_pt = pt; - } - - if( cvIsNaN(result) || cvIsInf(result) ) - { - ts->printf( cvtest::TS::LOG, "cvArcLength() returned invalid value (%g)\n", result ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - else if( fabs(result - result0) > FLT_EPSILON*100*result0 ) - { - ts->printf( cvtest::TS::LOG, "The function returned %g, while the correct result is %g\n", result, result0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - /****************************************************************************************\ * FitEllipse Test * \****************************************************************************************/ @@ -1530,7 +1380,7 @@ int CV_FitLineTest::prepare_test_case( int test_case_idx ) max_log_size = MAX(min_log_size,max_log_size); int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); dist_type = cvtest::randInt(rng) % 6 + 1; - dist_type += dist_type == CV_DIST_C; + dist_type += dist_type == cv::DIST_C; reps = 0.1; aeps = 0.01; return code; } @@ -1624,290 +1474,15 @@ _exit_: return code; } -/****************************************************************************************\ -* ContourMoments Test * -\****************************************************************************************/ - - -static void -cvTsGenerateTousledBlob( CvPoint2D32f center, CvSize2D32f axes, - double max_r_scale, double angle, CvArr* points, RNG& rng ) -{ - int i, total, point_type; - uchar* data = 0; - CvSeqReader reader; - memset( &reader, 0, sizeof(reader) ); - - if( CV_IS_SEQ(points) ) - { - CvSeq* ptseq = (CvSeq*)points; - total = ptseq->total; - point_type = CV_SEQ_ELTYPE(ptseq); - cvStartReadSeq( ptseq, &reader ); - } - else - { - CvMat* ptm = (CvMat*)points; - CV_Assert( CV_IS_MAT(ptm) && CV_IS_MAT_CONT(ptm->type) ); - total = ptm->rows + ptm->cols - 1; - point_type = CV_MAT_TYPE(ptm->type); - data = ptm->data.ptr; - } - - CV_Assert( point_type == CV_32SC2 || point_type == CV_32FC2 ); - - for( i = 0; i < total; i++ ) - { - CvPoint* pp; - Point2f p; - - double phi0 = 2*CV_PI*i/total; - double phi = CV_PI*angle/180.; - double t = cvtest::randReal(rng)*max_r_scale + (1 - max_r_scale); - double ta = axes.height*t; - double tb = axes.width*t; - double c0 = cos(phi0)*ta, s0 = sin(phi0)*tb; - double c = cos(phi), s = sin(phi); - p.x = (float)(c0*c - s0*s + center.x); - p.y = (float)(c0*s + s0*c + center.y); - - if( reader.ptr ) - { - pp = (CvPoint*)reader.ptr; - CV_NEXT_SEQ_ELEM( sizeof(*pp), reader ); - } - else - pp = ((CvPoint*)data) + i; - - if( point_type == CV_32SC2 ) - { - pp->x = cvRound(p.x); - pp->y = cvRound(p.y); - } - else - *(CvPoint2D32f*)pp = cvPoint2D32f(p); - } -} - - -class CV_ContourMomentsTest : public CV_BaseShapeDescrTest -{ -public: - CV_ContourMomentsTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void generate_point_set( void* points ); - void run_func(void); - int validate_test_results( int test_case_idx ); - CvMoments moments0, moments; - double area0, area; - Size2f axes; - Point2f center; - int max_max_r_scale; - double max_r_scale, angle; - Size img_size; -}; - - -CV_ContourMomentsTest::CV_ContourMomentsTest() -{ - min_log_size = 3; - max_log_size = 8; - max_max_r_scale = 15; - low_high_range = 200; - enable_flt_points = false; -} - - -void CV_ContourMomentsTest::generate_point_set( void* pointsSet ) -{ - RNG& rng = ts->get_rng(); - float max_sz; - - axes.width = (float)((cvtest::randReal(rng)*0.9 + 0.1)*low_high_range); - axes.height = (float)((cvtest::randReal(rng)*0.9 + 0.1)*low_high_range); - max_sz = MAX(axes.width, axes.height); - - img_size.width = img_size.height = cvRound(low_high_range*2.2); - - center.x = (float)(img_size.width*0.5 + (cvtest::randReal(rng)-0.5)*(img_size.width - max_sz*2)*0.8); - center.y = (float)(img_size.height*0.5 + (cvtest::randReal(rng)-0.5)*(img_size.height - max_sz*2)*0.8); - - CV_Assert( 0 < center.x - max_sz && center.x + max_sz < img_size.width && - 0 < center.y - max_sz && center.y + max_sz < img_size.height ); - - max_r_scale = cvtest::randReal(rng)*max_max_r_scale*0.01; - angle = cvtest::randReal(rng)*360; - - cvTsGenerateTousledBlob( cvPoint2D32f(center), cvSize2D32f(axes), max_r_scale, angle, pointsSet, rng ); - - if( points1 ) - points1->flags = CV_SEQ_MAGIC_VAL + CV_SEQ_POLYGON; -} - - -int CV_ContourMomentsTest::prepare_test_case( int test_case_idx ) -{ - min_log_size = MAX(min_log_size,3); - max_log_size = MIN(max_log_size,8); - max_log_size = MAX(min_log_size,max_log_size); - int code = CV_BaseShapeDescrTest::prepare_test_case( test_case_idx ); - return code; -} - - -void CV_ContourMomentsTest::run_func() -{ - moments = cvMoments(cv::moments(cv::cvarrToMat(points))); - area = cv::contourArea(cv::cvarrToMat(points)); -} - - -int CV_ContourMomentsTest::validate_test_results( int test_case_idx ) -{ - int code = CV_BaseShapeDescrTest::validate_test_results( test_case_idx ); - int i, n = (int)(sizeof(moments)/sizeof(moments.inv_sqrt_m00)); - CvMat* img = cvCreateMat( img_size.height, img_size.width, CV_8UC1 ); - CvPoint* pt = (CvPoint*)points2->data.i; - int count = points2->cols + points2->rows - 1; - double max_v0 = 0; - - cvZero(img); - cvFillPoly( img, &pt, &count, 1, cvScalarAll(1)); - cvMoments( img, &moments0 ); - - for( i = 0; i < n; i++ ) - { - double t = fabs((&moments0.m00)[i]); - max_v0 = MAX(max_v0, t); - } - - for( i = 0; i <= n; i++ ) - { - double v = i < n ? (&moments.m00)[i] : area; - double v0 = i < n ? (&moments0.m00)[i] : moments0.m00; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( cvtest::TS::LOG, - "The contour %s is invalid (=%g)\n", i < n ? "moment" : "area", v ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - break; - } - - if( fabs(v - v0) > 0.1*max_v0 ) - { - ts->printf( cvtest::TS::LOG, - "The computed contour %s is %g, while it should be %g\n", - i < n ? "moment" : "area", v, v0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - break; - } - } - - if( code < 0 ) - { - ts->set_failed_test_info( code ); - } - - cvReleaseMat( &img ); - return code; -} - - -////////////////////////////////////// Perimeter/Area/Slice test /////////////////////////////////// - -class CV_PerimeterAreaSliceTest : public cvtest::BaseTest -{ -public: - CV_PerimeterAreaSliceTest(); - ~CV_PerimeterAreaSliceTest(); -protected: - void run(int); -}; - -CV_PerimeterAreaSliceTest::CV_PerimeterAreaSliceTest() -{ -} -CV_PerimeterAreaSliceTest::~CV_PerimeterAreaSliceTest() {} - -void CV_PerimeterAreaSliceTest::run( int ) -{ - Ptr storage(cvCreateMemStorage()); - RNG& rng = theRNG(); - const double min_r = 90, max_r = 120; - - for( int i = 0; i < 100; i++ ) - { - ts->update_context( this, i, true ); - int n = rng.uniform(3, 30); - cvClearMemStorage(storage); - CvSeq* contour = cvCreateSeq(CV_SEQ_POLYGON, sizeof(CvSeq), sizeof(CvPoint), storage); - double dphi = CV_PI*2/n; - Point center; - center.x = rng.uniform(cvCeil(max_r), cvFloor(640-max_r)); - center.y = rng.uniform(cvCeil(max_r), cvFloor(480-max_r)); - - for( int j = 0; j < n; j++ ) - { - CvPoint pt = CV_STRUCT_INITIALIZER; - double r = rng.uniform(min_r, max_r); - double phi = j*dphi; - pt.x = cvRound(center.x + r*cos(phi)); - pt.y = cvRound(center.y - r*sin(phi)); - cvSeqPush(contour, &pt); - } - - CvSlice slice = {0, 0}; - for(;;) - { - slice.start_index = rng.uniform(-n/2, 3*n/2); - slice.end_index = rng.uniform(-n/2, 3*n/2); - int len = cvSliceLength(slice, contour); - if( len > 2 ) - break; - } - CvSeq *cslice = cvSeqSlice(contour, slice); - /*printf( "%d. (%d, %d) of %d, length = %d, length1 = %d\n", - i, slice.start_index, slice.end_index, - contour->total, cvSliceLength(slice, contour), cslice->total ); - - double area0 = cvContourArea(cslice); - double area1 = cvContourArea(contour, slice); - if( area0 != area1 ) - { - ts->printf(cvtest::TS::LOG, - "The contour area slice is computed differently (%g vs %g)\n", area0, area1 ); - ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY ); - return; - }*/ - - double len0 = cvArcLength(cslice, CV_WHOLE_SEQ, 1); - double len1 = cvArcLength(contour, slice, 1); - if( len0 != len1 ) - { - ts->printf(cvtest::TS::LOG, - "The contour arc length is computed differently (%g vs %g)\n", len0, len1 ); - ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY ); - return; - } - } - ts->set_failed_test_info(cvtest::TS::OK); -} - TEST(Imgproc_ConvexHull, accuracy) { CV_ConvHullTest test; test.safe_run(); } TEST(Imgproc_MinAreaRect, accuracy) { CV_MinAreaRectTest test; test.safe_run(); } TEST(Imgproc_MinTriangle, accuracy) { CV_MinTriangleTest test; test.safe_run(); } TEST(Imgproc_MinCircle, accuracy) { CV_MinCircleTest test; test.safe_run(); } TEST(Imgproc_MinCircle2, accuracy) { CV_MinCircleTest2 test; test.safe_run(); } -TEST(Imgproc_ContourPerimeter, accuracy) { CV_PerimeterTest test; test.safe_run(); } TEST(Imgproc_FitEllipse, accuracy) { CV_FitEllipseTest test; test.safe_run(); } TEST(Imgproc_FitEllipse, parallel) { CV_FitEllipseParallelTest test; test.safe_run(); } TEST(Imgproc_FitLine, accuracy) { CV_FitLineTest test; test.safe_run(); } -TEST(Imgproc_ContourMoments, accuracy) { CV_ContourMomentsTest test; test.safe_run(); } -TEST(Imgproc_ContourPerimeterSlice, accuracy) { CV_PerimeterAreaSliceTest test; test.safe_run(); } TEST(Imgproc_FitEllipse, small) { CV_FitEllipseSmallTest test; test.safe_run(); } diff --git a/modules/imgproc/test/test_distancetransform.cpp b/modules/imgproc/test/test_distancetransform.cpp index 32fc7aa2c3..8ebe8fde02 100644 --- a/modules/imgproc/test/test_distancetransform.cpp +++ b/modules/imgproc/test/test_distancetransform.cpp @@ -43,246 +43,6 @@ namespace opencv_test { namespace { -class CV_DisTransTest : public cvtest::ArrayTest -{ -public: - CV_DisTransTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ); - int prepare_test_case( int test_case_idx ); - - int mask_size; - int dist_type; - int fill_labels; - float mask[3]; -}; - - -CV_DisTransTest::CV_DisTransTest() -{ - test_array[INPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - optional_mask = false; - element_wise_relative_error = true; -} - - -void CV_DisTransTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - types[INPUT][0] = CV_8UC1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_32FC1; - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_32SC1; - - if( cvtest::randInt(rng) & 1 ) - { - mask_size = 3; - } - else - { - mask_size = 5; - } - - dist_type = cvtest::randInt(rng) % 3; - dist_type = dist_type == 0 ? CV_DIST_C : dist_type == 1 ? CV_DIST_L1 : CV_DIST_L2; - - // for now, check only the "labeled" distance transform mode - fill_labels = 0; - - if( !fill_labels ) - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = cvSize(0,0); -} - - -double CV_DisTransTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - Size sz = test_mat[INPUT][0].size(); - return dist_type == CV_DIST_C || dist_type == CV_DIST_L1 ? 0 : 0.01*MAX(sz.width, sz.height); -} - - -void CV_DisTransTest::get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ) -{ - cvtest::ArrayTest::get_minmax_bounds( i, j, type, low, high ); - if( i == INPUT && CV_MAT_DEPTH(type) == CV_8U ) - { - low = Scalar::all(0); - high = Scalar::all(10); - } -} - -int CV_DisTransTest::prepare_test_case( int test_case_idx ) -{ - int code = cvtest::ArrayTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - // the function's response to an "all-nonzeros" image is not determined, - // so put at least one zero point - Mat& mat = test_mat[INPUT][0]; - RNG& rng = ts->get_rng(); - int i = cvtest::randInt(rng) % mat.rows; - int j = cvtest::randInt(rng) % mat.cols; - mat.at(i,j) = 0; - } - - return code; -} - - -void CV_DisTransTest::run_func() -{ - cvDistTransform( test_array[INPUT][0], test_array[OUTPUT][0], dist_type, mask_size, - dist_type == CV_DIST_USER ? mask : 0, test_array[OUTPUT][1] ); -} - - -static void -cvTsDistTransform( const CvMat* _src, CvMat* _dst, int dist_type, - int mask_size, float* _mask, CvMat* /*_labels*/ ) -{ - int i, j, k; - int width = _src->cols, height = _src->rows; - const float init_val = 1e6; - float mask[3]; - CvMat* temp; - int ofs[16] = {0}; - float delta[16]; - int tstep, count; - - CV_Assert( mask_size == 3 || mask_size == 5 ); - - if( dist_type == CV_DIST_USER ) - memcpy( mask, _mask, sizeof(mask) ); - else if( dist_type == CV_DIST_C ) - { - mask_size = 3; - mask[0] = mask[1] = 1.f; - } - else if( dist_type == CV_DIST_L1 ) - { - mask_size = 3; - mask[0] = 1.f; - mask[1] = 2.f; - } - else if( mask_size == 3 ) - { - mask[0] = 0.955f; - mask[1] = 1.3693f; - } - else - { - mask[0] = 1.0f; - mask[1] = 1.4f; - mask[2] = 2.1969f; - } - - temp = cvCreateMat( height + mask_size-1, width + mask_size-1, CV_32F ); - tstep = temp->step / sizeof(float); - - if( mask_size == 3 ) - { - count = 4; - ofs[0] = -1; delta[0] = mask[0]; - ofs[1] = -tstep-1; delta[1] = mask[1]; - ofs[2] = -tstep; delta[2] = mask[0]; - ofs[3] = -tstep+1; delta[3] = mask[1]; - } - else - { - count = 8; - ofs[0] = -1; delta[0] = mask[0]; - ofs[1] = -tstep-2; delta[1] = mask[2]; - ofs[2] = -tstep-1; delta[2] = mask[1]; - ofs[3] = -tstep; delta[3] = mask[0]; - ofs[4] = -tstep+1; delta[4] = mask[1]; - ofs[5] = -tstep+2; delta[5] = mask[2]; - ofs[6] = -tstep*2-1; delta[6] = mask[2]; - ofs[7] = -tstep*2+1; delta[7] = mask[2]; - } - - for( i = 0; i < mask_size/2; i++ ) - { - float* t0 = (float*)(temp->data.ptr + i*temp->step); - float* t1 = (float*)(temp->data.ptr + (temp->rows - i - 1)*temp->step); - - for( j = 0; j < width + mask_size - 1; j++ ) - t0[j] = t1[j] = init_val; - } - - for( i = 0; i < height; i++ ) - { - uchar* s = _src->data.ptr + i*_src->step; - float* tmp = (float*)(temp->data.ptr + temp->step*(i + (mask_size/2))) + (mask_size/2); - - for( j = 0; j < mask_size/2; j++ ) - tmp[-j-1] = tmp[j + width] = init_val; - - for( j = 0; j < width; j++ ) - { - if( s[j] == 0 ) - tmp[j] = 0; - else - { - float min_dist = init_val; - for( k = 0; k < count; k++ ) - { - float t = tmp[j+ofs[k]] + delta[k]; - if( min_dist > t ) - min_dist = t; - } - tmp[j] = min_dist; - } - } - } - - for( i = height - 1; i >= 0; i-- ) - { - float* d = (float*)(_dst->data.ptr + i*_dst->step); - float* tmp = (float*)(temp->data.ptr + temp->step*(i + (mask_size/2))) + (mask_size/2); - - for( j = width - 1; j >= 0; j-- ) - { - float min_dist = tmp[j]; - if( min_dist > mask[0] ) - { - for( k = 0; k < count; k++ ) - { - float t = tmp[j-ofs[k]] + delta[k]; - if( min_dist > t ) - min_dist = t; - } - tmp[j] = min_dist; - } - d[j] = min_dist; - } - } - - cvReleaseMat( &temp ); -} - - -void CV_DisTransTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat _input = cvMat(test_mat[INPUT][0]), _output = cvMat(test_mat[REF_OUTPUT][0]); - - cvTsDistTransform( &_input, &_output, dist_type, mask_size, mask, 0 ); -} - - -TEST(Imgproc_DistanceTransform, accuracy) { CV_DisTransTest test; test.safe_run(); } - BIGDATA_TEST(Imgproc_DistanceTransform, large_image_12218) { const int lls_maxcnt = 79992000; // labels's maximum count diff --git a/modules/imgproc/test/test_drawing.cpp b/modules/imgproc/test/test_drawing.cpp index f943299585..cb120110e8 100644 --- a/modules/imgproc/test/test_drawing.cpp +++ b/modules/imgproc/test/test_drawing.cpp @@ -131,7 +131,7 @@ void CV_DrawingTest_CPP::draw( Mat& img ) p2 = Point(3,imgSize.height+1000); if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) - circle( img, Point(500,300), 50, cvColorToScalar(255,CV_8UC3), 5, 8, 1 ); // draw + circle( img, Point(500,300), 50, Scalar(255, 0, 0), 5, 8, 1 ); // draw p1 = Point(imgSize.width,1), p2 = Point(imgSize.width,3); if( clipLine(Rect(0,0,imgSize.width,imgSize.height), p1, p2) && clipLine(imgSize, p1, p2) ) @@ -147,7 +147,7 @@ void CV_DrawingTest_CPP::draw( Mat& img ) ellipse2Poly( Point(430,180), Size(100,150), 30, 0, 150, 20, polyline ); pts = &polyline[0]; n = (int)polyline.size(); - polylines( img, &pts, &n, 1, false, Scalar(0,0,150), 4, CV_AA ); + polylines( img, &pts, &n, 1, false, Scalar(0,0,150), 4, cv::LINE_AA ); n = 0; for( vector::const_iterator it = polyline.begin(); n < (int)polyline.size()-1; ++it, n++ ) { @@ -195,43 +195,43 @@ void CV_DrawingTest_CPP::draw( Mat& img ) textSize = getTextSize( text2, FONT_HERSHEY_SIMPLEX, fontScale, thickness, &baseline); textOrg = Point(5,5)+Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, cv::LINE_AA); fontScale = 1; textSize = getTextSize( text2, FONT_HERSHEY_PLAIN, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_PLAIN, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_PLAIN, fontScale, color, thickness, cv::LINE_AA); fontScale = 0.5; textSize = getTextSize( text2, FONT_HERSHEY_DUPLEX, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_DUPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_DUPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize( text2, FONT_HERSHEY_COMPLEX, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize( text2, FONT_HERSHEY_TRIPLEX, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_TRIPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_TRIPLEX, fontScale, color, thickness, cv::LINE_AA); fontScale = 1; textSize = getTextSize( text2, FONT_HERSHEY_COMPLEX_SMALL, fontScale, thickness, &baseline); textOrg += Point(0,180) + Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX_SMALL, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX_SMALL, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize( text2, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize( text2, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, color, thickness, cv::LINE_AA); dist = 15, fontScale = 0.5; textSize = getTextSize( text2, FONT_ITALIC, fontScale, thickness, &baseline); textOrg += Point(0,textSize.height+dist); - putText(img, text2, textOrg, FONT_ITALIC, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_ITALIC, fontScale, color, thickness, cv::LINE_AA); } int CV_DrawingTest_CPP::checkLineIterator( Mat& img ) @@ -324,7 +324,7 @@ void CV_DrawingTest_Far::draw(Mat& img) p2 = Point(32768 + 3, imgSize.height + 1000); if (clipLine(Rect(32768 + 0, 0, imgSize.width, imgSize.height), p1, p2) && clipLine(imgSize, p1, p2)) - circle(img, Point(65536 + 500, 300), 50, cvColorToScalar(255, CV_8UC3), 5, 8, 1); // draw + circle(img, Point(65536 + 500, 300), 50, Scalar(255, 0, 0), 5, 8, 1); // draw p1 = Point(imgSize.width, 1), p2 = Point(imgSize.width, 3); if (clipLine(Rect(32768 + 0, 0, imgSize.width, imgSize.height), p1, p2) && clipLine(imgSize, p1, p2)) @@ -340,7 +340,7 @@ void CV_DrawingTest_Far::draw(Mat& img) ellipse2Poly(Point(32768 + 430, 180), Size(100, 150), 30, 0, 150, 20, polyline); pts = &polyline[0]; n = (int)polyline.size(); - polylines(img, &pts, &n, 1, false, Scalar(0, 0, 150), 4, CV_AA); + polylines(img, &pts, &n, 1, false, Scalar(0, 0, 150), 4, cv::LINE_AA); n = 0; for (vector::const_iterator it = polyline.begin(); n < (int)polyline.size() - 1; ++it, n++) { @@ -388,43 +388,43 @@ void CV_DrawingTest_Far::draw(Mat& img) textSize = getTextSize(text2, FONT_HERSHEY_SIMPLEX, fontScale, thickness, &baseline); textOrg = Point(32768 + 5, 5) + Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, cv::LINE_AA); fontScale = 1; textSize = getTextSize(text2, FONT_HERSHEY_PLAIN, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_PLAIN, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_PLAIN, fontScale, color, thickness, cv::LINE_AA); fontScale = 0.5; textSize = getTextSize(text2, FONT_HERSHEY_DUPLEX, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_DUPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_DUPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize(text2, FONT_HERSHEY_COMPLEX, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize(text2, FONT_HERSHEY_TRIPLEX, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_TRIPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_TRIPLEX, fontScale, color, thickness, cv::LINE_AA); fontScale = 1; textSize = getTextSize(text2, FONT_HERSHEY_COMPLEX_SMALL, fontScale, thickness, &baseline); textOrg += Point(0, 180) + Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX_SMALL, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_COMPLEX_SMALL, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize(text2, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale, color, thickness, cv::LINE_AA); textSize = getTextSize(text2, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_HERSHEY_SCRIPT_COMPLEX, fontScale, color, thickness, cv::LINE_AA); dist = 15, fontScale = 0.5; textSize = getTextSize(text2, FONT_ITALIC, fontScale, thickness, &baseline); textOrg += Point(0, textSize.height + dist); - putText(img, text2, textOrg, FONT_ITALIC, fontScale, color, thickness, CV_AA); + putText(img, text2, textOrg, FONT_ITALIC, fontScale, color, thickness, cv::LINE_AA); img = img(Rect(32768, 0, 600, 400)).clone(); } @@ -520,7 +520,7 @@ protected: Size textSize = getTextSize(*line, *font | italic, fontScale, thickness, &baseline); Point textOrg(0, textSize.height + 2); Mat img(textSize + Size(0, baseline), CV_8UC3, Scalar(255, 255, 255)); - putText(img, *line, textOrg, *font | italic, fontScale, color, thickness, CV_AA); + putText(img, *line, textOrg, *font | italic, fontScale, color, thickness, cv::LINE_AA); results.push_back(img); bigSize.width = max(bigSize.width, img.size().width); diff --git a/modules/imgproc/test/test_filter.cpp b/modules/imgproc/test/test_filter.cpp index d27258fe0c..8de6a91216 100644 --- a/modules/imgproc/test/test_filter.cpp +++ b/modules/imgproc/test/test_filter.cpp @@ -169,277 +169,6 @@ int CV_FilterBaseTest::prepare_test_case( int test_case_idx ) return code; } - -///////////////////////// - -class CV_MorphologyBaseTest : public CV_FilterBaseTest -{ -public: - CV_MorphologyBaseTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - int prepare_test_case( int test_case_idx ); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - int optype, optype_min, optype_max; - int shape; - IplConvKernel* element; -}; - - -CV_MorphologyBaseTest::CV_MorphologyBaseTest() : CV_FilterBaseTest( false ) -{ - shape = -1; - element = 0; - optype = optype_min = optype_max = -1; -} - - -void CV_MorphologyBaseTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvtest::randInt(rng) % 4; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - int cn = CV_MAT_CN(types[INPUT][0]); - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, cn); - shape = cvtest::randInt(rng) % 4; - if( shape >= 3 ) - shape = CV_SHAPE_CUSTOM; - else - sizes[INPUT][1] = cvSize(0,0); - optype = cvtest::randInt(rng) % (optype_max - optype_min + 1) + optype_min; -} - - -double CV_MorphologyBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return test_mat[INPUT][0].depth() < CV_32F || - (optype == CV_MOP_ERODE || optype == CV_MOP_DILATE || - optype == CV_MOP_OPEN || optype == CV_MOP_CLOSE) ? 0 : 1e-5; -} - - -int CV_MorphologyBaseTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_FilterBaseTest::prepare_test_case( test_case_idx ); - vector eldata; - - if( code <= 0 ) - return code; - - if( shape == CV_SHAPE_CUSTOM ) - { - eldata.resize(aperture_size.width*aperture_size.height); - const uchar* src = test_mat[INPUT][1].ptr(); - int srcstep = (int)test_mat[INPUT][1].step; - int i, j, nonzero = 0; - - for( i = 0; i < aperture_size.height; i++ ) - { - for( j = 0; j < aperture_size.width; j++ ) - { - eldata[i*aperture_size.width + j] = src[i*srcstep + j]; - nonzero += src[i*srcstep + j] != 0; - } - } - - if( nonzero == 0 ) - eldata[anchor.y*aperture_size.width + anchor.x] = 1; - } - - cvReleaseStructuringElement( &element ); - element = cvCreateStructuringElementEx( aperture_size.width, aperture_size.height, - anchor.x, anchor.y, shape, eldata.empty() ? 0 : &eldata[0] ); - return code; -} - - -void CV_MorphologyBaseTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0], &dst = test_mat[REF_OUTPUT][0]; - Mat _ielement(element->nRows, element->nCols, CV_32S, element->values); - Mat _element; - _ielement.convertTo(_element, CV_8U); - Point _anchor(element->anchorX, element->anchorY); - int _border = BORDER_REPLICATE; - - if( optype == CV_MOP_ERODE ) - { - cvtest::erode( src, dst, _element, _anchor, _border ); - } - else if( optype == CV_MOP_DILATE ) - { - cvtest::dilate( src, dst, _element, _anchor, _border ); - } - else - { - Mat temp; - if( optype == CV_MOP_OPEN ) - { - cvtest::erode( src, temp, _element, _anchor, _border ); - cvtest::dilate( temp, dst, _element, _anchor, _border ); - } - else if( optype == CV_MOP_CLOSE ) - { - cvtest::dilate( src, temp, _element, _anchor, _border ); - cvtest::erode( temp, dst, _element, _anchor, _border ); - } - else if( optype == CV_MOP_GRADIENT ) - { - cvtest::erode( src, temp, _element, _anchor, _border ); - cvtest::dilate( src, dst, _element, _anchor, _border ); - cvtest::add( dst, 1, temp, -1, Scalar::all(0), dst, dst.type() ); - } - else if( optype == CV_MOP_TOPHAT ) - { - cvtest::erode( src, temp, _element, _anchor, _border ); - cvtest::dilate( temp, dst, _element, _anchor, _border ); - cvtest::add( src, 1, dst, -1, Scalar::all(0), dst, dst.type() ); - } - else if( optype == CV_MOP_BLACKHAT ) - { - cvtest::dilate( src, temp, _element, _anchor, _border ); - cvtest::erode( temp, dst, _element, _anchor, _border ); - cvtest::add( dst, 1, src, -1, Scalar::all(0), dst, dst.type() ); - } - else - CV_Error( CV_StsBadArg, "Unknown operation" ); - } - - cvReleaseStructuringElement( &element ); -} - - -/////////////// erode /////////////// - -class CV_ErodeTest : public CV_MorphologyBaseTest -{ -public: - CV_ErodeTest(); -protected: - void run_func(); -}; - - -CV_ErodeTest::CV_ErodeTest() -{ - optype_min = optype_max = CV_MOP_ERODE; -} - - -void CV_ErodeTest::run_func() -{ - cvErode( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], element, 1 ); -} - - -/////////////// dilate /////////////// - -class CV_DilateTest : public CV_MorphologyBaseTest -{ -public: - CV_DilateTest(); -protected: - void run_func(); -}; - - -CV_DilateTest::CV_DilateTest() -{ - optype_min = optype_max = CV_MOP_DILATE; -} - - -void CV_DilateTest::run_func() -{ - cvDilate( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], element, 1 ); -} - -/////////////// morphEx /////////////// - -class CV_MorphExTest : public CV_MorphologyBaseTest -{ -public: - CV_MorphExTest(); -protected: - void run_func(); -}; - - -CV_MorphExTest::CV_MorphExTest() -{ - optype_min = CV_MOP_ERODE; - optype_max = CV_MOP_BLACKHAT; -} - - -void CV_MorphExTest::run_func() -{ - cvMorphologyEx( test_array[inplace ? OUTPUT : INPUT][0], - test_array[OUTPUT][0], 0, element, optype, 1 ); -} - -/////////////// generic filter /////////////// - -class CV_FilterTest : public CV_FilterBaseTest -{ -public: - CV_FilterTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_FilterTest::CV_FilterTest() : CV_FilterBaseTest( true ) -{ -} - - -void CV_FilterTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - RNG& rng = ts->get_rng(); - int depth = cvtest::randInt(rng)%4; - int cn = CV_MAT_CN(types[INPUT][0]); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, cn); -} - - -double CV_FilterTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth <= CV_8S ? 2 : depth <= CV_32S ? 32 : - depth == CV_32F ? 1e-4 : 1e-10; -} - - -void CV_FilterTest::run_func() -{ - CvMat kernel = cvMat(test_mat[INPUT][1]); - cvFilter2D( test_array[inplace ? OUTPUT : INPUT][0], - test_array[OUTPUT][0], &kernel, cvPoint(anchor)); -} - - -void CV_FilterTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - cvtest::filter2D( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], test_mat[REF_OUTPUT][0].type(), - test_mat[INPUT][1], anchor, 0, BORDER_REPLICATE ); -} - - //////////////////////// class CV_DerivBaseTest : public CV_FilterBaseTest @@ -680,603 +409,6 @@ void CV_LaplaceTest::prepare_to_validation( int /*test_case_idx*/ ) kernel, anchor, 0, BORDER_REPLICATE ); } - -//////////////////////////////////////////////////////////// - -class CV_SmoothBaseTest : public CV_FilterBaseTest -{ -public: - CV_SmoothBaseTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - const char* smooth_type; - - void dump_test_case(int test_case_idx, std::ostream* out) CV_OVERRIDE - { - CV_FilterBaseTest::dump_test_case(test_case_idx, out); - *out << "smooth_type=" << smooth_type << std::endl; - } -}; - - -CV_SmoothBaseTest::CV_SmoothBaseTest() : CV_FilterBaseTest( true ) -{ - smooth_type = ""; -} - - -void CV_SmoothBaseTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvtest::randInt(rng) % 2; - int cn = CV_MAT_CN(types[INPUT][0]); - depth = depth == 0 ? CV_8U : CV_32F; - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - anchor.x = cvtest::randInt(rng)%(max_aperture_size/2+1); - anchor.y = cvtest::randInt(rng)%(max_aperture_size/2+1); - aperture_size.width = anchor.x*2 + 1; - aperture_size.height = anchor.y*2 + 1; - sizes[INPUT][1] = aperture_size; -} - - -double CV_SmoothBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth < CV_32F ? 1 : 1e-5; -} - - -/////////////// blur /////////////// - -class CV_BlurTest : public CV_SmoothBaseTest -{ -public: - CV_BlurTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - bool normalize; -}; - - -CV_BlurTest::CV_BlurTest() -{ -} - - -void CV_BlurTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvtest::randInt(rng) % 4; - int cn = (cvtest::randInt(rng) % 4) + 1; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - types[OUTPUT][0] = types[REF_OUTPUT][0] = types[INPUT][0] = CV_MAKETYPE(depth, cn); - normalize = cvtest::randInt(rng) % 2 != 0; - if( !normalize ) - { - types[INPUT][0] = CV_MAKETYPE(depth, 1); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth==CV_8U?CV_16S:CV_32F,1); - } -} - - -void CV_BlurTest::run_func() -{ - cvSmooth( inplace ? test_array[OUTPUT][0] : test_array[INPUT][0], - test_array[OUTPUT][0], normalize ? CV_BLUR : CV_BLUR_NO_SCALE, - aperture_size.width, aperture_size.height ); -} - - -int CV_BlurTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_SmoothBaseTest::prepare_test_case( test_case_idx ); - return code > 0 && !normalize && test_mat[INPUT][0].channels() > 1 ? 0 : code; -} - - -void CV_BlurTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat kernel(aperture_size, CV_64F); - kernel.setTo(Scalar::all(normalize ? 1./(aperture_size.width*aperture_size.height) : 1.)); - cvtest::filter2D( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], test_mat[REF_OUTPUT][0].depth(), - kernel, anchor, 0, BORDER_REPLICATE ); -} - - -/////////////// gaussian /////////////// - -class CV_GaussianBlurTest : public CV_SmoothBaseTest -{ -public: - CV_GaussianBlurTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); - double sigma; - int param1, param2; - - void dump_test_case(int test_case_idx, std::ostream* out) CV_OVERRIDE - { - CV_SmoothBaseTest::dump_test_case(test_case_idx, out); - *out << "kernel=(" << param1 << ", " << param2 << ") sigma=" << sigma << std::endl; - } -}; - - -CV_GaussianBlurTest::CV_GaussianBlurTest() : CV_SmoothBaseTest() -{ - sigma = 0.; - smooth_type = "Gaussian"; -} - - -double CV_GaussianBlurTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth <= CV_8S ? 8 : 1e-5; -} - - -void CV_GaussianBlurTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - int kernel_case = cvtest::randInt(rng) % 2; - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - anchor = cvPoint(aperture_size.width/2,aperture_size.height/2); - - sigma = exp(cvtest::randReal(rng)*5-2); - param1 = aperture_size.width; - param2 = aperture_size.height; - - if( kernel_case == 0 ) - sigma = 0.; -} - -void CV_GaussianBlurTest::run_func() -{ - cvSmooth( test_array[inplace ? OUTPUT : INPUT][0], - test_array[OUTPUT][0], CV_GAUSSIAN, - param1, param2, sigma, sigma ); -} - - -// !!! Copied from cvSmooth, if the code is changed in cvSmooth, -// make sure to update this one too. -#define SMALL_GAUSSIAN_SIZE 9 -static void -calcGaussianKernel( int n, double sigma, vector& kernel ) -{ - static const float small_gaussian_tab[][SMALL_GAUSSIAN_SIZE] = - { - {1.f}, - {0.25f, 0.5f, 0.25f}, - {0.0625f, 0.25f, 0.375f, 0.25f, 0.0625f}, - {0.03125, 0.109375, 0.21875, 0.28125, 0.21875, 0.109375, 0.03125}, - {4.0 / 256, 13.0 / 256, 30.0 / 256, 51.0 / 256, 60.0 / 256, 51.0 / 256, 30.0 / 256, 13.0 / 256, 4.0 / 256} - }; - - kernel.resize(n); - if( n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ) - { - CV_Assert(n%2 == 1); - memcpy(&kernel[0], small_gaussian_tab[n / 2], n*sizeof(kernel[0])); - } - else - { - double sigmaX = sigma > 0 ? sigma : (n/2 - 1)*0.3 + 0.8; - double scale2X = -0.5/(sigmaX*sigmaX); - double sum = 1.; - int i; - sum = kernel[n/2] = 1.f; - - for( i = 1; i <= n/2; i++ ) - { - kernel[n/2+i] = kernel[n/2-i] = (float)exp(scale2X*i*i); - sum += kernel[n/2+i]*2; - } - - sum = 1./sum; - for( i = 0; i <= n/2; i++ ) - kernel[n/2+i] = kernel[n/2-i] = (float)(kernel[n/2+i]*sum); - } -} - - -static Mat calcGaussianKernel2D( Size ksize, double sigma ) -{ - vector kx, ky; - Mat kernel(ksize, CV_32F); - - calcGaussianKernel( kernel.cols, sigma, kx ); - calcGaussianKernel( kernel.rows, sigma, ky ); - - for( int i = 0; i < kernel.rows; i++ ) - for( int j = 0; j < kernel.cols; j++ ) - kernel.at(i, j) = kx[j]*ky[i]; - return kernel; -} - - -void CV_GaussianBlurTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat kernel = calcGaussianKernel2D( aperture_size, sigma ); - cvtest::filter2D( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], test_mat[REF_OUTPUT][0].depth(), - kernel, anchor, 0, border & ~BORDER_ISOLATED ); -} - - -/////////////// median /////////////// - -class CV_MedianBlurTest : public CV_SmoothBaseTest -{ -public: - CV_MedianBlurTest(); - -protected: - void prepare_to_validation( int test_case_idx ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); -}; - - -CV_MedianBlurTest::CV_MedianBlurTest() -{ - smooth_type = "Median"; -} - - -void CV_MedianBlurTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - CV_SmoothBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = CV_8U; - int cn = CV_MAT_CN(types[INPUT][0]); - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - types[INPUT][1] = CV_MAKETYPE(depth,1); - - aperture_size.height = aperture_size.width; - anchor.x = anchor.y = aperture_size.width / 2; - sizes[INPUT][1] = cvSize(aperture_size.width,aperture_size.height); - - sizes[OUTPUT][0] = sizes[INPUT][0]; - sizes[REF_OUTPUT][0] = sizes[INPUT][0]; - - inplace = false; - border = BORDER_REPLICATE | BORDER_ISOLATED; -} - - -double CV_MedianBlurTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return 0; -} - - -void CV_MedianBlurTest::run_func() -{ - cvSmooth( test_array[INPUT][0], test_array[OUTPUT][0], - CV_MEDIAN, aperture_size.width ); -} - - -struct median_pair -{ - int col; - int val; - median_pair() { } - median_pair( int _col, int _val ) : col(_col), val(_val) { } -}; - - -static void test_medianFilter( const Mat& src, Mat& dst, int m ) -{ - int i, j, k, l, m2 = m*m, n; - vector col_buf(m+1); - vector _buf0(m*m+1), _buf1(m*m+1); - median_pair *buf0 = &_buf0[0], *buf1 = &_buf1[0]; - int step = (int)(src.step/src.elemSize()); - - CV_Assert( src.rows == dst.rows + m - 1 && src.cols == dst.cols + m - 1 && - src.type() == dst.type() && src.type() == CV_8UC1 ); - - for( i = 0; i < dst.rows; i++ ) - { - uchar* dst1 = dst.ptr(i); - for( k = 0; k < m; k++ ) - { - const uchar* src1 = src.ptr(i+k); - for( j = 0; j < m-1; j++ ) - *buf0++ = median_pair(j, src1[j]); - } - - n = m2 - m; - buf0 -= n; - for( k = n-1; k > 0; k-- ) - { - int f = 0; - for( j = 0; j < k; j++ ) - { - if( buf0[j].val > buf0[j+1].val ) - { - median_pair t; - CV_SWAP( buf0[j], buf0[j+1], t ); - f = 1; - } - } - if( !f ) - break; - } - - for( j = 0; j < dst.cols; j++ ) - { - int ins_col = j + m - 1; - int del_col = j - 1; - const uchar* src1 = src.ptr(i) + ins_col; - for( k = 0; k < m; k++, src1 += step ) - { - col_buf[k] = src1[0]; - for( l = k-1; l >= 0; l-- ) - { - int t; - if( col_buf[l] < col_buf[l+1] ) - break; - CV_SWAP( col_buf[l], col_buf[l+1], t ); - } - } - - col_buf[m] = INT_MAX; - - for( k = 0, l = 0; k < n; ) - { - if( buf0[k].col == del_col ) - k++; - else if( buf0[k].val < col_buf[l] ) - *buf1++ = buf0[k++]; - else - { - CV_Assert( col_buf[l] < INT_MAX ); - *buf1++ = median_pair(ins_col,col_buf[l++]); - } - } - - for( ; l < m; l++ ) - *buf1++ = median_pair(ins_col,col_buf[l]); - - if( del_col < 0 ) - n += m; - buf1 -= n; - CV_Assert( n == m2 ); - dst1[j] = (uchar)buf1[n/2].val; - median_pair* tbuf; - CV_SWAP( buf0, buf1, tbuf ); - } - } -} - - -void CV_MedianBlurTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - // CV_SmoothBaseTest::prepare_to_validation( test_case_idx ); - const Mat& src0 = test_mat[INPUT][0]; - Mat& dst0 = test_mat[REF_OUTPUT][0]; - int i, cn = src0.channels(); - int m = aperture_size.width; - Mat src(src0.rows + m - 1, src0.cols + m - 1, src0.depth()); - Mat dst; - if( cn == 1 ) - dst = dst0; - else - dst.create(src0.size(), src0.depth()); - - for( i = 0; i < cn; i++ ) - { - Mat ptr = src0; - if( cn > 1 ) - { - cvtest::extract( src0, dst, i ); - ptr = dst; - } - cvtest::copyMakeBorder( ptr, src, m/2, m/2, m/2, m/2, border & ~BORDER_ISOLATED ); - test_medianFilter( src, dst, m ); - if( cn > 1 ) - cvtest::insert( dst, dst0, i ); - } -} - - -/////////////// pyramid tests /////////////// - -class CV_PyramidBaseTest : public CV_FilterBaseTest -{ -public: - CV_PyramidBaseTest( bool downsample ); - -protected: - double get_success_error_level( int test_case_idx, int i, int j ); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - bool downsample; - Mat kernel; -}; - - -CV_PyramidBaseTest::CV_PyramidBaseTest( bool _downsample ) : CV_FilterBaseTest(true) -{ - static float kdata[] = { 1.f, 4.f, 6.f, 4.f, 1.f }; - downsample = _downsample; - Mat kernel1d(1, 5, CV_32F, kdata); - kernel = (kernel1d.t()*kernel1d)*((downsample ? 1 : 4)/256.); -} - - -double CV_PyramidBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth < CV_32F ? 1 : 1e-5; -} - - -void CV_PyramidBaseTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, - vector >& types ) -{ - const int channels[] = {1, 3, 4}; - const int depthes[] = {CV_8U, CV_16S, CV_16U, CV_32F}; - - RNG& rng = ts->get_rng(); - CvSize sz = {0, 0}; - CV_FilterBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - int depth = depthes[cvtest::randInt(rng) % (sizeof(depthes)/sizeof(depthes[0]))]; - int cn = channels[cvtest::randInt(rng) % (sizeof(channels)/sizeof(channels[0]))]; - - aperture_size = cvSize(5,5); - anchor = cvPoint(aperture_size.width/2, aperture_size.height/2); - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth, cn); - - sz.width = MAX( sizes[INPUT][0].width/2, 1 ); - sz.height = MAX( sizes[INPUT][0].height/2, 1 ); - - if( downsample ) - { - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sz; - sz.width *= 2; - sz.height *= 2; - sizes[INPUT][0] = sz; - } - else - { - sizes[INPUT][0] = sz; - sz.width *= 2; - sz.height *= 2; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sz; - } - - sizes[INPUT][1] = aperture_size; - inplace = false; -} - - -/////// pyrdown //////// - -class CV_PyramidDownTest : public CV_PyramidBaseTest -{ -public: - CV_PyramidDownTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_PyramidDownTest::CV_PyramidDownTest() : CV_PyramidBaseTest( true ) -{ -} - - -void CV_PyramidDownTest::run_func() -{ - cvPyrDown( test_array[INPUT][0], test_array[OUTPUT][0], CV_GAUSSIAN_5x5 ); -} - - -void CV_PyramidDownTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0], &dst = test_mat[REF_OUTPUT][0]; - Mat temp; - cvtest::filter2D(src, temp, src.depth(), - kernel, Point(kernel.cols/2, kernel.rows/2), - 0, BORDER_REFLECT_101); - - size_t elem_size = temp.elemSize(); - size_t ncols = dst.cols*elem_size; - - for( int i = 0; i < dst.rows; i++ ) - { - const uchar* src_row = temp.ptr(i*2); - uchar* dst_row = dst.ptr(i); - - for( size_t j = 0; j < ncols; j += elem_size ) - { - for( size_t k = 0; k < elem_size; k++ ) - dst_row[j+k] = src_row[j*2+k]; - } - } -} - - -/////// pyrup //////// - -class CV_PyramidUpTest : public CV_PyramidBaseTest -{ -public: - CV_PyramidUpTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_PyramidUpTest::CV_PyramidUpTest() : CV_PyramidBaseTest( false ) -{ -} - - -void CV_PyramidUpTest::run_func() -{ - cvPyrUp( test_array[INPUT][0], test_array[OUTPUT][0], CV_GAUSSIAN_5x5 ); -} - - -void CV_PyramidUpTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0], &dst = test_mat[REF_OUTPUT][0]; - Mat temp(dst.size(), dst.type()); - - size_t elem_size = src.elemSize(); - size_t ncols = src.cols*elem_size; - - for( int i = 0; i < src.rows; i++ ) - { - const uchar* src_row = src.ptr(i); - uchar* dst_row = temp.ptr(i*2); - - if( i*2 + 1 < temp.rows ) - memset( temp.ptr(i*2+1), 0, temp.cols*elem_size ); - for( size_t j = 0; j < ncols; j += elem_size ) - { - for( size_t k = 0; k < elem_size; k++ ) - { - dst_row[j*2+k] = src_row[j+k]; - dst_row[j*2+k+elem_size] = 0; - } - } - } - - cvtest::filter2D(temp, dst, dst.depth(), - kernel, Point(kernel.cols/2, kernel.rows/2), - 0, BORDER_REFLECT_101); -} - - //////////////////////// feature selection ////////////////////////// class CV_FeatureSelBaseTest : public cvtest::ArrayTest @@ -1369,193 +501,6 @@ void CV_FeatureSelBaseTest::get_test_array_types_and_sizes( int test_case_idx, sizes[OUTPUT][0].width = sizes[REF_OUTPUT][0].width = sizes[INPUT][0].width*width_factor; } - -static void -test_cornerEigenValsVecs( const Mat& src, Mat& eigenv, Mat& ocv_eigenv, - int block_size, int _aperture_size, int mode ) -{ - int i, j; - int aperture_size = _aperture_size < 0 ? 3 : _aperture_size; - Point anchor( aperture_size/2, aperture_size/2 ); - - CV_Assert( src.type() == CV_8UC1 || src.type() == CV_32FC1 ); - CV_Assert( eigenv.type() == CV_32FC1 ); - CV_Assert( src.rows == eigenv.rows && - ((mode > 0 && src.cols == eigenv.cols) || - (mode == 0 && src.cols*6 == eigenv.cols)) ); - - int type = src.type(); - int ftype = CV_32FC1; - double kernel_scale = type != ftype ? 1./255 : 1; - - Mat dx2, dy2, dxdy(src.size(), CV_32F), kernel; - - kernel = cvtest::calcSobelKernel2D( 1, 0, _aperture_size ); - cvtest::filter2D( src, dx2, ftype, kernel*kernel_scale, anchor, 0, BORDER_REPLICATE ); - kernel = cvtest::calcSobelKernel2D( 0, 1, _aperture_size ); - cvtest::filter2D( src, dy2, ftype, kernel*kernel_scale, anchor, 0, BORDER_REPLICATE ); - - double denom = (1 << (aperture_size-1))*block_size; - denom = denom * denom; - if( _aperture_size < 0 ) - denom *= 4; - denom = 1./denom; - - for( i = 0; i < src.rows; i++ ) - { - float* dxdyp = dxdy.ptr(i); - float* dx2p = dx2.ptr(i); - float* dy2p = dy2.ptr(i); - - for( j = 0; j < src.cols; j++ ) - { - double xval = dx2p[j], yval = dy2p[j]; - dxdyp[j] = (float)(xval*yval*denom); - dx2p[j] = (float)(xval*xval*denom); - dy2p[j] = (float)(yval*yval*denom); - } - } - - kernel = Mat::ones(block_size, block_size, CV_32F); - anchor = Point(block_size/2, block_size/2); - - cvtest::filter2D( dx2, dx2, ftype, kernel, anchor, 0, BORDER_REPLICATE ); - cvtest::filter2D( dy2, dy2, ftype, kernel, anchor, 0, BORDER_REPLICATE ); - cvtest::filter2D( dxdy, dxdy, ftype, kernel, anchor, 0, BORDER_REPLICATE ); - - if( mode == 0 ) - { - for( i = 0; i < src.rows; i++ ) - { - float* eigenvp = eigenv.ptr(i); - float* ocv_eigenvp = ocv_eigenv.ptr(i); - const float* dxdyp = dxdy.ptr(i); - const float* dx2p = dx2.ptr(i); - const float* dy2p = dy2.ptr(i); - - for( j = 0; j < src.cols; j++ ) - { - double a = dx2p[j], b = dxdyp[j], c = dy2p[j]; - double d = sqrt((a-c)*(a-c) + 4*b*b); - double l1 = 0.5*(a + c + d); - double l2 = 0.5*(a + c - d); - double x1, y1, x2, y2, s; - - if( fabs(a - l1) + fabs(b) >= 1e-3 ) - x1 = b, y1 = l1 - a; - else - x1 = l1 - c, y1 = b; - s = 1./(sqrt(x1*x1+y1*y1)+DBL_EPSILON); - x1 *= s; y1 *= s; - - if( fabs(a - l2) + fabs(b) >= 1e-3 ) - x2 = b, y2 = l2 - a; - else - x2 = l2 - c, y2 = b; - s = 1./(sqrt(x2*x2+y2*y2)+DBL_EPSILON); - x2 *= s; y2 *= s; - - /* the orientation of eigen vectors might be inversed relative to OpenCV function, - which is normal */ - if( (fabs(x1) >= fabs(y1) && ocv_eigenvp[j*6+2]*x1 < 0) || - (fabs(x1) < fabs(y1) && ocv_eigenvp[j*6+3]*y1 < 0) ) - x1 = -x1, y1 = -y1; - - if( (fabs(x2) >= fabs(y2) && ocv_eigenvp[j*6+4]*x2 < 0) || - (fabs(x2) < fabs(y2) && ocv_eigenvp[j*6+5]*y2 < 0) ) - x2 = -x2, y2 = -y2; - - eigenvp[j*6] = (float)l1; - eigenvp[j*6+1] = (float)l2; - eigenvp[j*6+2] = (float)x1; - eigenvp[j*6+3] = (float)y1; - eigenvp[j*6+4] = (float)x2; - eigenvp[j*6+5] = (float)y2; - } - } - } - else if( mode == 1 ) - { - for( i = 0; i < src.rows; i++ ) - { - float* eigenvp = eigenv.ptr(i); - const float* dxdyp = dxdy.ptr(i); - const float* dx2p = dx2.ptr(i); - const float* dy2p = dy2.ptr(i); - - for( j = 0; j < src.cols; j++ ) - { - double a = dx2p[j], b = dxdyp[j], c = dy2p[j]; - double d = sqrt((a-c)*(a-c) + 4*b*b); - eigenvp[j] = (float)(0.5*(a + c - d)); - } - } - } -} - - -// min eigenval -class CV_MinEigenValTest : public CV_FeatureSelBaseTest -{ -public: - CV_MinEigenValTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_MinEigenValTest::CV_MinEigenValTest() : CV_FeatureSelBaseTest( 1 ) -{ -} - - -void CV_MinEigenValTest::run_func() -{ - cvCornerMinEigenVal( test_array[INPUT][0], test_array[OUTPUT][0], - block_size, aperture_size ); -} - - -void CV_MinEigenValTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - test_cornerEigenValsVecs( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], - test_mat[OUTPUT][0], block_size, aperture_size, 1 ); -} - - -// eigenval's & vec's -class CV_EigenValVecTest : public CV_FeatureSelBaseTest -{ -public: - CV_EigenValVecTest(); - -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_EigenValVecTest::CV_EigenValVecTest() : CV_FeatureSelBaseTest( 6 ) -{ -} - - -void CV_EigenValVecTest::run_func() -{ - cvCornerEigenValsAndVecs( test_array[INPUT][0], test_array[OUTPUT][0], - block_size, aperture_size ); -} - - -void CV_EigenValVecTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - test_cornerEigenValsVecs( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], - test_mat[OUTPUT][0], block_size, aperture_size, 0 ); -} - - // precornerdetect class CV_PreCornerDetectTest : public CV_FeatureSelBaseTest { @@ -1637,233 +582,12 @@ void CV_PreCornerDetectTest::prepare_to_validation( int /*test_case_idx*/ ) } } - -///////// integral ///////// - -class CV_IntegralTest : public cvtest::ArrayTest -{ -public: - CV_IntegralTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int prepare_test_case( int test_case_idx ); -}; - - -CV_IntegralTest::CV_IntegralTest() -{ - test_array[INPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - element_wise_relative_error = true; -} - - -void CV_IntegralTest::get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ) -{ - cvtest::ArrayTest::get_minmax_bounds( i, j, type, low, high ); - int depth = CV_MAT_DEPTH(type); - if( depth == CV_32F ) - { - low = Scalar::all(-10.); - high = Scalar::all(10.); - } -} - - -void CV_IntegralTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - int depth = cvtest::randInt(rng) % 2, sum_depth; - int cn = cvtest::randInt(rng) % 4 + 1; - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - Size sum_size; - - depth = depth == 0 ? CV_8U : CV_32F; - int b = (cvtest::randInt(rng) & 1) != 0; - sum_depth = depth == CV_8U && b ? CV_32S : b ? CV_32F : CV_64F; - - types[INPUT][0] = CV_MAKETYPE(depth,cn); - types[OUTPUT][0] = types[REF_OUTPUT][0] = - types[OUTPUT][2] = types[REF_OUTPUT][2] = CV_MAKETYPE(sum_depth, cn); - types[OUTPUT][1] = types[REF_OUTPUT][1] = CV_MAKETYPE(CV_64F, cn); - - sum_size.width = sizes[INPUT][0].width + 1; - sum_size.height = sizes[INPUT][0].height + 1; - - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = sum_size; - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = - sizes[OUTPUT][2] = sizes[REF_OUTPUT][2] = Size(0,0); - - if( cvtest::randInt(rng) % 3 > 0 ) - { - sizes[OUTPUT][1] = sizes[REF_OUTPUT][1] = sum_size; - if( cvtest::randInt(rng) % 2 > 0 ) - sizes[REF_OUTPUT][2] = sizes[OUTPUT][2] = sum_size; - } -} - - -double CV_IntegralTest::get_success_error_level( int, int i, int j ) -{ - int depth = test_mat[i][j].depth(); - return depth == CV_32S ? 0 : depth == CV_64F ? FLT_EPSILON : 5e-3; -} - - -int CV_IntegralTest::prepare_test_case( int test_case_idx ) -{ - int code = cvtest::ArrayTest::prepare_test_case( test_case_idx ); - return code > 0 && ((test_array[OUTPUT][2] && test_mat[OUTPUT][2].channels() > 1) || - test_mat[OUTPUT][0].depth() < test_mat[INPUT][0].depth()) ? 0 : code; -} - - -void CV_IntegralTest::run_func() -{ - cvIntegral( test_array[INPUT][0], test_array[OUTPUT][0], - test_array[OUTPUT][1], test_array[OUTPUT][2] ); -} - - -static void test_integral( const Mat& img, Mat* sum, Mat* sqsum, Mat* tilted ) -{ - CV_Assert( img.depth() == CV_32F ); - - sum->create(img.rows+1, img.cols+1, CV_64F); - if( sqsum ) - sqsum->create(img.rows+1, img.cols+1, CV_64F); - if( tilted ) - tilted->create(img.rows+1, img.cols+1, CV_64F); - - const float* data = img.ptr(); - double* sdata = sum->ptr(); - double* sqdata = sqsum ? sqsum->ptr() : 0; - double* tdata = tilted ? tilted->ptr() : 0; - int step = (int)(img.step/sizeof(data[0])); - int sstep = (int)(sum->step/sizeof(sdata[0])); - int sqstep = sqsum ? (int)(sqsum->step/sizeof(sqdata[0])) : 0; - int tstep = tilted ? (int)(tilted->step/sizeof(tdata[0])) : 0; - Size size = img.size(); - - memset( sdata, 0, (size.width+1)*sizeof(sdata[0]) ); - if( sqsum ) - memset( sqdata, 0, (size.width+1)*sizeof(sqdata[0]) ); - if( tilted ) - memset( tdata, 0, (size.width+1)*sizeof(tdata[0]) ); - - for( ; size.height--; data += step ) - { - double s = 0, sq = 0; - int x; - sdata += sstep; - sqdata += sqstep; - tdata += tstep; - - for( x = 0; x <= size.width; x++ ) - { - double t = x > 0 ? data[x-1] : 0, ts = t; - s += t; - sq += t*t; - - sdata[x] = s + sdata[x - sstep]; - if( sqdata ) - sqdata[x] = sq + sqdata[x - sqstep]; - - if( !tdata ) - continue; - - if( x == 0 ) - ts += tdata[-tstep+1]; - else - { - ts += tdata[x-tstep-1]; - if( data > img.ptr() ) - { - ts += data[x-step-1]; - if( x < size.width ) - ts += tdata[x-tstep+1] - tdata[x-tstep*2]; - } - } - - tdata[x] = ts; - } - } -} - - -void CV_IntegralTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0]; - int cn = src.channels(); - - Mat* sum0 = &test_mat[REF_OUTPUT][0]; - Mat* sqsum0 = test_array[REF_OUTPUT][1] ? &test_mat[REF_OUTPUT][1] : 0; - Mat* tsum0 = test_array[REF_OUTPUT][2] ? &test_mat[REF_OUTPUT][2] : 0; - - Mat plane, srcf, psum, psqsum, ptsum, psum2, psqsum2, ptsum2; - if( cn == 1 ) - { - plane = src; - psum2 = *sum0; - psqsum2 = sqsum0 ? *sqsum0 : Mat(); - ptsum2 = tsum0 ? *tsum0 : Mat(); - } - - for( int i = 0; i < cn; i++ ) - { - if( cn > 1 ) - cvtest::extract(src, plane, i); - plane.convertTo(srcf, CV_32F); - - test_integral( srcf, &psum, sqsum0 ? &psqsum : 0, tsum0 ? &ptsum : 0 ); - psum.convertTo(psum2, sum0->depth()); - if( sqsum0 ) - psqsum.convertTo(psqsum2, sqsum0->depth()); - if( tsum0 ) - ptsum.convertTo(ptsum2, tsum0->depth()); - - if( cn > 1 ) - { - cvtest::insert(psum2, *sum0, i); - if( sqsum0 ) - cvtest::insert(psqsum2, *sqsum0, i); - if( tsum0 ) - cvtest::insert(ptsum2, *tsum0, i); - } - } -} - - /////////////////////////////////////////////////////////////////////////////////// -TEST(Imgproc_Erode, accuracy) { CV_ErodeTest test; test.safe_run(); } -TEST(Imgproc_Dilate, accuracy) { CV_DilateTest test; test.safe_run(); } -TEST(Imgproc_MorphologyEx, accuracy) { CV_MorphExTest test; test.safe_run(); } -TEST(Imgproc_Filter2D, accuracy) { CV_FilterTest test; test.safe_run(); } TEST(Imgproc_Sobel, accuracy) { CV_SobelTest test; test.safe_run(); } TEST(Imgproc_SpatialGradient, accuracy) { CV_SpatialGradientTest test; test.safe_run(); } TEST(Imgproc_Laplace, accuracy) { CV_LaplaceTest test; test.safe_run(); } -TEST(Imgproc_Blur, accuracy) { CV_BlurTest test; test.safe_run(); } -TEST(Imgproc_GaussianBlur, accuracy) { CV_GaussianBlurTest test; test.safe_run(); } -TEST(Imgproc_MedianBlur, accuracy) { CV_MedianBlurTest test; test.safe_run(); } -TEST(Imgproc_PyramidDown, accuracy) { CV_PyramidDownTest test; test.safe_run(); } -TEST(Imgproc_PyramidUp, accuracy) { CV_PyramidUpTest test; test.safe_run(); } -TEST(Imgproc_MinEigenVal, accuracy) { CV_MinEigenValTest test; test.safe_run(); } -TEST(Imgproc_EigenValsVecs, accuracy) { CV_EigenValVecTest test; test.safe_run(); } TEST(Imgproc_PreCornerDetect, accuracy) { CV_PreCornerDetectTest test; test.safe_run(); } -TEST(Imgproc_Integral, accuracy) { CV_IntegralTest test; test.safe_run(); } ////////////////////////////////////////////////////////////////////////////////// diff --git a/modules/imgproc/test/test_floodfill.cpp b/modules/imgproc/test/test_floodfill.cpp index 934e421fba..0412135f85 100644 --- a/modules/imgproc/test/test_floodfill.cpp +++ b/modules/imgproc/test/test_floodfill.cpp @@ -43,490 +43,6 @@ namespace opencv_test { namespace { -class CV_FloodFillTest : public cvtest::ArrayTest -{ -public: - CV_FloodFillTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - void fill_array( int test_case_idx, int i, int j, Mat& arr ); - - /*int write_default_params(CvFileStorage* fs); - void get_timing_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types - CvSize** whole_sizes, bool *are_images ); - void print_timing_params( int test_case_idx, char* ptr, int params_left );*/ - Point seed_pt; - Scalar new_val; - Scalar l_diff, u_diff; - int connectivity; - bool use_mask, mask_only; - int range_type; - int new_mask_val; - bool test_cpp; -}; - - -CV_FloodFillTest::CV_FloodFillTest() -{ - test_array[INPUT_OUTPUT].push_back(NULL); - test_array[INPUT_OUTPUT].push_back(NULL); - test_array[REF_INPUT_OUTPUT].push_back(NULL); - test_array[REF_INPUT_OUTPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - optional_mask = false; - element_wise_relative_error = true; - - test_cpp = false; -} - - -void CV_FloodFillTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, - vector >& types ) -{ - RNG& rng = ts->get_rng(); - int depth, cn; - int i; - double buff[8]; - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - - depth = cvtest::randInt(rng) % 3; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_32S : CV_32F; - cn = cvtest::randInt(rng) & 1 ? 3 : 1; - - use_mask = (cvtest::randInt(rng) & 1) != 0; - connectivity = (cvtest::randInt(rng) & 1) ? 4 : 8; - mask_only = use_mask && (cvtest::randInt(rng) & 1) != 0; - new_mask_val = cvtest::randInt(rng) & 255; - range_type = cvtest::randInt(rng) % 3; - - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(depth, cn); - types[INPUT_OUTPUT][1] = types[REF_INPUT_OUTPUT][1] = CV_8UC1; - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(9,1); - - if( !use_mask ) - sizes[INPUT_OUTPUT][1] = sizes[REF_INPUT_OUTPUT][1] = cvSize(0,0); - else - { - Size sz = sizes[INPUT_OUTPUT][0]; - sizes[INPUT_OUTPUT][1] = sizes[REF_INPUT_OUTPUT][1] = Size(sz.width+2,sz.height+2); - } - - seed_pt.x = cvtest::randInt(rng) % sizes[INPUT_OUTPUT][0].width; - seed_pt.y = cvtest::randInt(rng) % sizes[INPUT_OUTPUT][0].height; - - if( range_type == 0 ) - l_diff = u_diff = Scalar::all(0.); - else - { - Mat m( 1, 8, CV_16S, buff ); - rng.fill( m, RNG::NORMAL, Scalar::all(0), Scalar::all(32) ); - for( i = 0; i < 4; i++ ) - { - l_diff.val[i] = fabs(m.at(i)/16.); - u_diff.val[i] = fabs(m.at(i+4)/16.); - } - } - - new_val = Scalar::all(0.); - for( i = 0; i < cn; i++ ) - new_val.val[i] = cvtest::randReal(rng)*255; - - test_cpp = (cvtest::randInt(rng) & 256) == 0; -} - - -double CV_FloodFillTest::get_success_error_level( int /*test_case_idx*/, int i, int j ) -{ - return i == OUTPUT ? FLT_EPSILON : j == 0 ? FLT_EPSILON : 0; -} - - -void CV_FloodFillTest::fill_array( int test_case_idx, int i, int j, Mat& arr ) -{ - RNG& rng = ts->get_rng(); - - if( i != INPUT && i != INPUT_OUTPUT ) - { - cvtest::ArrayTest::fill_array( test_case_idx, i, j, arr ); - return; - } - - if( j == 0 ) - { - Mat tmp = arr; - Scalar m = Scalar::all(128); - Scalar s = Scalar::all(10); - - if( arr.depth() == CV_32FC1 ) - tmp.create(arr.size(), CV_MAKETYPE(CV_8U, arr.channels())); - - if( range_type == 0 ) - s = Scalar::all(2); - - rng.fill(tmp, RNG::NORMAL, m, s ); - if( arr.data != tmp.data ) - cvtest::convert(tmp, arr, arr.type()); - } - else - { - Scalar l = Scalar::all(-2); - Scalar u = Scalar::all(2); - cvtest::randUni(rng, arr, l, u ); - rectangle( arr, Point(0,0), Point(arr.cols-1,arr.rows-1), Scalar::all(1), 1, 8, 0 ); - } -} - - -void CV_FloodFillTest::run_func() -{ - int flags = connectivity + (mask_only ? CV_FLOODFILL_MASK_ONLY : 0) + - (range_type == 1 ? CV_FLOODFILL_FIXED_RANGE : 0) + (new_mask_val << 8); - double* odata = test_mat[OUTPUT][0].ptr(); - - if(!test_cpp) - { - CvConnectedComp comp; - cvFloodFill( test_array[INPUT_OUTPUT][0], cvPoint(seed_pt), cvScalar(new_val), cvScalar(l_diff), cvScalar(u_diff), &comp, - flags, test_array[INPUT_OUTPUT][1] ); - odata[0] = comp.area; - odata[1] = comp.rect.x; - odata[2] = comp.rect.y; - odata[3] = comp.rect.width; - odata[4] = comp.rect.height; - odata[5] = comp.value.val[0]; - odata[6] = comp.value.val[1]; - odata[7] = comp.value.val[2]; - odata[8] = comp.value.val[3]; - } - else - { - cv::Mat img = cv::cvarrToMat(test_array[INPUT_OUTPUT][0]), - mask = test_array[INPUT_OUTPUT][1] ? cv::cvarrToMat(test_array[INPUT_OUTPUT][1]) : cv::Mat(); - cv::Rect rect; - int area; - if( mask.empty() ) - area = cv::floodFill( img, seed_pt, new_val, &rect, l_diff, u_diff, flags ); - else - area = cv::floodFill( img, mask, seed_pt, new_val, &rect, l_diff, u_diff, flags ); - odata[0] = area; - odata[1] = rect.x; - odata[2] = rect.y; - odata[3] = rect.width; - odata[4] = rect.height; - odata[5] = odata[6] = odata[7] = odata[8] = 0; - } -} - - -typedef struct ff_offset_pair_t -{ - int mofs, iofs; -} -ff_offset_pair_t; - -static void -cvTsFloodFill( CvMat* _img, CvPoint seed_pt, CvScalar new_val, - CvScalar l_diff, CvScalar u_diff, CvMat* _mask, - double* comp, int connectivity, int range_type, - int new_mask_val, bool mask_only ) -{ - CvMemStorage* st = cvCreateMemStorage(); - ff_offset_pair_t p0, p; - CvSeq* seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(p0), st ); - CvMat* tmp = _img; - CvMat* mask; - CvRect r = cvRect( 0, 0, -1, -1 ); - int area = 0; - int i, j; - ushort* m; - float* img; - int mstep, step; - int cn = CV_MAT_CN(_img->type); - int mdelta[8], idelta[8], ncount; - int cols = _img->cols, rows = _img->rows; - int u0 = 0, u1 = 0, u2 = 0; - double s0 = 0, s1 = 0, s2 = 0; - - if( CV_MAT_DEPTH(_img->type) == CV_8U || CV_MAT_DEPTH(_img->type) == CV_32S ) - { - tmp = cvCreateMat( rows, cols, CV_MAKETYPE(CV_32F,CV_MAT_CN(_img->type)) ); - cvtest::convert(cvarrToMat(_img), cvarrToMat(tmp), -1); - } - - mask = cvCreateMat( rows + 2, cols + 2, CV_16UC1 ); - - if( _mask ) - cvtest::convert(cvarrToMat(_mask), cvarrToMat(mask), -1); - else - { - Mat m_mask = cvarrToMat(mask); - cvtest::set( m_mask, Scalar::all(0), Mat() ); - cvRectangle( mask, cvPoint(0,0), cvPoint(mask->cols-1,mask->rows-1), cvScalar(Scalar::all(1.)), 1, 8, 0 ); - } - - new_mask_val = (new_mask_val != 0 ? new_mask_val : 1) << 8; - - m = (ushort*)(mask->data.ptr + mask->step) + 1; - mstep = mask->step / sizeof(m[0]); - img = tmp->data.fl; - step = tmp->step / sizeof(img[0]); - - p0.mofs = seed_pt.y*mstep + seed_pt.x; - p0.iofs = seed_pt.y*step + seed_pt.x*cn; - - if( m[p0.mofs] ) - goto _exit_; - - cvSeqPush( seq, &p0 ); - m[p0.mofs] = (ushort)new_mask_val; - - if( connectivity == 4 ) - { - ncount = 4; - mdelta[0] = -mstep; idelta[0] = -step; - mdelta[1] = -1; idelta[1] = -cn; - mdelta[2] = 1; idelta[2] = cn; - mdelta[3] = mstep; idelta[3] = step; - } - else - { - ncount = 8; - mdelta[0] = -mstep-1; mdelta[1] = -mstep; mdelta[2] = -mstep+1; - idelta[0] = -step-cn; idelta[1] = -step; idelta[2] = -step+cn; - - mdelta[3] = -1; mdelta[4] = 1; - idelta[3] = -cn; idelta[4] = cn; - - mdelta[5] = mstep-1; mdelta[6] = mstep; mdelta[7] = mstep+1; - idelta[5] = step-cn; idelta[6] = step; idelta[7] = step+cn; - } - - if( cn == 1 ) - { - float a0 = (float)-l_diff.val[0]; - float b0 = (float)u_diff.val[0]; - - s0 = img[p0.iofs]; - - if( range_type < 2 ) - { - a0 += (float)s0; b0 += (float)s0; - } - - while( seq->total ) - { - cvSeqPop( seq, &p0 ); - float a = a0, b = b0; - float* ptr = img + p0.iofs; - ushort* mptr = m + p0.mofs; - - if( range_type == 2 ) - a += ptr[0], b += ptr[0]; - - for( i = 0; i < ncount; i++ ) - { - int md = mdelta[i], id = idelta[i]; - float v; - if( !mptr[md] && a <= (v = ptr[id]) && v <= b ) - { - mptr[md] = (ushort)new_mask_val; - p.mofs = p0.mofs + md; - p.iofs = p0.iofs + id; - cvSeqPush( seq, &p ); - } - } - } - } - else - { - float a0 = (float)-l_diff.val[0]; - float a1 = (float)-l_diff.val[1]; - float a2 = (float)-l_diff.val[2]; - float b0 = (float)u_diff.val[0]; - float b1 = (float)u_diff.val[1]; - float b2 = (float)u_diff.val[2]; - - s0 = img[p0.iofs]; - s1 = img[p0.iofs + 1]; - s2 = img[p0.iofs + 2]; - - if( range_type < 2 ) - { - a0 += (float)s0; b0 += (float)s0; - a1 += (float)s1; b1 += (float)s1; - a2 += (float)s2; b2 += (float)s2; - } - - while( seq->total ) - { - cvSeqPop( seq, &p0 ); - float _a0 = a0, _a1 = a1, _a2 = a2; - float _b0 = b0, _b1 = b1, _b2 = b2; - float* ptr = img + p0.iofs; - ushort* mptr = m + p0.mofs; - - if( range_type == 2 ) - { - _a0 += ptr[0]; _b0 += ptr[0]; - _a1 += ptr[1]; _b1 += ptr[1]; - _a2 += ptr[2]; _b2 += ptr[2]; - } - - for( i = 0; i < ncount; i++ ) - { - int md = mdelta[i], id = idelta[i]; - float v; - if( !mptr[md] && - _a0 <= (v = ptr[id]) && v <= _b0 && - _a1 <= (v = ptr[id+1]) && v <= _b1 && - _a2 <= (v = ptr[id+2]) && v <= _b2 ) - { - mptr[md] = (ushort)new_mask_val; - p.mofs = p0.mofs + md; - p.iofs = p0.iofs + id; - cvSeqPush( seq, &p ); - } - } - } - } - - r.x = r.width = seed_pt.x; - r.y = r.height = seed_pt.y; - - if( !mask_only ) - { - s0 = new_val.val[0]; - s1 = new_val.val[1]; - s2 = new_val.val[2]; - - if( tmp != _img ) - { - u0 = saturate_cast(s0); - u1 = saturate_cast(s1); - u2 = saturate_cast(s2); - - s0 = u0; - s1 = u1; - s2 = u2; - } - } - else - s0 = s1 = s2 = 0; - - new_mask_val >>= 8; - - for( i = 0; i < rows; i++ ) - { - float* ptr = img + i*step; - ushort* mptr = m + i*mstep; - uchar* dmptr = _mask ? _mask->data.ptr + (i+1)*_mask->step + 1 : 0; - double area0 = area; - - for( j = 0; j < cols; j++ ) - { - if( mptr[j] > 255 ) - { - if( dmptr ) - dmptr[j] = (uchar)new_mask_val; - if( !mask_only ) - { - if( cn == 1 ) - ptr[j] = (float)s0; - else - { - ptr[j*3] = (float)s0; - ptr[j*3+1] = (float)s1; - ptr[j*3+2] = (float)s2; - } - } - else - { - if( cn == 1 ) - s0 += ptr[j]; - else - { - s0 += ptr[j*3]; - s1 += ptr[j*3+1]; - s2 += ptr[j*3+2]; - } - } - - area++; - if( r.x > j ) - r.x = j; - if( r.width < j ) - r.width = j; - } - } - - if( area != area0 ) - { - if( r.y > i ) - r.y = i; - if( r.height < i ) - r.height = i; - } - } - -_exit_: - cvReleaseMat( &mask ); - if( tmp != _img ) - { - if( !mask_only ) - cvtest::convert(cvarrToMat(tmp), cvarrToMat(_img), -1); - cvReleaseMat( &tmp ); - } - - comp[0] = area; - comp[1] = r.x; - comp[2] = r.y; - comp[3] = r.width - r.x + 1; - comp[4] = r.height - r.y + 1; -#if 0 - if( mask_only ) - { - double t = area ? 1./area : 0; - s0 *= t; - s1 *= t; - s2 *= t; - } - comp[5] = s0; - comp[6] = s1; - comp[7] = s2; -#else - comp[5] = new_val.val[0]; - comp[6] = new_val.val[1]; - comp[7] = new_val.val[2]; -#endif - comp[8] = 0; - - cvReleaseMemStorage(&st); -} - - -void CV_FloodFillTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - double* comp = test_mat[REF_OUTPUT][0].ptr(); - CvMat _input = cvMat(test_mat[REF_INPUT_OUTPUT][0]); - CvMat _mask = cvMat(test_mat[REF_INPUT_OUTPUT][1]); - cvTsFloodFill( &_input, cvPoint(seed_pt), cvScalar(new_val), cvScalar(l_diff), cvScalar(u_diff), - _mask.data.ptr ? &_mask : 0, - comp, connectivity, range_type, - new_mask_val, mask_only ); - if(test_cpp) - comp[5] = comp[6] = comp[7] = comp[8] = 0; -} - -TEST(Imgproc_FloodFill, accuracy) { CV_FloodFillTest test; test.safe_run(); } - TEST(Imgproc_FloodFill, maskValue) { const int n = 50; diff --git a/modules/imgproc/test/test_histograms.cpp b/modules/imgproc/test/test_histograms.cpp index b57af774f2..0a4b2b66db 100644 --- a/modules/imgproc/test/test_histograms.cpp +++ b/modules/imgproc/test/test_histograms.cpp @@ -43,1890 +43,6 @@ namespace opencv_test { namespace { -class CV_BaseHistTest : public cvtest::BaseTest -{ -public: - enum { MAX_HIST = 12 }; - - CV_BaseHistTest(); - ~CV_BaseHistTest(); - void clear(); - -protected: - int read_params( const cv::FileStorage& fs ); - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - virtual void init_hist( int test_case_idx, int i ); - - virtual void get_hist_params( int test_case_idx ); - virtual float** get_hist_ranges( int test_case_idx ); - - int max_log_size; - int max_cdims; - int cdims; - int dims[CV_MAX_DIM]; - int total_size; - int hist_type; - int hist_count; - int uniform; - int gen_random_hist; - double gen_hist_max_val, gen_hist_sparse_nz_ratio; - - int init_ranges; - int img_type; - int img_max_log_size; - double low, high, range_delta; - Size img_size; - - vector hist; - vector _ranges; - vector ranges; - bool test_cpp; -}; - - -CV_BaseHistTest::CV_BaseHistTest() -{ - test_case_count = 100; - max_log_size = 20; - img_max_log_size = 8; - max_cdims = 6; - hist_count = 1; - init_ranges = 0; - gen_random_hist = 0; - gen_hist_max_val = 100; - - test_cpp = false; -} - - -CV_BaseHistTest::~CV_BaseHistTest() -{ - clear(); -} - - -void CV_BaseHistTest::clear() -{ - cvtest::BaseTest::clear(); - for( size_t i = 0; i < hist.size(); i++ ) - cvReleaseHist( &hist[i] ); -} - - -int CV_BaseHistTest::read_params( const cv::FileStorage& fs ) -{ - int code = cvtest::BaseTest::read_params( fs ); - if( code < 0 ) - return code; - - read( find_param( fs, "struct_count" ), test_case_count, test_case_count ); - read( find_param( fs, "max_log_size" ), max_log_size, max_log_size ); - max_log_size = cvtest::clipInt( max_log_size, 1, 20 ); - read( find_param( fs, "max_log_array_size" ), img_max_log_size, img_max_log_size ); - img_max_log_size = cvtest::clipInt( img_max_log_size, 1, 9 ); - - read( find_param( fs, "max_cdims" ), max_cdims, max_cdims ); - max_cdims = cvtest::clipInt( max_cdims, 1, 6 ); - - return 0; -} - - -void CV_BaseHistTest::get_hist_params( int /*test_case_idx*/ ) -{ - RNG& rng = ts->get_rng(); - int i, max_dim_size, max_ni_dim_size = 31; - double hist_size; - - cdims = cvtest::randInt(rng) % max_cdims + 1; - hist_size = exp(cvtest::randReal(rng)*max_log_size*CV_LOG2); - max_dim_size = cvRound(pow(hist_size,1./cdims)); - total_size = 1; - uniform = cvtest::randInt(rng) % 2; - hist_type = cvtest::randInt(rng) % 2 ? CV_HIST_SPARSE : CV_HIST_ARRAY; - - for( i = 0; i < cdims; i++ ) - { - dims[i] = cvtest::randInt(rng) % (max_dim_size + 2) + 2; - if( !uniform ) - dims[i] = MIN(dims[i], max_ni_dim_size); - total_size *= dims[i]; - } - - img_type = cvtest::randInt(rng) % 2 ? CV_32F : CV_8U; - img_size.width = cvRound( exp(cvtest::randReal(rng) * img_max_log_size * CV_LOG2) ); - img_size.height = cvRound( exp(cvtest::randReal(rng) * img_max_log_size * CV_LOG2) ); - - if( img_type < CV_32F ) - { - low = cvtest::getMinVal(img_type); - high = cvtest::getMaxVal(img_type); - } - else - { - high = 1000; - low = -high; - } - - range_delta = (cvtest::randInt(rng) % 2)*(high-low)*0.05; -} - - -float** CV_BaseHistTest::get_hist_ranges( int /*test_case_idx*/ ) -{ - double _low = low + range_delta, _high = high - range_delta; - - if( !init_ranges ) - return 0; - - ranges.resize(cdims); - - if( uniform ) - { - _ranges.resize(cdims*2); - for( int i = 0; i < cdims; i++ ) - { - _ranges[i*2] = (float)_low; - _ranges[i*2+1] = (float)_high; - ranges[i] = &_ranges[i*2]; - } - } - else - { - int i, dims_sum = 0, ofs = 0; - for( i = 0; i < cdims; i++ ) - dims_sum += dims[i] + 1; - _ranges.resize(dims_sum); - - for( i = 0; i < cdims; i++ ) - { - int j, n = dims[i]; - // generate logarithmic scale - double delta, q, val; - for( j = 0; j < 10; j++ ) - { - q = 1. + (j+1)*0.1; - if( (pow(q,(double)n)-1)/(q-1.) >= _high-_low ) - break; - } - - if( j == 0 ) - { - delta = (_high-_low)/n; - q = 1.; - } - else - { - q = 1 + j*0.1; - delta = cvFloor((_high-_low)*(q-1)/(pow(q,(double)n) - 1)); - delta = MAX(delta, 1.); - } - val = _low; - - for( j = 0; j <= n; j++ ) - { - _ranges[j+ofs] = (float)MIN(val,_high); - val += delta; - delta *= q; - } - ranges[i] = &_ranges[ofs]; - ofs += n + 1; - } - } - - return &ranges[0]; -} - - -void CV_BaseHistTest::init_hist( int /*test_case_idx*/, int hist_i ) -{ - if( gen_random_hist ) - { - RNG& rng = ts->get_rng(); - - if( hist_type == CV_HIST_ARRAY ) - { - Mat h = cvarrToMat(hist[hist_i]->bins); - cvtest::randUni(rng, h, Scalar::all(0), Scalar::all(gen_hist_max_val) ); - } - else - { - CvArr* arr = hist[hist_i]->bins; - int i, j, totalSize = 1, nz_count; - int idx[CV_MAX_DIM]; - for( i = 0; i < cdims; i++ ) - totalSize *= dims[i]; - - nz_count = cvtest::randInt(rng) % MAX( totalSize/4, 100 ); - nz_count = MIN( nz_count, totalSize ); - - // a zero number of non-zero elements should be allowed - for( i = 0; i < nz_count; i++ ) - { - for( j = 0; j < cdims; j++ ) - idx[j] = cvtest::randInt(rng) % dims[j]; - cvSetRealND(arr, idx, cvtest::randReal(rng)*gen_hist_max_val); - } - } - } -} - - -int CV_BaseHistTest::prepare_test_case( int test_case_idx ) -{ - int i; - float** r; - - clear(); - - cvtest::BaseTest::prepare_test_case( test_case_idx ); - get_hist_params( test_case_idx ); - r = get_hist_ranges( test_case_idx ); - hist.resize(hist_count); - - for( i = 0; i < hist_count; i++ ) - { - hist[i] = cvCreateHist( cdims, dims, hist_type, r, uniform ); - init_hist( test_case_idx, i ); - } - test_cpp = (cvtest::randInt(ts->get_rng()) % 2) != 0; - - return 1; -} - - -void CV_BaseHistTest::run_func(void) -{ -} - - -int CV_BaseHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - return 0; -} - - -////////////// testing operation for reading/writing individual histogram bins ////////////// - -class CV_QueryHistTest : public CV_BaseHistTest -{ -public: - CV_QueryHistTest(); - ~CV_QueryHistTest(); - void clear(); - -protected: - void run_func(void); - int prepare_test_case( int test_case_idx ); - int validate_test_results( int test_case_idx ); - void init_hist( int test_case_idx, int i ); - - Mat indices; - Mat values; - Mat values0; -}; - - -CV_QueryHistTest::CV_QueryHistTest() -{ - hist_count = 1; -} - - -CV_QueryHistTest::~CV_QueryHistTest() -{ - clear(); -} - - -void CV_QueryHistTest::clear() -{ - CV_BaseHistTest::clear(); -} - - -void CV_QueryHistTest::init_hist( int /*test_case_idx*/, int i ) -{ - if( hist_type == CV_HIST_ARRAY ) - cvZero( hist[i]->bins ); -} - - -int CV_QueryHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - int i, j, iters; - float default_value = 0.f; - RNG& rng = ts->get_rng(); - int* idx; - - iters = (cvtest::randInt(rng) % MAX(total_size/10,100)) + 1; - iters = MIN( iters, total_size*9/10 + 1 ); - - indices = Mat(1, iters*cdims, CV_32S); - values = Mat(1, iters, CV_32F ); - values0 = Mat( 1, iters, CV_32F ); - idx = indices.ptr(); - - //printf( "total_size = %d, cdims = %d, iters = %d\n", total_size, cdims, iters ); - - Mat bit_mask(1, (total_size + 7)/8, CV_8U, Scalar(0)); - - #define GET_BIT(n) (bit_mask.data[(n)/8] & (1 << ((n)&7))) - #define SET_BIT(n) bit_mask.data[(n)/8] |= (1 << ((n)&7)) - - // set random histogram bins' values to the linear indices of the bins - for( i = 0; i < iters; i++ ) - { - int lin_idx = 0; - for( j = 0; j < cdims; j++ ) - { - int t = cvtest::randInt(rng) % dims[j]; - idx[i*cdims + j] = t; - lin_idx = lin_idx*dims[j] + t; - } - - if( cvtest::randInt(rng) % 8 || GET_BIT(lin_idx) ) - { - values0.at(i) = (float)(lin_idx+1); - SET_BIT(lin_idx); - } - else - // some histogram bins will not be initialized intentionally, - // they should be equal to the default value - values0.at(i) = default_value; - } - - // do the second pass to make values0 consistent with bit_mask - for( i = 0; i < iters; i++ ) - { - int lin_idx = 0; - for( j = 0; j < cdims; j++ ) - lin_idx = lin_idx*dims[j] + idx[i*cdims + j]; - - if( GET_BIT(lin_idx) ) - values0.at(i) = (float)(lin_idx+1); - } - } - - return code; -} - - -void CV_QueryHistTest::run_func(void) -{ - int i, iters = values.cols; - CvArr* h = hist[0]->bins; - const int* idx = indices.ptr(); - float* val = values.ptr(); - float default_value = 0.f; - - // stage 1: write bins - if( cdims == 1 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0.at(i); - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal1D( h, idx[i], v0 ); - else - *(float*)cvPtr1D( h, idx[i] ) = v0; - } - else - cvSetRealND( h, idx+i, v0 ); - } - else if( cdims == 2 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0.at(i); - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal2D( h, idx[i*2], idx[i*2+1], v0 ); - else - *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ) = v0; - } - else - cvSetRealND( h, idx+i*2, v0 ); - } - else if( cdims == 3 ) - for( i = 0; i < iters; i++ ) - { - float v0 = values0.at(i); - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - { - if( !(i % 4) ) - cvSetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2], v0 ); - else - *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ) = v0; - } - else - cvSetRealND( h, idx+i*3, v0 ); - } - else - for( i = 0; i < iters; i++ ) - { - float v0 = values0.at(i); - if( fabs(v0 - default_value) < FLT_EPSILON ) - continue; - if( !(i % 2) ) - cvSetRealND( h, idx+i*cdims, v0 ); - else - *(float*)cvPtrND( h, idx+i*cdims ) = v0; - } - - // stage 2: read bins - if( cdims == 1 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr1D( h, idx[i] ); - else - val[i] = (float)cvGetReal1D( h, idx[i] ); - } - else if( cdims == 2 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ); - else - val[i] = (float)cvGetReal2D( h, idx[i*2], idx[i*2+1] ); - } - else if( cdims == 3 ) - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ); - else - val[i] = (float)cvGetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ); - } - else - for( i = 0; i < iters; i++ ) - { - if( !(i % 2) ) - val[i] = *(float*)cvPtrND( h, idx+i*cdims ); - else - val[i] = (float)cvGetRealND( h, idx+i*cdims ); - } -} - - -int CV_QueryHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - int i, j, iters = values.cols; - - for( i = 0; i < iters; i++ ) - { - float v = values.at(i), v0 = values0.at(i); - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( cvtest::TS::LOG, "The bin #%d has invalid value\n", i ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - else if( fabs(v - v0) > FLT_EPSILON ) - { - ts->printf( cvtest::TS::LOG, "The bin #%d = %g, while it should be %g\n", i, v, v0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - { - ts->printf( cvtest::TS::LOG, "The bin index = (" ); - for( j = 0; j < cdims; j++ ) - ts->printf( cvtest::TS::LOG, "%d%s", indices.at(i*cdims + j), - j < cdims-1 ? ", " : ")\n" ); - break; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -////////////// cvGetMinMaxHistValue ////////////// - -class CV_MinMaxHistTest : public CV_BaseHistTest -{ -public: - CV_MinMaxHistTest(); - -protected: - void run_func(void); - void init_hist(int, int); - int validate_test_results( int test_case_idx ); - int min_idx[CV_MAX_DIM], max_idx[CV_MAX_DIM]; - float min_val, max_val; - int min_idx0[CV_MAX_DIM], max_idx0[CV_MAX_DIM]; - float min_val0, max_val0; -}; - - - -CV_MinMaxHistTest::CV_MinMaxHistTest() -{ - hist_count = 1; - gen_random_hist = 1; -} - - -void CV_MinMaxHistTest::init_hist(int test_case_idx, int hist_i) -{ - int i, eq = 1; - RNG& rng = ts->get_rng(); - CV_BaseHistTest::init_hist( test_case_idx, hist_i ); - - for(;;) - { - for( i = 0; i < cdims; i++ ) - { - min_idx0[i] = cvtest::randInt(rng) % dims[i]; - max_idx0[i] = cvtest::randInt(rng) % dims[i]; - eq &= min_idx0[i] == max_idx0[i]; - } - if( !eq || total_size == 1 ) - break; - } - - min_val0 = (float)(-cvtest::randReal(rng)*10 - FLT_EPSILON); - max_val0 = (float)(cvtest::randReal(rng)*10 + FLT_EPSILON + gen_hist_max_val); - - if( total_size == 1 ) - min_val0 = max_val0; - - cvSetRealND( hist[0]->bins, min_idx0, min_val0 ); - cvSetRealND( hist[0]->bins, max_idx0, max_val0 ); -} - - -void CV_MinMaxHistTest::run_func(void) -{ - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h; - ((CvSparseMat*)hist[0]->bins)->copyToSparseMat(h); - double _min_val = 0, _max_val = 0; - cv::minMaxLoc(h, &_min_val, &_max_val, min_idx, max_idx ); - min_val = (float)_min_val; - max_val = (float)_max_val; - } - else - cvGetMinMaxHistValue( hist[0], &min_val, &max_val, min_idx, max_idx ); -} - - -int CV_MinMaxHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - - if( cvIsNaN(min_val) || cvIsInf(min_val) || - cvIsNaN(max_val) || cvIsInf(max_val) ) - { - ts->printf( cvtest::TS::LOG, - "The extrema histogram bin values are invalid (min = %g, max = %g)\n", min_val, max_val ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - else if( fabs(min_val - min_val0) > FLT_EPSILON || - fabs(max_val - max_val0) > FLT_EPSILON ) - { - ts->printf( cvtest::TS::LOG, - "The extrema histogram bin values are incorrect: (min = %g, should be = %g), (max = %g, should be = %g)\n", - min_val, min_val0, max_val, max_val0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - } - else - { - int i; - for( i = 0; i < cdims; i++ ) - { - if( min_idx[i] != min_idx0[i] || max_idx[i] != max_idx0[i] ) - { - ts->printf( cvtest::TS::LOG, - "The %d-th coordinates of extrema histogram bin values are incorrect: " - "(min = %d, should be = %d), (max = %d, should be = %d)\n", - i, min_idx[i], min_idx0[i], max_idx[i], max_idx0[i] ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - } - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -////////////// cvNormalizeHist ////////////// - -class CV_NormHistTest : public CV_BaseHistTest -{ -public: - CV_NormHistTest(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - double factor; -}; - - - -CV_NormHistTest::CV_NormHistTest() -{ - hist_count = 1; - gen_random_hist = 1; - factor = 0; -} - - -int CV_NormHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - RNG& rng = ts->get_rng(); - factor = cvtest::randReal(rng)*10 + 0.1; - if( hist_type == CV_HIST_SPARSE && - ((CvSparseMat*)hist[0]->bins)->heap->active_count == 0 ) - factor = 0; - } - - return code; -} - - -void CV_NormHistTest::run_func(void) -{ - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h; - ((CvSparseMat*)hist[0]->bins)->copyToSparseMat(h); - cv::normalize(h, h, factor, CV_L1); - cvReleaseSparseMat((CvSparseMat**)&hist[0]->bins); - hist[0]->bins = cvCreateSparseMat(h); - } - else - cvNormalizeHist( hist[0], factor ); -} - - -int CV_NormHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - double sum = 0; - - if( hist_type == CV_HIST_ARRAY ) - { - int i; - const float* ptr = (float*)cvPtr1D( hist[0]->bins, 0 ); - - for( i = 0; i < total_size; i++ ) - sum += ptr[i]; - } - else - { - CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins; - CvSparseMatIterator iterator; - CvSparseNode *node; - - for( node = cvInitSparseMatIterator( sparse, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator )) - { - sum += *(float*)CV_NODE_VAL(sparse,node); - } - } - - if( cvIsNaN(sum) || cvIsInf(sum) ) - { - ts->printf( cvtest::TS::LOG, - "The normalized histogram has invalid sum =%g\n", sum ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - else if( fabs(sum - factor) > FLT_EPSILON*10*fabs(factor) ) - { - ts->printf( cvtest::TS::LOG, - "The normalized histogram has incorrect sum =%g, while it should be =%g\n", sum, factor ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -////////////// cvThreshHist ////////////// - -class CV_ThreshHistTest : public CV_BaseHistTest -{ -public: - CV_ThreshHistTest(); - ~CV_ThreshHistTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - Mat indices; - Mat values; - int orig_nz_count; - - double threshold; -}; - - - -CV_ThreshHistTest::CV_ThreshHistTest() : threshold(0) -{ - hist_count = 1; - gen_random_hist = 1; -} - - -CV_ThreshHistTest::~CV_ThreshHistTest() -{ - clear(); -} - - -void CV_ThreshHistTest::clear() -{ - CV_BaseHistTest::clear(); -} - - -int CV_ThreshHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - RNG& rng = ts->get_rng(); - threshold = cvtest::randReal(rng)*gen_hist_max_val; - - if( hist_type == CV_HIST_ARRAY ) - { - orig_nz_count = total_size; - - values = Mat( 1, total_size, CV_32F ); - indices = Mat(); - memcpy( values.ptr(), cvPtr1D( hist[0]->bins, 0 ), total_size*sizeof(float) ); - } - else - { - CvSparseMat* sparse = (CvSparseMat*)hist[0]->bins; - CvSparseMatIterator iterator; - CvSparseNode* node; - int i, k; - - orig_nz_count = sparse->heap->active_count; - - values = Mat( 1, orig_nz_count+1, CV_32F ); - indices = Mat( 1, (orig_nz_count+1)*cdims, CV_32S ); - - for( node = cvInitSparseMatIterator( sparse, &iterator ), i = 0; - node != 0; node = cvGetNextSparseNode( &iterator ), i++ ) - { - const int* idx = CV_NODE_IDX(sparse,node); - - OPENCV_ASSERT( i < orig_nz_count, "CV_ThreshHistTest::prepare_test_case", "Buffer overflow" ); - - values.at(i) = *(float*)CV_NODE_VAL(sparse,node); - for( k = 0; k < cdims; k++ ) - indices.at(i*cdims + k) = idx[k]; - } - - OPENCV_ASSERT( i == orig_nz_count, "Unmatched buffer size", - "CV_ThreshHistTest::prepare_test_case" ); - } - } - - return code; -} - - -void CV_ThreshHistTest::run_func(void) -{ - cvThreshHist( hist[0], threshold ); -} - - -int CV_ThreshHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - int i; - float* ptr0 = values.ptr(); - float* ptr = 0; - CvSparseMat* sparse = 0; - - if( hist_type == CV_HIST_ARRAY ) - ptr = (float*)cvPtr1D( hist[0]->bins, 0 ); - else - sparse = (CvSparseMat*)hist[0]->bins; - - if( code > 0 ) - { - for( i = 0; i < orig_nz_count; i++ ) - { - float v0 = ptr0[i], v; - - if( hist_type == CV_HIST_ARRAY ) - v = ptr[i]; - else - { - v = (float)cvGetRealND( sparse, indices.ptr() + i*cdims ); - cvClearND( sparse, indices.ptr() + i*cdims ); - } - - if( v0 <= threshold ) v0 = 0.f; - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( cvtest::TS::LOG, "The %d-th bin is invalid (=%g)\n", i, v ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > FLT_EPSILON*10*fabs(v0) ) - { - ts->printf( cvtest::TS::LOG, "The %d-th bin is incorrect (=%g, should be =%g)\n", i, v, v0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - break; - } - } - } - - if( code > 0 && hist_type == CV_HIST_SPARSE ) - { - if( sparse->heap->active_count > 0 ) - { - ts->printf( cvtest::TS::LOG, - "There some extra histogram bins in the sparse histogram after the thresholding\n" ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -////////////// cvCompareHist ////////////// - -class CV_CompareHistTest : public CV_BaseHistTest -{ -public: - enum { MAX_METHOD = 6 }; - - CV_CompareHistTest(); -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - double result[MAX_METHOD+1]; -}; - - - -CV_CompareHistTest::CV_CompareHistTest() -{ - hist_count = 2; - gen_random_hist = 1; -} - - -int CV_CompareHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - return code; -} - - -void CV_CompareHistTest::run_func(void) -{ - int k; - if( hist_type != CV_HIST_ARRAY && test_cpp ) - { - cv::SparseMat h0, h1; - ((CvSparseMat*)hist[0]->bins)->copyToSparseMat(h0); - ((CvSparseMat*)hist[1]->bins)->copyToSparseMat(h1); - for( k = 0; k < MAX_METHOD; k++ ) - result[k] = cv::compareHist(h0, h1, k); - } - else - for( k = 0; k < MAX_METHOD; k++ ) - result[k] = cvCompareHist( hist[0], hist[1], k ); -} - - -int CV_CompareHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - int i; - double result0[MAX_METHOD+1]; - double s0 = 0, s1 = 0, sq0 = 0, sq1 = 0, t; - - for( i = 0; i < MAX_METHOD; i++ ) - result0[i] = 0; - - if( hist_type == CV_HIST_ARRAY ) - { - float* ptr0 = (float*)cvPtr1D( hist[0]->bins, 0 ); - float* ptr1 = (float*)cvPtr1D( hist[1]->bins, 0 ); - - for( i = 0; i < total_size; i++ ) - { - double v0 = ptr0[i], v1 = ptr1[i]; - result0[CV_COMP_CORREL] += v0*v1; - result0[CV_COMP_INTERSECT] += MIN(v0,v1); - if( fabs(v0) > DBL_EPSILON ) - result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/v0; - if( fabs(v0 + v1) > DBL_EPSILON ) - result0[CV_COMP_CHISQR_ALT] += (v0 - v1)*(v0 - v1)/(v0 + v1); - s0 += v0; - s1 += v1; - sq0 += v0*v0; - sq1 += v1*v1; - result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1); - { - if( fabs(v0) <= DBL_EPSILON ) - continue; - if( fabs(v1) <= DBL_EPSILON ) - v1 = 1e-10; - result0[CV_COMP_KL_DIV] += v0 * std::log( v0 / v1 ); - } - } - } - else - { - CvSparseMat* sparse0 = (CvSparseMat*)hist[0]->bins; - CvSparseMat* sparse1 = (CvSparseMat*)hist[1]->bins; - CvSparseMatIterator iterator; - CvSparseNode* node; - - for( node = cvInitSparseMatIterator( sparse0, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator ) ) - { - const int* idx = CV_NODE_IDX(sparse0, node); - double v0 = *(float*)CV_NODE_VAL(sparse0, node); - double v1 = (float)cvGetRealND(sparse1, idx); - - result0[CV_COMP_CORREL] += v0*v1; - result0[CV_COMP_INTERSECT] += MIN(v0,v1); - if( fabs(v0) > DBL_EPSILON ) - result0[CV_COMP_CHISQR] += (v0 - v1)*(v0 - v1)/v0; - if( fabs(v0 + v1) > DBL_EPSILON ) - result0[CV_COMP_CHISQR_ALT] += (v0 - v1)*(v0 - v1)/(v0 + v1); - s0 += v0; - sq0 += v0*v0; - result0[CV_COMP_BHATTACHARYYA] += sqrt(v0*v1); - { - if (v0 <= DBL_EPSILON) - continue; - if (!v1) - v1 = 1e-10; - result0[CV_COMP_KL_DIV] += v0 * std::log( v0 / v1 ); - } - } - - for( node = cvInitSparseMatIterator( sparse1, &iterator ); - node != 0; node = cvGetNextSparseNode( &iterator ) ) - { - double v1 = *(float*)CV_NODE_VAL(sparse1, node); - s1 += v1; - sq1 += v1*v1; - } - } - - result0[CV_COMP_CHISQR_ALT] *= 2; - - t = (sq0 - s0*s0/total_size)*(sq1 - s1*s1/total_size); - result0[CV_COMP_CORREL] = fabs(t) > DBL_EPSILON ? - (result0[CV_COMP_CORREL] - s0*s1/total_size)/sqrt(t) : 1; - - s1 *= s0; - s0 = result0[CV_COMP_BHATTACHARYYA]; - s0 = 1. - s0*(s1 > FLT_EPSILON ? 1./sqrt(s1) : 1.); - result0[CV_COMP_BHATTACHARYYA] = sqrt(MAX(s0,0.)); - - for( i = 0; i < MAX_METHOD; i++ ) - { - double v = result[i], v0 = result0[i]; - const char* method_name = - i == CV_COMP_CHISQR ? "Chi-Square" : - i == CV_COMP_CHISQR_ALT ? "Alternative Chi-Square" : - i == CV_COMP_CORREL ? "Correlation" : - i == CV_COMP_INTERSECT ? "Intersection" : - i == CV_COMP_BHATTACHARYYA ? "Bhattacharyya" : - i == CV_COMP_KL_DIV ? "Kullback-Leibler" : "Unknown"; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( cvtest::TS::LOG, "The comparison result using the method #%d (%s) is invalid (=%g)\n", - i, method_name, v ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > FLT_EPSILON*14*MAX(fabs(v0),0.1) ) - { - ts->printf( cvtest::TS::LOG, "The comparison result using the method #%d (%s)\n\tis inaccurate (=%g, should be =%g)\n", - i, method_name, v, v0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - break; - } - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -////////////// cvCalcHist ////////////// - -class CV_CalcHistTest : public CV_BaseHistTest -{ -public: - CV_CalcHistTest(); - ~CV_CalcHistTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - vector images; - vector channels; -}; - - - -CV_CalcHistTest::CV_CalcHistTest() : images(CV_MAX_DIM+1), channels(CV_MAX_DIM+1) -{ - hist_count = 2; - gen_random_hist = 0; - init_ranges = 1; -} - - -CV_CalcHistTest::~CV_CalcHistTest() -{ - clear(); -} - - -void CV_CalcHistTest::clear() -{ - CV_BaseHistTest::clear(); -} - - -int CV_CalcHistTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - RNG& rng = ts->get_rng(); - int i; - - for( i = 0; i <= CV_MAX_DIM; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvtest::randInt(rng) % 3 + 1; - images[i] = Mat(img_size, CV_MAKETYPE(img_type, nch)); - channels[i] = cvtest::randInt(rng) % nch; - cvtest::randUni( rng, images[i], Scalar::all(low), Scalar::all(high) ); - } - else if( i == CV_MAX_DIM ) - { - if( cvtest::randInt(rng) % 2 ) - { - // create mask - images[i] = Mat(img_size, CV_8U); - - // make ~25% pixels in the mask non-zero - cvtest::randUni( rng, images[i], Scalar::all(-2), Scalar::all(2) ); - } - else - images[i] = Mat(); - } - } - } - - return code; -} - - -void CV_CalcHistTest::run_func(void) -{ - int size[CV_MAX_DIM]; - int hdims = cvGetDims( hist[0]->bins, size); - bool huniform = CV_IS_UNIFORM_HIST(hist[0]); - - const float* uranges[CV_MAX_DIM] = {0}; - const float** hranges = 0; - - if( hist[0]->type & CV_HIST_RANGES_FLAG ) - { - hranges = (const float**)hist[0]->thresh2; - if( huniform ) - { - for(int i = 0; i < hdims; i++ ) - uranges[i] = &hist[0]->thresh[i][0]; - hranges = uranges; - } - } - - std::vector imagesv(cdims); - copy(images.begin(), images.begin() + cdims, imagesv.begin()); - - Mat mask = images[CV_MAX_DIM]; - if( !CV_IS_SPARSE_HIST(hist[0]) ) - { - cv::Mat H = cv::cvarrToMat(hist[0]->bins); - if(huniform) - { - vector emptyChannels; - vector hSize(hdims); - for(int i = 0; i < hdims; i++) - hSize[i] = size[i]; - vector vranges; - if(hranges) - { - vranges.resize(hdims*2); - for(int i = 0; i < hdims; i++ ) - { - vranges[i*2 ] = hist[0]->thresh[i][0]; - vranges[i*2+1] = hist[0]->thresh[i][1]; - } - } - cv::calcHist(imagesv, emptyChannels, mask, H, hSize, vranges); - } - else - { - cv::calcHist( &imagesv[0], (int)imagesv.size(), 0, mask, - H, cvGetDims(hist[0]->bins), H.size, hranges, huniform ); - } - } - else - { - CvSparseMat* sparsemat = (CvSparseMat*)hist[0]->bins; - - cvZero( hist[0]->bins ); - - cv::SparseMat sH; - sparsemat->copyToSparseMat(sH); - - cv::calcHist( &imagesv[0], (int)imagesv.size(), 0, mask, sH, sH.dims(), - sH.dims() > 0 ? sH.hdr->size : 0, hranges, huniform, false); - - cv::SparseMatConstIterator it = sH.begin(); - int nz = (int)sH.nzcount(); - for(int i = 0; i < nz; i++, ++it ) - { - CV_Assert(it.ptr != NULL); - *(float*)cvPtrND(sparsemat, it.node()->idx, 0, -2) = *(const float*)it.ptr; - } - } -} - - -static void -cvTsCalcHist( const vector& images, CvHistogram* hist, Mat mask, const vector& channels ) -{ - int x, y, k; - union - { - const float* fl; - const uchar* ptr; - } - plane[CV_MAX_DIM]; - int nch[CV_MAX_DIM]; - int dims[CV_MAX_DIM]; - int uniform = CV_IS_UNIFORM_HIST(hist); - - int cdims = cvGetDims( hist->bins, dims ); - cvZero( hist->bins ); - - Size img_size = images[0].size(); - int img_depth = images[0].depth(); - for( k = 0; k < cdims; k++ ) - { - nch[k] = images[k].channels(); - } - - for( y = 0; y < img_size.height; y++ ) - { - const uchar* mptr = mask.empty() ? 0 : mask.ptr(y); - - if( img_depth == CV_8U ) - for( k = 0; k < cdims; k++ ) - plane[k].ptr = images[k].ptr(y) + channels[k]; - else - for( k = 0; k < cdims; k++ ) - plane[k].fl = images[k].ptr(y) + channels[k]; - - for( x = 0; x < img_size.width; x++ ) - { - float val[CV_MAX_DIM]; - int idx[CV_MAX_DIM]; - - if( mptr && !mptr[x] ) - continue; - if( img_depth == CV_8U ) - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].ptr[x*nch[k]]; - else - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].fl[x*nch[k]]; - - idx[cdims-1] = -1; - - if( uniform ) - { - for( k = 0; k < cdims; k++ ) - { - double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1]; - if (v < lo || v >= hi) - break; - double idx_ = (v - lo)*dims[k]/(hi - lo); - idx[k] = cvFloor(idx_); - if (idx[k] < 0) - { - idx[k] = 0; - } - if (idx[k] >= dims[k]) - { - idx[k] = dims[k] - 1; - } - } - } - else - { - for( k = 0; k < cdims; k++ ) - { - float v = val[k]; - float* t = hist->thresh2[k]; - int j, n = dims[k]; - - for( j = 0; j <= n; j++ ) - if( v < t[j] ) - break; - if( j <= 0 || j > n ) - break; - idx[k] = j-1; - } - } - - if( k < cdims ) - continue; - - (*(float*)cvPtrND( hist->bins, idx ))++; - } - } -} - - -int CV_CalcHistTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - double diff; - cvTsCalcHist( images, hist[1], images[CV_MAX_DIM], channels ); - diff = cvCompareHist( hist[0], hist[1], CV_COMP_CHISQR ); - if( diff > DBL_EPSILON ) - { - ts->printf( cvtest::TS::LOG, "The histogram does not match to the reference one\n" ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - - -CV_CalcHistTest hist_calc_test; - - - -////////////// cvCalcBackProject ////////////// - -class CV_CalcBackProjectTest : public CV_BaseHistTest -{ -public: - CV_CalcBackProjectTest(); - ~CV_CalcBackProjectTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - vector images; - vector channels; -}; - - - -CV_CalcBackProjectTest::CV_CalcBackProjectTest() : images(CV_MAX_DIM+3), channels(CV_MAX_DIM+3) -{ - hist_count = 1; - gen_random_hist = 0; - init_ranges = 1; -} - - -CV_CalcBackProjectTest::~CV_CalcBackProjectTest() -{ - clear(); -} - - -void CV_CalcBackProjectTest::clear() -{ - CV_BaseHistTest::clear(); -} - - -int CV_CalcBackProjectTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - RNG& rng = ts->get_rng(); - int i, j, n, img_len = img_size.area(); - - for( i = 0; i < CV_MAX_DIM + 3; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvtest::randInt(rng) % 3 + 1; - images[i] = Mat(img_size, CV_MAKETYPE(img_type, nch)); - channels[i] = cvtest::randInt(rng) % nch; - - cvtest::randUni( rng, images[i], Scalar::all(low), Scalar::all(high) ); - } - else if( i == CV_MAX_DIM ) - { - if(cvtest::randInt(rng) % 2 ) - { - // create mask - images[i] = Mat(img_size, CV_8U); - // make ~25% pixels in the mask non-zero - cvtest::randUni( rng, images[i], Scalar::all(-2), Scalar::all(2) ); - } - else - { - images[i] = Mat(); - } - } - else if( i > CV_MAX_DIM ) - { - images[i] = Mat(img_size, images[0].type()); - } - } - - cvTsCalcHist( images, hist[0], images[CV_MAX_DIM], channels ); - - // now modify the images a bit to add some zeros go to the backprojection - n = cvtest::randInt(rng) % (img_len/20+1); - for( i = 0; i < cdims; i++ ) - { - uchar* data = images[i].data; - for( j = 0; j < n; j++ ) - { - int idx = cvtest::randInt(rng) % img_len; - double val = cvtest::randReal(rng)*(high - low) + low; - - if( img_type == CV_8U ) - ((uchar*)data)[idx] = (uchar)cvRound(val); - else - ((float*)data)[idx] = (float)val; - } - } - } - - return code; -} - - -void CV_CalcBackProjectTest::run_func(void) -{ - int size[CV_MAX_DIM]; - int hdims = cvGetDims( hist[0]->bins, size ); - - bool huniform = CV_IS_UNIFORM_HIST(hist[0]); - const float* uranges[CV_MAX_DIM] = {0}; - const float** hranges = 0; - - if( hist[0]->type & CV_HIST_RANGES_FLAG ) - { - hranges = (const float**)hist[0]->thresh2; - if( huniform ) - { - for(int i = 0; i < hdims; i++ ) - uranges[i] = &hist[0]->thresh[i][0]; - hranges = uranges; - } - } - - std::vector imagesv(hdims); - copy(images.begin(), images.begin() + hdims, imagesv.begin()); - - cv::Mat dst = images[CV_MAX_DIM+1]; - - CV_Assert( dst.size() == imagesv[0].size() && dst.depth() == imagesv[0].depth() ); - - if( !CV_IS_SPARSE_HIST(hist[0]) ) - { - cv::Mat H = cv::cvarrToMat(hist[0]->bins); - if(huniform) - { - vector emptyChannels; - vector vranges; - if(hranges) - { - vranges.resize(hdims*2); - for(int i = 0; i < hdims; i++ ) - { - vranges[i*2 ] = hist[0]->thresh[i][0]; - vranges[i*2+1] = hist[0]->thresh[i][1]; - } - } - cv::calcBackProject(imagesv, emptyChannels, H, dst, vranges, 1); - } - else - { - cv::calcBackProject( &imagesv[0], (int)imagesv.size(), - 0, H, dst, hranges, 1, false ); - } - } - else - { - cv::SparseMat sH; - ((const CvSparseMat*)hist[0]->bins)->copyToSparseMat(sH); - cv::calcBackProject( &imagesv[0], (int)imagesv.size(), - 0, sH, dst, hranges, 1, huniform ); - } -} - - -static void -cvTsCalcBackProject( const vector& images, Mat dst, CvHistogram* hist, const vector& channels ) -{ - int x, y, k, cdims; - union - { - const float* fl; - const uchar* ptr; - } - plane[CV_MAX_DIM]; - int nch[CV_MAX_DIM]; - int dims[CV_MAX_DIM]; - int uniform = CV_IS_UNIFORM_HIST(hist); - Size img_size = images[0].size(); - int img_depth = images[0].depth(); - - cdims = cvGetDims( hist->bins, dims ); - - for( k = 0; k < cdims; k++ ) - nch[k] = images[k].channels(); - - for( y = 0; y < img_size.height; y++ ) - { - if( img_depth == CV_8U ) - for( k = 0; k < cdims; k++ ) - plane[k].ptr = images[k].ptr(y) + channels[k]; - else - for( k = 0; k < cdims; k++ ) - plane[k].fl = images[k].ptr(y) + channels[k]; - - for( x = 0; x < img_size.width; x++ ) - { - float val[CV_MAX_DIM]; - float bin_val = 0; - int idx[CV_MAX_DIM]; - - if( img_depth == CV_8U ) - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].ptr[x*nch[k]]; - else - for( k = 0; k < cdims; k++ ) - val[k] = plane[k].fl[x*nch[k]]; - idx[cdims-1] = -1; - - if( uniform ) - { - for( k = 0; k < cdims; k++ ) - { - double v = val[k], lo = hist->thresh[k][0], hi = hist->thresh[k][1]; - idx[k] = cvFloor((v - lo)*dims[k]/(hi - lo)); - if( idx[k] < 0 || idx[k] >= dims[k] ) - break; - } - } - else - { - for( k = 0; k < cdims; k++ ) - { - float v = val[k]; - float* t = hist->thresh2[k]; - int j, n = dims[k]; - - for( j = 0; j <= n; j++ ) - if( v < t[j] ) - break; - if( j <= 0 || j > n ) - break; - idx[k] = j-1; - } - } - - if( k == cdims ) - bin_val = (float)cvGetRealND( hist->bins, idx ); - - if( img_depth == CV_8U ) - { - int t = cvRound(bin_val); - dst.at(y, x) = saturate_cast(t); - } - else - dst.at(y, x) = bin_val; - } - } -} - - -int CV_CalcBackProjectTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - - cvTsCalcBackProject( images, images[CV_MAX_DIM+2], hist[0], channels ); - Mat a = images[CV_MAX_DIM+1], b = images[CV_MAX_DIM+2]; - double threshold = a.depth() == CV_8U ? 2 : FLT_EPSILON; - code = cvtest::cmpEps2( ts, a, b, threshold, true, "Back project image" ); - - if( code < 0 ) - ts->set_failed_test_info( code ); - - return code; -} - - -////////////// cvCalcBackProjectPatch ////////////// - -class CV_CalcBackProjectPatchTest : public CV_BaseHistTest -{ -public: - CV_CalcBackProjectPatchTest(); - ~CV_CalcBackProjectPatchTest(); - void clear(); - -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - vector images; - vector channels; - - Size patch_size; - double factor; - int method; -}; - - -CV_CalcBackProjectPatchTest::CV_CalcBackProjectPatchTest() : - images(CV_MAX_DIM+2), channels(CV_MAX_DIM+2) -{ - hist_count = 1; - gen_random_hist = 0; - init_ranges = 1; - img_max_log_size = 6; -} - - -CV_CalcBackProjectPatchTest::~CV_CalcBackProjectPatchTest() -{ - clear(); -} - - -void CV_CalcBackProjectPatchTest::clear() -{ - CV_BaseHistTest::clear(); -} - - -int CV_CalcBackProjectPatchTest::prepare_test_case( int test_case_idx ) -{ - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - if( code > 0 ) - { - RNG& rng = ts->get_rng(); - int i, j, n, img_len = img_size.area(); - - patch_size.width = cvtest::randInt(rng) % img_size.width + 1; - patch_size.height = cvtest::randInt(rng) % img_size.height + 1; - patch_size.width = MIN( patch_size.width, 30 ); - patch_size.height = MIN( patch_size.height, 30 ); - - factor = 1.; - method = cvtest::randInt(rng) % CV_CompareHistTest::MAX_METHOD; - - for( i = 0; i < CV_MAX_DIM + 2; i++ ) - { - if( i < cdims ) - { - int nch = 1; //cvtest::randInt(rng) % 3 + 1; - images[i] = Mat(img_size, CV_MAKETYPE(img_type, nch)); - channels[i] = cvtest::randInt(rng) % nch; - cvtest::randUni( rng, images[i], Scalar::all(low), Scalar::all(high) ); - } - else if( i >= CV_MAX_DIM ) - { - images[i] = Mat(img_size - patch_size + Size(1, 1), CV_32F); - } - } - - cvTsCalcHist( images, hist[0], Mat(), channels ); - cvNormalizeHist( hist[0], factor ); - - // now modify the images a bit - n = cvtest::randInt(rng) % (img_len/10+1); - for( i = 0; i < cdims; i++ ) - { - uchar* data = images[i].data; - for( j = 0; j < n; j++ ) - { - int idx = cvtest::randInt(rng) % img_len; - double val = cvtest::randReal(rng)*(high - low) + low; - - if( img_type == CV_8U ) - ((uchar*)data)[idx] = (uchar)cvRound(val); - else - ((float*)data)[idx] = (float)val; - } - } - } - - return code; -} - - -void CV_CalcBackProjectPatchTest::run_func(void) -{ - CvMat dst = cvMat(images[CV_MAX_DIM]); - vector img(cdims); - vector pimg(cdims); - for(int i = 0; i < cdims; i++) - { - img[i] = cvMat(images[i]); - pimg[i] = &img[i]; - } - cvCalcArrBackProjectPatch( (CvArr**)&pimg[0], &dst, cvSize(patch_size), hist[0], method, factor ); -} - - -static void -cvTsCalcBackProjectPatch( const vector& images, Mat dst, Size patch_size, - CvHistogram* hist, int method, - double factor, const vector& channels ) -{ - CvHistogram* model = 0; - - int x, y; - Size size = dst.size(); - - cvCopyHist( hist, &model ); - cvNormalizeHist( hist, factor ); - - vector img(images.size()); - for( y = 0; y < size.height; y++ ) - { - for( x = 0; x < size.width; x++ ) - { - double result; - - Rect roi(Point(x, y), patch_size); - for(size_t i = 0; i < img.size(); i++) - img[i] = images[i](roi); - - cvTsCalcHist( img, model, Mat(), channels ); - cvNormalizeHist( model, factor ); - result = cvCompareHist( model, hist, method ); - dst.at(y, x) = (float)result; - } - } - - cvReleaseHist( &model ); -} - - -int CV_CalcBackProjectPatchTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - double err_level = 5e-3; - - Mat dst = images[CV_MAX_DIM+1]; - vector imagesv(cdims); - for(int i = 0; i < cdims; i++) - imagesv[i] = images[i]; - cvTsCalcBackProjectPatch( imagesv, dst, patch_size, hist[0], - method, factor, channels ); - - Mat a = images[CV_MAX_DIM], b = images[CV_MAX_DIM+1]; - code = cvtest::cmpEps2( ts, a, b, err_level, true, "BackProjectPatch result" ); - - if( code < 0 ) - ts->set_failed_test_info( code ); - - return code; -} - - -////////////// cvCalcBayesianProb ////////////// - -class CV_BayesianProbTest : public CV_BaseHistTest -{ -public: - enum { MAX_METHOD = 4 }; - - CV_BayesianProbTest(); -protected: - int prepare_test_case( int test_case_idx ); - void run_func(void); - int validate_test_results( int test_case_idx ); - void init_hist( int test_case_idx, int i ); - void get_hist_params( int test_case_idx ); -}; - - - -CV_BayesianProbTest::CV_BayesianProbTest() -{ - hist_count = CV_MAX_DIM; - gen_random_hist = 1; -} - - -void CV_BayesianProbTest::get_hist_params( int test_case_idx ) -{ - CV_BaseHistTest::get_hist_params( test_case_idx ); - hist_type = CV_HIST_ARRAY; -} - - -void CV_BayesianProbTest::init_hist( int test_case_idx, int hist_i ) -{ - if( hist_i < hist_count/2 ) - CV_BaseHistTest::init_hist( test_case_idx, hist_i ); -} - - -int CV_BayesianProbTest::prepare_test_case( int test_case_idx ) -{ - RNG& rng = ts->get_rng(); - - hist_count = (cvtest::randInt(rng) % (MAX_HIST/2-1) + 2)*2; - hist_count = MIN( hist_count, MAX_HIST ); - int code = CV_BaseHistTest::prepare_test_case( test_case_idx ); - - return code; -} - - -void CV_BayesianProbTest::run_func(void) -{ - cvCalcBayesianProb( &hist[0], hist_count/2, &hist[hist_count/2] ); -} - - -int CV_BayesianProbTest::validate_test_results( int /*test_case_idx*/ ) -{ - int code = cvtest::TS::OK; - int i, j, n = hist_count/2; - double s[CV_MAX_DIM]; - const double err_level = 1e-5; - - for( i = 0; i < total_size; i++ ) - { - double sum = 0; - for( j = 0; j < n; j++ ) - { - double v = hist[j]->mat.data.fl[i]; - sum += v; - s[j] = v; - } - sum = sum > DBL_EPSILON ? 1./sum : 0; - - for( j = 0; j < n; j++ ) - { - double v0 = s[j]*sum; - double v = hist[j+n]->mat.data.fl[i]; - - if( cvIsNaN(v) || cvIsInf(v) ) - { - ts->printf( cvtest::TS::LOG, - "The element #%d in the destination histogram #%d is invalid (=%g)\n", - i, j, v ); - code = cvtest::TS::FAIL_INVALID_OUTPUT; - break; - } - else if( fabs(v0 - v) > err_level*fabs(v0) ) - { - ts->printf( cvtest::TS::LOG, - "The element #%d in the destination histogram #%d is inaccurate (=%g, should be =%g)\n", - i, j, v, v0 ); - code = cvtest::TS::FAIL_BAD_ACCURACY; - break; - } - } - if( j < n ) - break; - } - - if( code < 0 ) - ts->set_failed_test_info( code ); - return code; -} - -////////////////////////////////////////////////////////////////////////////////////////////////////// - -TEST(Imgproc_Hist_Calc, accuracy) { CV_CalcHistTest test; test.safe_run(); } -TEST(Imgproc_Hist_Query, accuracy) { CV_QueryHistTest test; test.safe_run(); } - -TEST(Imgproc_Hist_Compare, accuracy) { CV_CompareHistTest test; test.safe_run(); } -TEST(Imgproc_Hist_Threshold, accuracy) { CV_ThreshHistTest test; test.safe_run(); } -TEST(Imgproc_Hist_Normalize, accuracy) { CV_NormHistTest test; test.safe_run(); } -TEST(Imgproc_Hist_MinMaxVal, accuracy) { CV_MinMaxHistTest test; test.safe_run(); } - -TEST(Imgproc_Hist_CalcBackProject, accuracy) { CV_CalcBackProjectTest test; test.safe_run(); } -TEST(Imgproc_Hist_CalcBackProjectPatch, accuracy) { CV_CalcBackProjectPatchTest test; test.safe_run(); } -TEST(Imgproc_Hist_BayesianProb, accuracy) { CV_BayesianProbTest test; test.safe_run(); } - TEST(Imgproc_Hist_Calc, calcHist_regression_11544) { cv::Mat1w m = cv::Mat1w::zeros(10, 10); diff --git a/modules/imgproc/test/test_houghcircles.cpp b/modules/imgproc/test/test_houghcircles.cpp index 094963211c..74608112a7 100644 --- a/modules/imgproc/test/test_houghcircles.cpp +++ b/modules/imgproc/test/test_houghcircles.cpp @@ -123,7 +123,7 @@ public: vector circles; const double dp = 1.0; - HoughCircles(src, circles, CV_HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); + HoughCircles(src, circles, cv::HOUGH_GRADIENT, dp, minDist, edgeThreshold, accumThreshold, minRadius, maxRadius); string imgProc = string(cvtest::TS::ptr()->get_data_path()) + "imgproc/"; #if DEBUG_IMAGES diff --git a/modules/imgproc/test/test_imgwarp.cpp b/modules/imgproc/test/test_imgwarp.cpp index dbc8fb8704..c1710268dd 100644 --- a/modules/imgproc/test/test_imgwarp.cpp +++ b/modules/imgproc/test/test_imgwarp.cpp @@ -197,182 +197,10 @@ int CV_ImgWarpBaseTest::prepare_test_case( int test_case_idx ) return code; } - -///////////////////////// - -class CV_ResizeTest : public CV_ImgWarpBaseTest -{ -public: - CV_ResizeTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void run_func(); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_ResizeTest::CV_ResizeTest() : CV_ImgWarpBaseTest( false ) -{ -} - - -void CV_ResizeTest::get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - Size sz; - - sz.width = (cvtest::randInt(rng) % sizes[INPUT][0].width) + 1; - sz.height = (cvtest::randInt(rng) % sizes[INPUT][0].height) + 1; - - if( cvtest::randInt(rng) & 1 ) - { - int xfactor = cvtest::randInt(rng) % 10 + 1; - int yfactor = cvtest::randInt(rng) % 10 + 1; - - if( cvtest::randInt(rng) & 1 ) - yfactor = xfactor; - - sz.width = sizes[INPUT][0].width / xfactor; - sz.width = MAX(sz.width,1); - sz.height = sizes[INPUT][0].height / yfactor; - sz.height = MAX(sz.height,1); - sizes[INPUT][0].width = sz.width * xfactor; - sizes[INPUT][0].height = sz.height * yfactor; - } - - if( cvtest::randInt(rng) & 1 ) - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sz; - else - { - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = sizes[INPUT][0]; - sizes[INPUT][0] = sz; - } - if( interpolation == 4 && - (MIN(sizes[INPUT][0].width,sizes[INPUT_OUTPUT][0].width) < 4 || - MIN(sizes[INPUT][0].height,sizes[INPUT_OUTPUT][0].height) < 4)) - interpolation = 2; -} - - -void CV_ResizeTest::run_func() -{ - cvResize( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], interpolation ); -} - - -double CV_ResizeTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 1e-1; -} - - -void CV_ResizeTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMat _src = cvMat(test_mat[INPUT][0]), _dst = cvMat(test_mat[REF_INPUT_OUTPUT][0]); - CvMat *src = &_src, *dst = &_dst; - int i, j, k; - CvMat* x_idx = cvCreateMat( 1, dst->cols, CV_32SC1 ); - CvMat* y_idx = cvCreateMat( 1, dst->rows, CV_32SC1 ); - int* x_tab = x_idx->data.i; - int elem_size = CV_ELEM_SIZE(src->type); - int drows = dst->rows, dcols = dst->cols; - - if( interpolation == CV_INTER_NN ) - { - for( j = 0; j < dcols; j++ ) - { - int t = (j*src->cols*2 + MIN(src->cols,dcols) - 1)/(dcols*2); - t -= t >= src->cols; - x_idx->data.i[j] = t*elem_size; - } - - for( j = 0; j < drows; j++ ) - { - int t = (j*src->rows*2 + MIN(src->rows,drows) - 1)/(drows*2); - t -= t >= src->rows; - y_idx->data.i[j] = t; - } - } - else - { - double scale_x = (double)src->cols/dcols; - double scale_y = (double)src->rows/drows; - - for( j = 0; j < dcols; j++ ) - { - double f = ((j+0.5)*scale_x - 0.5); - i = cvRound(f); - x_idx->data.i[j] = (i < 0 ? 0 : i >= src->cols ? src->cols - 1 : i)*elem_size; - } - - for( j = 0; j < drows; j++ ) - { - double f = ((j+0.5)*scale_y - 0.5); - i = cvRound(f); - y_idx->data.i[j] = i < 0 ? 0 : i >= src->rows ? src->rows - 1 : i; - } - } - - for( i = 0; i < drows; i++ ) - { - uchar* dptr = dst->data.ptr + dst->step*i; - const uchar* sptr0 = src->data.ptr + src->step*y_idx->data.i[i]; - - for( j = 0; j < dcols; j++, dptr += elem_size ) - { - const uchar* sptr = sptr0 + x_tab[j]; - for( k = 0; k < elem_size; k++ ) - dptr[k] = sptr[k]; - } - } - - cvReleaseMat( &x_idx ); - cvReleaseMat( &y_idx ); -} - -class CV_ResizeExactTest : public CV_ResizeTest -{ -public: - CV_ResizeExactTest(); - -protected: - void get_test_array_types_and_sizes(int test_case_idx, vector >& sizes, vector >& types); -}; - - -CV_ResizeExactTest::CV_ResizeExactTest() : CV_ResizeTest() -{ - max_interpolation = 2; -} - - -void CV_ResizeExactTest::get_test_array_types_and_sizes(int test_case_idx, vector >& sizes, vector >& types) -{ - CV_ResizeTest::get_test_array_types_and_sizes(test_case_idx, sizes, types); - switch (interpolation) - { - case 0: - interpolation = INTER_LINEAR_EXACT; - break; - case 1: - interpolation = INTER_NEAREST_EXACT; - break; - default: - CV_Assert(interpolation < max_interpolation); - } - if (CV_MAT_DEPTH(types[INPUT][0]) == CV_32F || - CV_MAT_DEPTH(types[INPUT][0]) == CV_64F) - types[INPUT][0] = types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(CV_8U, CV_MAT_CN(types[INPUT][0])); -} - ///////////////////////// static void test_remap( const Mat& src, Mat& dst, const Mat& mapx, const Mat& mapy, - Mat* mask=0, int interpolation=CV_INTER_LINEAR ) + Mat* mask=0, int interpolation=cv::INTER_LINEAR ) { int x, y, k; int drows = dst.rows, dcols = dst.cols; @@ -383,7 +211,7 @@ static void test_remap( const Mat& src, Mat& dst, const Mat& mapx, const Mat& ma int step = (int)(src.step / CV_ELEM_SIZE(depth)); int delta; - if( interpolation != CV_INTER_CUBIC ) + if( interpolation != cv::INTER_CUBIC ) { delta = 0; scols -= 1; srows -= 1; @@ -488,243 +316,6 @@ static void test_remap( const Mat& src, Mat& dst, const Mat& mapx, const Mat& ma } } -///////////////////////// - -class CV_WarpAffineTest : public CV_ImgWarpBaseTest -{ -public: - CV_WarpAffineTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_WarpAffineTest::CV_WarpAffineTest() : CV_ImgWarpBaseTest( true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - spatial_scale_decimate = spatial_scale_zoom; -} - - -void CV_WarpAffineTest::get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ) -{ - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - Size sz = sizes[INPUT][0]; - // run for the second time to get output of a different size - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sz; - sizes[INPUT][1] = Size( 3, 2 ); -} - - -void CV_WarpAffineTest::run_func() -{ - CvMat mtx = cvMat(test_mat[INPUT][1]); - cvWarpAffine( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &mtx, interpolation ); -} - - -double CV_WarpAffineTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_WarpAffineTest::prepare_test_case( int test_case_idx ) -{ - RNG& rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const Mat& src = test_mat[INPUT][0]; - const Mat& dst = test_mat[INPUT_OUTPUT][0]; - Mat& mat = test_mat[INPUT][1]; - Point2f center; - double scale, angle; - - if( code <= 0 ) - return code; - - double buffer[6]; - Mat tmp( 2, 3, mat.type(), buffer ); - - center.x = (float)((cvtest::randReal(rng)*1.2 - 0.1)*src.cols); - center.y = (float)((cvtest::randReal(rng)*1.2 - 0.1)*src.rows); - angle = cvtest::randReal(rng)*360; - scale = ((double)dst.rows/src.rows + (double)dst.cols/src.cols)*0.5; - getRotationMatrix2D(center, angle, scale).convertTo(mat, mat.depth()); - rng.fill( tmp, CV_RAND_NORMAL, Scalar::all(1.), Scalar::all(0.01) ); - cv::max(tmp, 0.9, tmp); - cv::min(tmp, 1.1, tmp); - cv::multiply(tmp, mat, mat, 1.); - - return code; -} - - -void CV_WarpAffineTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - const Mat& src = test_mat[INPUT][0]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - Mat& dst0 = test_mat[INPUT_OUTPUT][0]; - Mat mapx(dst.size(), CV_32F), mapy(dst.size(), CV_32F); - double m[6]; - Mat srcAb, dstAb( 2, 3, CV_64FC1, m ); - - //cvInvert( &tM, &M, CV_LU ); - // [R|t] -> [R^-1 | -(R^-1)*t] - test_mat[INPUT][1].convertTo( srcAb, CV_64F ); - Mat A = srcAb.colRange(0, 2); - Mat b = srcAb.col(2); - Mat invA = dstAb.colRange(0, 2); - Mat invAb = dstAb.col(2); - cv::invert(A, invA, CV_SVD); - cv::gemm(invA, b, -1, Mat(), 0, invAb); - - for( int y = 0; y < dst.rows; y++ ) - for( int x = 0; x < dst.cols; x++ ) - { - mapx.at(y, x) = (float)(x*m[0] + y*m[1] + m[2]); - mapy.at(y, x) = (float)(x*m[3] + y*m[4] + m[5]); - } - - Mat mask( dst.size(), CV_8U ); - test_remap( src, dst, mapx, mapy, &mask ); - dst.setTo(Scalar::all(0), mask); - dst0.setTo(Scalar::all(0), mask); -} - - -///////////////////////// - -class CV_WarpPerspectiveTest : public CV_ImgWarpBaseTest -{ -public: - CV_WarpPerspectiveTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_WarpPerspectiveTest::CV_WarpPerspectiveTest() : CV_ImgWarpBaseTest( true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - spatial_scale_decimate = spatial_scale_zoom; -} - - -void CV_WarpPerspectiveTest::get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ) -{ - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - Size sz = sizes[INPUT][0]; - // run for the second time to get output of a different size - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - sizes[INPUT][0] = sz; - sizes[INPUT][1] = Size( 3, 3 ); -} - - -void CV_WarpPerspectiveTest::run_func() -{ - CvMat mtx = cvMat(test_mat[INPUT][1]); - cvWarpPerspective( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &mtx, interpolation ); -} - - -double CV_WarpPerspectiveTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth == CV_8U ? 16 : depth == CV_16U ? 1024 : 5e-2; -} - - -int CV_WarpPerspectiveTest::prepare_test_case( int test_case_idx ) -{ - RNG& rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const CvMat src = cvMat(test_mat[INPUT][0]); - const CvMat dst = cvMat(test_mat[INPUT_OUTPUT][0]); - Mat& mat = test_mat[INPUT][1]; - Point2f s[4], d[4]; - int i; - - if( code <= 0 ) - return code; - - s[0] = Point2f(0,0); - d[0] = Point2f(0,0); - s[1] = Point2f(src.cols-1.f,0); - d[1] = Point2f(dst.cols-1.f,0); - s[2] = Point2f(src.cols-1.f,src.rows-1.f); - d[2] = Point2f(dst.cols-1.f,dst.rows-1.f); - s[3] = Point2f(0,src.rows-1.f); - d[3] = Point2f(0,dst.rows-1.f); - - float bufer[16]; - Mat tmp( 1, 16, CV_32FC1, bufer ); - - rng.fill( tmp, CV_RAND_NORMAL, Scalar::all(0.), Scalar::all(0.1) ); - - for( i = 0; i < 4; i++ ) - { - s[i].x += bufer[i*4]*src.cols/2; - s[i].y += bufer[i*4+1]*src.rows/2; - d[i].x += bufer[i*4+2]*dst.cols/2; - d[i].y += bufer[i*4+3]*dst.rows/2; - } - - cv::getPerspectiveTransform( s, d ).convertTo( mat, mat.depth() ); - return code; -} - - -void CV_WarpPerspectiveTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - Mat& dst0 = test_mat[INPUT_OUTPUT][0]; - Mat mapx(dst.size(), CV_32F), mapy(dst.size(), CV_32F); - double m[9]; - Mat srcM, dstM(3, 3, CV_64F, m); - - //cvInvert( &tM, &M, CV_LU ); - // [R|t] -> [R^-1 | -(R^-1)*t] - test_mat[INPUT][1].convertTo( srcM, CV_64F ); - cv::invert(srcM, dstM, CV_SVD); - - for( int y = 0; y < dst.rows; y++ ) - { - for( int x = 0; x < dst.cols; x++ ) - { - double xs = x*m[0] + y*m[1] + m[2]; - double ys = x*m[3] + y*m[4] + m[5]; - double ds = x*m[6] + y*m[7] + m[8]; - - ds = ds ? 1./ds : 0; - xs *= ds; - ys *= ds; - - mapx.at(y, x) = (float)xs; - mapy.at(y, x) = (float)ys; - } - } - - Mat mask( dst.size(), CV_8U ); - test_remap( src, dst, mapx, mapy, &mask ); - dst.setTo(Scalar::all(0), mask); - dst0.setTo(Scalar::all(0), mask); -} - - ///////////////////////// class CV_RemapTest : public CV_ImgWarpBaseTest @@ -756,7 +347,7 @@ void CV_RemapTest::get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void run_func(); - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - double get_success_error_level( int test_case_idx, int i, int j ); -}; - - -CV_GetQuadSubPixTest::CV_GetQuadSubPixTest() : CV_ImgWarpBaseTest( true ) -{ - //spatial_scale_zoom = spatial_scale_decimate; - spatial_scale_decimate = spatial_scale_zoom; -} - - -void CV_GetQuadSubPixTest::get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ) -{ - int min_size = 4; - CV_ImgWarpBaseTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - Size sz = sizes[INPUT][0], dsz; - RNG& rng = ts->get_rng(); - int msz, src_depth = cvtest::randInt(rng) % 2, dst_depth; - int cn = cvtest::randInt(rng) % 2 ? 3 : 1; - - dst_depth = src_depth = src_depth == 0 ? CV_8U : CV_32F; - if( src_depth < CV_32F && cvtest::randInt(rng) % 2 ) - dst_depth = CV_32F; - - types[INPUT][0] = CV_MAKETYPE(src_depth,cn); - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(dst_depth,cn); - - sz.width = MAX(sz.width,min_size); - sz.height = MAX(sz.height,min_size); - sizes[INPUT][0] = sz; - msz = MIN( sz.width, sz.height ); - - dsz.width = cvRound(sqrt(cvtest::randReal(rng)*msz) + 1); - dsz.height = cvRound(sqrt(cvtest::randReal(rng)*msz) + 1); - dsz.width = MIN(dsz.width,msz); - dsz.height = MIN(dsz.width,msz); - dsz.width = MAX(dsz.width,min_size); - dsz.height = MAX(dsz.height,min_size); - sizes[INPUT_OUTPUT][0] = sizes[REF_INPUT_OUTPUT][0] = dsz; - sizes[INPUT][1] = cvSize( 3, 2 ); -} - - -void CV_GetQuadSubPixTest::run_func() -{ - CvMat mtx = cvMat(test_mat[INPUT][1]); - cvGetQuadrangleSubPix( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], &mtx ); -} - - -double CV_GetQuadSubPixTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int in_depth = test_mat[INPUT][0].depth(); - //int out_depth = test_mat[INPUT_OUTPUT][0].depth(); - - return in_depth >= CV_32F ? 1e-2 : 4; -} - - -int CV_GetQuadSubPixTest::prepare_test_case( int test_case_idx ) -{ - RNG& rng = ts->get_rng(); - int code = CV_ImgWarpBaseTest::prepare_test_case( test_case_idx ); - const Mat& src = test_mat[INPUT][0]; - Mat& mat = test_mat[INPUT][1]; - Point2f center; - double scale, angle; - - if( code <= 0 ) - return code; - - double a[6]; - Mat A( 2, 3, CV_64FC1, a ); - - center.x = (float)((cvtest::randReal(rng)*1.2 - 0.1)*src.cols); - center.y = (float)((cvtest::randReal(rng)*1.2 - 0.1)*src.rows); - angle = cvtest::randReal(rng)*360; - scale = cvtest::randReal(rng)*0.2 + 0.9; - - // y = Ax + b -> x = A^-1(y - b) = A^-1*y - A^-1*b - scale = 1./scale; - angle = angle*(CV_PI/180.); - a[0] = a[4] = cos(angle)*scale; - a[1] = sin(angle)*scale; - a[3] = -a[1]; - a[2] = center.x - a[0]*center.x - a[1]*center.y; - a[5] = center.y - a[3]*center.x - a[4]*center.y; - A.convertTo( mat, mat.depth() ); - - return code; -} - - -void CV_GetQuadSubPixTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src0 = test_mat[INPUT][0]; - Mat& dst0 = test_mat[REF_INPUT_OUTPUT][0]; - Mat src = src0, dst = dst0; - int ftype = CV_MAKETYPE(CV_32F,src0.channels()); - double a[6], dx = (dst0.cols - 1)*0.5, dy = (dst0.rows - 1)*0.5; - Mat A( 2, 3, CV_64F, a ); - - if( src.depth() != CV_32F ) - src0.convertTo(src, CV_32F); - - if( dst.depth() != CV_32F ) - dst.create(dst0.size(), ftype); - - test_mat[INPUT][1].convertTo( A, CV_64F ); - a[2] -= a[0]*dx + a[1]*dy; - a[5] -= a[3]*dx + a[4]*dy; - test_getQuadrangeSubPix( src, dst, a ); - - if( dst.data != dst0.data ) - dst.convertTo(dst0, dst0.depth()); -} - ////////////////////////////// resizeArea ///////////////////////////////// template @@ -1292,13 +755,8 @@ TEST(Imgproc_resize_area, regression_quarter_round) ////////////////////////////////////////////////////////////////////////// -TEST(Imgproc_Resize, accuracy) { CV_ResizeTest test; test.safe_run(); } -TEST(Imgproc_ResizeExact, accuracy) { CV_ResizeExactTest test; test.safe_run(); } -TEST(Imgproc_WarpAffine, accuracy) { CV_WarpAffineTest test; test.safe_run(); } -TEST(Imgproc_WarpPerspective, accuracy) { CV_WarpPerspectiveTest test; test.safe_run(); } TEST(Imgproc_Remap, accuracy) { CV_RemapTest test; test.safe_run(); } TEST(Imgproc_GetRectSubPix, accuracy) { CV_GetRectSubPixTest test; test.safe_run(); } -TEST(Imgproc_GetQuadSubPix, accuracy) { CV_GetQuadSubPixTest test; test.safe_run(); } ////////////////////////////////////////////////////////////////////////// @@ -1526,11 +984,11 @@ TEST(Imgproc_linearPolar, identity) { linearPolar(src, dst, Point2f((N-1) * 0.5f, (N-1) * 0.5f), N * 0.5f, - CV_WARP_FILL_OUTLIERS | CV_INTER_LINEAR | CV_WARP_INVERSE_MAP); + cv::WARP_FILL_OUTLIERS | cv::INTER_LINEAR | cv::WARP_INVERSE_MAP); linearPolar(dst, src, Point2f((N-1) * 0.5f, (N-1) * 0.5f), N * 0.5f, - CV_WARP_FILL_OUTLIERS | CV_INTER_LINEAR); + cv::WARP_FILL_OUTLIERS | cv::INTER_LINEAR); double psnr = cvtest::PSNR(in(roi), src(roi)); EXPECT_LE(25, psnr) << "iteration=" << i; diff --git a/modules/imgproc/test/test_imgwarp_strict.cpp b/modules/imgproc/test/test_imgwarp_strict.cpp index eea5e447e9..da8a197b3f 100644 --- a/modules/imgproc/test/test_imgwarp_strict.cpp +++ b/modules/imgproc/test/test_imgwarp_strict.cpp @@ -163,7 +163,7 @@ void CV_ImageWarpBaseTest::generate_test_data() for (y = 0; y < ssize.height; y += cell_size) for (x = 0; x < ssize.width; x += cell_size) rectangle(src, Point(x, y), Point(x + std::min(cell_size, ssize.width - x), y + - std::min(cell_size, ssize.height - y)), Scalar::all((x + y) % 2 ? 255: 0), CV_FILLED); + std::min(cell_size, ssize.height - y)), Scalar::all((x + y) % 2 ? 255: 0), cv::FILLED); } else { @@ -175,7 +175,7 @@ void CV_ImageWarpBaseTest::generate_test_data() } // generating an interpolation type - interpolation = rng.uniform(0, CV_INTER_LANCZOS4 + 1); + interpolation = rng.uniform(0, cv::INTER_LANCZOS4 + 1); // generating the dst matrix structure double scale_x, scale_y; @@ -288,10 +288,10 @@ void CV_ImageWarpBaseTest::validate_results() const #ifdef SHOW_IMAGE const std::string w1("OpenCV impl (run func)"), w2("Reference func"), w3("Src image"), w4("Diff"); - namedWindow(w1, CV_WINDOW_KEEPRATIO); - namedWindow(w2, CV_WINDOW_KEEPRATIO); - namedWindow(w3, CV_WINDOW_KEEPRATIO); - namedWindow(w4, CV_WINDOW_KEEPRATIO); + namedWindow(w1, cv::WINDOW_KEEPRATIO); + namedWindow(w2, cv::WINDOW_KEEPRATIO); + namedWindow(w3, cv::WINDOW_KEEPRATIO); + namedWindow(w4, cv::WINDOW_KEEPRATIO); Mat diff; absdiff(reference_dst, _dst, diff); @@ -442,7 +442,7 @@ void CV_Resize_Test::generate_test_data() for (y = 0; y < ssize.height; y += cell_size) for (x = 0; x < ssize.width; x += cell_size) rectangle(src, Point(x, y), Point(x + std::min(cell_size, ssize.width - x), y + - std::min(cell_size, ssize.height - y)), Scalar::all((x + y) % 2 ? 255: 0), CV_FILLED); + std::min(cell_size, ssize.height - y)), Scalar::all((x + y) % 2 ? 255: 0), cv::FILLED); } else { @@ -1082,7 +1082,7 @@ void CV_WarpAffine_Test::generate_test_data() // warp_matrix is inverse if (rng.uniform(0., 1.) > 0) - interpolation |= CV_WARP_INVERSE_MAP; + interpolation |= cv::WARP_INVERSE_MAP; } void CV_WarpAffine_Test::run_func() @@ -1123,7 +1123,7 @@ void CV_WarpAffine_Test::warpAffine(const Mat& _src, Mat& _dst) else mapy = Mat(); - if (!(interpolation & CV_WARP_INVERSE_MAP)) + if (!(interpolation & cv::WARP_INVERSE_MAP)) invertAffineTransform(tM.clone(), tM); const int AB_BITS = MAX(10, (int)INTER_BITS); @@ -1239,7 +1239,7 @@ void CV_WarpPerspective_Test::warpPerspective(const Mat& _src, Mat& _dst) M = tmp; } - if (!(interpolation & CV_WARP_INVERSE_MAP)) + if (!(interpolation & cv::WARP_INVERSE_MAP)) { Mat tmp; invert(M, tmp); diff --git a/modules/imgproc/test/test_moments.cpp b/modules/imgproc/test/test_moments.cpp index faaf4cd108..0f1d0344dd 100644 --- a/modules/imgproc/test/test_moments.cpp +++ b/modules/imgproc/test/test_moments.cpp @@ -43,373 +43,6 @@ namespace opencv_test { namespace { -#define OCL_TUNING_MODE 0 -#if OCL_TUNING_MODE -#define OCL_TUNING_MODE_ONLY(code) code -#else -#define OCL_TUNING_MODE_ONLY(code) -#endif - -// image moments -class CV_MomentsTest : public cvtest::ArrayTest -{ -public: - CV_MomentsTest(bool try_umat); - -protected: - - enum { MOMENT_COUNT = 25 }; - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - bool is_binary; - bool try_umat_; -}; - - -CV_MomentsTest::CV_MomentsTest(bool try_umat) : - try_umat_(try_umat) -{ - test_array[INPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - is_binary = false; - OCL_TUNING_MODE_ONLY(test_case_count = 10); - //element_wise_relative_error = false; -} - - -void CV_MomentsTest::get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ) -{ - cvtest::ArrayTest::get_minmax_bounds( i, j, type, low, high ); - int depth = CV_MAT_DEPTH(type); - - if( depth == CV_16U ) - { - low = Scalar::all(0); - high = Scalar::all(1000); - } - else if( depth == CV_16S ) - { - low = Scalar::all(-1000); - high = Scalar::all(1000); - } - else if( depth == CV_32F ) - { - low = Scalar::all(-1); - high = Scalar::all(1); - } -} - -void CV_MomentsTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - int depth = cvtest::randInt(rng) % 4; - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_16S : CV_32F; - - is_binary = cvtest::randInt(rng) % 2 != 0; - - OCL_TUNING_MODE_ONLY( - depth = CV_8U; - is_binary = false; - sizes[INPUT][0] = Size(1024,768) - ); - - types[INPUT][0] = CV_MAKETYPE(depth, 1); - types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(MOMENT_COUNT,1); - if(CV_MAT_DEPTH(types[INPUT][0])>=CV_32S) - sizes[INPUT][0].width = MAX(sizes[INPUT][0].width, 3); - - cvmat_allowed = true; -} - - -double CV_MomentsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - int depth = test_mat[INPUT][0].depth(); - return depth != CV_32F ? FLT_EPSILON*10 : FLT_EPSILON*100; -} - -int CV_MomentsTest::prepare_test_case( int test_case_idx ) -{ - int code = cvtest::ArrayTest::prepare_test_case( test_case_idx ); - return code; -} - - -void CV_MomentsTest::run_func() -{ - CvMoments* m = (CvMoments*)test_mat[OUTPUT][0].ptr(); - double* others = (double*)(m + 1); - if (try_umat_) - { - UMat u; - test_mat[INPUT][0].clone().copyTo(u); - OCL_TUNING_MODE_ONLY( - static double ttime = 0; - static int ncalls = 0; - moments(u, is_binary != 0); - double t = (double)getTickCount()); - Moments new_m = moments(u, is_binary != 0); - OCL_TUNING_MODE_ONLY( - ttime += (double)getTickCount() - t; - ncalls++; - printf("%g\n", ttime/ncalls/u.total())); - *m = cvMoments(new_m); - } - else - cvMoments( test_array[INPUT][0], m, is_binary ); - - others[0] = cvGetNormalizedCentralMoment( m, 2, 0 ); - others[1] = cvGetNormalizedCentralMoment( m, 1, 1 ); - others[2] = cvGetNormalizedCentralMoment( m, 0, 2 ); - others[3] = cvGetNormalizedCentralMoment( m, 3, 0 ); - others[4] = cvGetNormalizedCentralMoment( m, 2, 1 ); - others[5] = cvGetNormalizedCentralMoment( m, 1, 2 ); - others[6] = cvGetNormalizedCentralMoment( m, 0, 3 ); -} - - -void CV_MomentsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - Mat& src = test_mat[INPUT][0]; - CvMoments m = cvMoments(); - double* mdata = test_mat[REF_OUTPUT][0].ptr(); - int depth = src.depth(); - int cn = src.channels(); - int i, y, x, cols = src.cols; - double xc = 0., yc = 0.; - - int coi = 0; - for( y = 0; y < src.rows; y++ ) - { - double s0 = 0, s1 = 0, s2 = 0, s3 = 0; - uchar* ptr = src.ptr(y); - for( x = 0; x < cols; x++ ) - { - double val; - if( depth == CV_8U ) - val = ptr[x*cn + coi]; - else if( depth == CV_16U ) - val = ((ushort*)ptr)[x*cn + coi]; - else if( depth == CV_16S ) - val = ((short*)ptr)[x*cn + coi]; - else - val = ((float*)ptr)[x*cn + coi]; - - if( is_binary ) - val = val != 0; - - s0 += val; - s1 += val*x; - s2 += val*x*x; - s3 += ((val*x)*x)*x; - } - - m.m00 += s0; - m.m01 += s0*y; - m.m02 += (s0*y)*y; - m.m03 += ((s0*y)*y)*y; - - m.m10 += s1; - m.m11 += s1*y; - m.m12 += (s1*y)*y; - - m.m20 += s2; - m.m21 += s2*y; - - m.m30 += s3; - } - - if( m.m00 != 0 ) - { - xc = m.m10/m.m00, yc = m.m01/m.m00; - m.inv_sqrt_m00 = 1./sqrt(fabs(m.m00)); - } - - for( y = 0; y < src.rows; y++ ) - { - double s0 = 0, s1 = 0, s2 = 0, s3 = 0, y1 = y - yc; - uchar* ptr = src.ptr(y); - for( x = 0; x < cols; x++ ) - { - double val, x1 = x - xc; - if( depth == CV_8U ) - val = ptr[x*cn + coi]; - else if( depth == CV_16U ) - val = ((ushort*)ptr)[x*cn + coi]; - else if( depth == CV_16S ) - val = ((short*)ptr)[x*cn + coi]; - else - val = ((float*)ptr)[x*cn + coi]; - - if( is_binary ) - val = val != 0; - - s0 += val; - s1 += val*x1; - s2 += val*x1*x1; - s3 += ((val*x1)*x1)*x1; - } - - m.mu02 += s0*y1*y1; - m.mu03 += ((s0*y1)*y1)*y1; - - m.mu11 += s1*y1; - m.mu12 += (s1*y1)*y1; - - m.mu20 += s2; - m.mu21 += s2*y1; - - m.mu30 += s3; - } - - memcpy( mdata, &m, sizeof(m)); - mdata += sizeof(m)/sizeof(m.m00); - - /* calc normalized moments */ - { - double inv_m00 = m.inv_sqrt_m00*m.inv_sqrt_m00; - double s2 = inv_m00*inv_m00; /* 1./(m00 ^ (2/2 + 1)) */ - double s3 = s2*m.inv_sqrt_m00; /* 1./(m00 ^ (3/2 + 1)) */ - - mdata[0] = m.mu20 * s2; - mdata[1] = m.mu11 * s2; - mdata[2] = m.mu02 * s2; - - mdata[3] = m.mu30 * s3; - mdata[4] = m.mu21 * s3; - mdata[5] = m.mu12 * s3; - mdata[6] = m.mu03 * s3; - } - - double* a = test_mat[REF_OUTPUT][0].ptr(); - double* b = test_mat[OUTPUT][0].ptr(); - for( i = 0; i < MOMENT_COUNT; i++ ) - { - if( fabs(a[i]) < 1e-3 ) - a[i] = 0; - if( fabs(b[i]) < 1e-3 ) - b[i] = 0; - } -} - - -// Hu invariants -class CV_HuMomentsTest : public cvtest::ArrayTest -{ -public: - CV_HuMomentsTest(); - -protected: - - enum { MOMENT_COUNT = 18, HU_MOMENT_COUNT = 7 }; - - int prepare_test_case( int test_case_idx ); - void prepare_to_validation( int /*test_case_idx*/ ); - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); -}; - - -CV_HuMomentsTest::CV_HuMomentsTest() -{ - test_array[INPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); -} - - -void CV_HuMomentsTest::get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high ) -{ - cvtest::ArrayTest::get_minmax_bounds( i, j, type, low, high ); - low = Scalar::all(-10000); - high = Scalar::all(10000); -} - - -void CV_HuMomentsTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_64FC1; - sizes[INPUT][0] = cvSize(MOMENT_COUNT,1); - sizes[OUTPUT][0] = sizes[REF_OUTPUT][0] = cvSize(HU_MOMENT_COUNT,1); -} - - -double CV_HuMomentsTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return FLT_EPSILON; -} - - - -int CV_HuMomentsTest::prepare_test_case( int test_case_idx ) -{ - int code = cvtest::ArrayTest::prepare_test_case( test_case_idx ); - if( code > 0 ) - { - // ... - } - - return code; -} - - -void CV_HuMomentsTest::run_func() -{ - cvGetHuMoments( test_mat[INPUT][0].ptr(), - test_mat[OUTPUT][0].ptr() ); -} - - -void CV_HuMomentsTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - CvMoments* m = test_mat[INPUT][0].ptr(); - CvHuMoments* hu = test_mat[REF_OUTPUT][0].ptr(); - - double inv_m00 = m->inv_sqrt_m00*m->inv_sqrt_m00; - double s2 = inv_m00*inv_m00; /* 1./(m00 ^ (2/2 + 1)) */ - double s3 = s2*m->inv_sqrt_m00; /* 1./(m00 ^ (3/2 + 1)) */ - - double nu20 = m->mu20 * s2; - double nu11 = m->mu11 * s2; - double nu02 = m->mu02 * s2; - - double nu30 = m->mu30 * s3; - double nu21 = m->mu21 * s3; - double nu12 = m->mu12 * s3; - double nu03 = m->mu03 * s3; - - #undef sqr - #define sqr(a) ((a)*(a)) - - hu->hu1 = nu20 + nu02; - hu->hu2 = sqr(nu20 - nu02) + 4*sqr(nu11); - hu->hu3 = sqr(nu30 - 3*nu12) + sqr(3*nu21 - nu03); - hu->hu4 = sqr(nu30 + nu12) + sqr(nu21 + nu03); - hu->hu5 = (nu30 - 3*nu12)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + - (3*nu21 - nu03)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); - hu->hu6 = (nu20 - nu02)*(sqr(nu30 + nu12) - sqr(nu21 + nu03)) + - 4*nu11*(nu30 + nu12)*(nu21 + nu03); - hu->hu7 = (3*nu21 - nu03)*(nu30 + nu12)*(sqr(nu30 + nu12) - 3*sqr(nu21 + nu03)) + - (3*nu12 - nu30)*(nu21 + nu03)*(3*sqr(nu30 + nu12) - sqr(nu21 + nu03)); -} - - -TEST(Imgproc_Moments, accuracy) { CV_MomentsTest test(false); test.safe_run(); } -OCL_TEST(Imgproc_Moments, accuracy) { CV_MomentsTest test(true); test.safe_run(); } -TEST(Imgproc_HuMoments, accuracy) { CV_HuMomentsTest test; test.safe_run(); } - class CV_SmallContourMomentTest : public cvtest::BaseTest { public: diff --git a/modules/imgproc/test/test_pc.cpp b/modules/imgproc/test/test_pc.cpp index edfe0701e5..7b06e3bd65 100644 --- a/modules/imgproc/test/test_pc.cpp +++ b/modules/imgproc/test/test_pc.cpp @@ -66,8 +66,8 @@ void CV_PhaseCorrelatorTest::run( int ) double expectedShiftY = -20.0; // draw 10x10 rectangles @ (100, 100) and (90, 80) should see ~(-10, -20) shift here... - cv::rectangle(r1, Point(100, 100), Point(110, 110), Scalar(0, 0, 0), CV_FILLED); - cv::rectangle(r2, Point(90, 80), Point(100, 90), Scalar(0, 0, 0), CV_FILLED); + cv::rectangle(r1, Point(100, 100), Point(110, 110), Scalar(0, 0, 0), cv::FILLED); + cv::rectangle(r2, Point(90, 80), Point(100, 90), Scalar(0, 0, 0), cv::FILLED); Mat hann; createHanningWindow(hann, r1.size(), CV_64F); diff --git a/modules/imgproc/test/test_templmatch.cpp b/modules/imgproc/test/test_templmatch.cpp index 0994ac5b4a..93a1cdb5e8 100644 --- a/modules/imgproc/test/test_templmatch.cpp +++ b/modules/imgproc/test/test_templmatch.cpp @@ -125,7 +125,7 @@ void CV_TemplMatchTest::get_test_array_types_and_sizes( int test_case_idx, double CV_TemplMatchTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) { if( test_mat[INPUT][1].depth() == CV_8U || - (method >= CV_TM_CCOEFF && test_mat[INPUT][1].cols*test_mat[INPUT][1].rows <= 2) ) + (method >= cv::TM_CCOEFF && test_mat[INPUT][1].cols*test_mat[INPUT][1].rows <= 2) ) return 1e-2; else return 1e-3; @@ -157,7 +157,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu if( b_sdv.val[0]*b_sdv.val[0] + b_sdv.val[1]*b_sdv.val[1] + b_sdv.val[2]*b_sdv.val[2] + b_sdv.val[3]*b_sdv.val[3] < DBL_EPSILON && - method == CV_TM_CCOEFF_NORMED ) + method == cv::TM_CCOEFF_NORMED ) { cvSet( result, cvScalarAll(1.) ); return; @@ -166,7 +166,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu if( method & 1 ) { b_denom = 0; - if( method != CV_TM_CCOEFF_NORMED ) + if( method != cv::TM_CCOEFF_NORMED ) { b_denom = b_sum2; } @@ -180,7 +180,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu b_denom = 1.; } - CV_Assert( CV_TM_SQDIFF <= method && method <= CV_TM_CCOEFF_NORMED ); + CV_Assert( cv::TM_SQDIFF <= method && method <= cv::TM_CCOEFF_NORMED ); for( i = 0; i < result->rows; i++ ) { @@ -195,7 +195,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu const uchar* a = img->data.ptr + i*img->step + j*cn; const uchar* b = templ->data.ptr; - if( cn == 1 || method < CV_TM_CCOEFF ) + if( cn == 1 || method < cv::TM_CCOEFF ) { for( k = 0; k < height; k++, a += a_step, b += b_step ) for( l = 0; l < width_n; l++ ) @@ -227,7 +227,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu const float* a = (const float*)(img->data.ptr + i*img->step) + j*cn; const float* b = (const float*)templ->data.ptr; - if( cn == 1 || method < CV_TM_CCOEFF ) + if( cn == 1 || method < cv::TM_CCOEFF ) { for( k = 0; k < height; k++, a += a_step, b += b_step ) for( l = 0; l < width_n; l++ ) @@ -257,12 +257,12 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu switch( method ) { - case CV_TM_CCORR: - case CV_TM_CCORR_NORMED: + case cv::TM_CCORR: + case cv::TM_CCORR_NORMED: value = ccorr.val[0]; break; - case CV_TM_SQDIFF: - case CV_TM_SQDIFF_NORMED: + case cv::TM_SQDIFF: + case cv::TM_SQDIFF_NORMED: value = (a_sum2.val[0] + b_sum2 - 2*ccorr.val[0]); break; default: @@ -276,7 +276,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu double denom; // calc denominator - if( method != CV_TM_CCOEFF_NORMED ) + if( method != cv::TM_CCOEFF_NORMED ) { denom = a_sum2.val[0] + a_sum2.val[1] + a_sum2.val[2]; } @@ -292,7 +292,7 @@ static void cvTsMatchTemplate( const CvMat* img, const CvMat* templ, CvMat* resu else if( fabs(value) < denom*1.125 ) value = value > 0 ? 1 : -1; else - value = method != CV_TM_SQDIFF_NORMED ? 0 : 1; + value = method != cv::TM_SQDIFF_NORMED ? 0 : 1; } ((float*)(result->data.ptr + result->step*i))[j] = (float)value; @@ -318,7 +318,7 @@ void CV_TemplMatchTest::prepare_to_validation( int /*test_case_idx*/ ) cvReleaseFileStorage( &fs ); }*/ - if( method >= CV_TM_CCOEFF ) + if( method >= cv::TM_CCOEFF ) { // avoid numerical stability problems in singular cases (when the results are near to 0) const double delta = 10.; @@ -415,7 +415,7 @@ TEST(Imgproc_MatchTemplate, bug_9597) { cv::Mat cvimg(cv::Size(61, 82), CV_8UC1, (void*)img, cv::Mat::AUTO_STEP); cv::Mat cvtmpl(cv::Size(17, 17), CV_8UC1, (void*)tmpl, cv::Mat::AUTO_STEP); cv::Mat result; - cv::matchTemplate(cvimg, cvtmpl, result, CV_TM_SQDIFF); + cv::matchTemplate(cvimg, cvtmpl, result, cv::TM_SQDIFF); double minValue; cv::minMaxLoc(result, &minValue, NULL, NULL, NULL); ASSERT_GE(minValue, 0); diff --git a/modules/imgproc/test/test_templmatchmask.cpp b/modules/imgproc/test/test_templmatchmask.cpp index cca110ae22..3c8ab665ae 100644 --- a/modules/imgproc/test/test_templmatchmask.cpp +++ b/modules/imgproc/test/test_templmatchmask.cpp @@ -6,9 +6,9 @@ namespace opencv_test { namespace { -CV_ENUM(MatchTemplType, CV_TM_CCORR, CV_TM_CCORR_NORMED, - CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, - CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED) +CV_ENUM(MatchTemplType, cv::TM_CCORR, cv::TM_CCORR_NORMED, + cv::TM_SQDIFF, cv::TM_SQDIFF_NORMED, + cv::TM_CCOEFF, cv::TM_CCOEFF_NORMED) class Imgproc_MatchTemplateWithMask : public TestWithParam> { @@ -76,7 +76,7 @@ void Imgproc_MatchTemplateWithMask::SetUp() TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplSQDIFF) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_SQDIFF, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_SQDIFF, mask_testtype_); // Naive implementation for one point Mat temp = img_roi_masked_ - templ_masked_; Scalar temp_s = sum(temp.mul(temp)); @@ -87,7 +87,7 @@ TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplSQDIFF) TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplSQDIFF_NORMED) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_SQDIFF_NORMED, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_SQDIFF_NORMED, mask_testtype_); // Naive implementation for one point Mat temp = img_roi_masked_ - templ_masked_; Scalar temp_s = sum(temp.mul(temp)); @@ -106,7 +106,7 @@ TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplSQDIFF_NORMED) TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCORR) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_CCORR, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_CCORR, mask_testtype_); // Naive implementation for one point Scalar temp_s = sum(templ_masked_.mul(img_roi_masked_)); double val = temp_s[0] + temp_s[1] + temp_s[2] + temp_s[3]; @@ -116,7 +116,7 @@ TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCORR) TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCORR_NORMED) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_CCORR_NORMED, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_CCORR_NORMED, mask_testtype_); // Naive implementation for one point Scalar temp_s = sum(templ_masked_.mul(img_roi_masked_)); double val = temp_s[0] + temp_s[1] + temp_s[2] + temp_s[3]; @@ -134,7 +134,7 @@ TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCORR_NORMED) TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCOEFF) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_CCOEFF, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_CCOEFF, mask_testtype_); // Naive implementation for one point Scalar temp_s = sum(mask_); for (int i = 0; i < 4; i++) @@ -157,7 +157,7 @@ TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCOEFF) TEST_P(Imgproc_MatchTemplateWithMask, CompareNaiveImplCCOEFF_NORMED) { - matchTemplate(img_testtype_, templ_testtype_, result_, CV_TM_CCOEFF_NORMED, mask_testtype_); + matchTemplate(img_testtype_, templ_testtype_, result_, cv::TM_CCOEFF_NORMED, mask_testtype_); // Naive implementation for one point Scalar temp_s = sum(mask_); for (int i = 0; i < 4; i++) @@ -265,14 +265,14 @@ INSTANTIATE_TEST_CASE_P(SingleChannelMask, Imgproc_MatchTemplateWithMask2, Combine( Values(CV_32FC1, CV_32FC3, CV_8UC1, CV_8UC3), Values(CV_32FC1, CV_8UC1), - Values(CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, - CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED))); + Values(cv::TM_SQDIFF, cv::TM_SQDIFF_NORMED, cv::TM_CCORR, cv::TM_CCORR_NORMED, + cv::TM_CCOEFF, cv::TM_CCOEFF_NORMED))); INSTANTIATE_TEST_CASE_P(MultiChannelMask, Imgproc_MatchTemplateWithMask2, Combine( Values(CV_32FC3, CV_8UC3), Values(CV_32FC3, CV_8UC3), - Values(CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, - CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED))); + Values(cv::TM_SQDIFF, cv::TM_SQDIFF_NORMED, cv::TM_CCORR, cv::TM_CCORR_NORMED, + cv::TM_CCOEFF, cv::TM_CCOEFF_NORMED))); }} // namespace diff --git a/modules/imgproc/test/test_thresh.cpp b/modules/imgproc/test/test_thresh.cpp index 510560fd05..a9f323780c 100644 --- a/modules/imgproc/test/test_thresh.cpp +++ b/modules/imgproc/test/test_thresh.cpp @@ -43,451 +43,6 @@ namespace opencv_test { namespace { -class CV_ThreshTest : public cvtest::ArrayTest -{ -public: - CV_ThreshTest(int test_type = 0); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - void run_func(); - void prepare_to_validation( int ); - - int thresh_type; - double thresh_val; - double max_val; - int extra_type; -}; - - -CV_ThreshTest::CV_ThreshTest(int test_type) -{ - CV_Assert( (test_type & CV_THRESH_MASK) == 0 ); - test_array[INPUT].push_back(NULL); - test_array[OUTPUT].push_back(NULL); - test_array[REF_OUTPUT].push_back(NULL); - optional_mask = false; - element_wise_relative_error = true; - extra_type = test_type; - // Reduce number of test with automated thresholding - if (extra_type != 0) - test_case_count = 250; -} - - -void CV_ThreshTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - int depth = cvtest::randInt(rng) % 5, cn = cvtest::randInt(rng) % 4 + 1; - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16S : depth == 2 ? CV_16U : depth == 3 ? CV_32F : CV_64F; - - if ( extra_type == CV_THRESH_OTSU ) - { - depth = cvtest::randInt(rng) % 2 == 0 ? CV_8U : CV_16U; - cn = 1; - } - - types[INPUT][0] = types[OUTPUT][0] = types[REF_OUTPUT][0] = CV_MAKETYPE(depth,cn); - thresh_type = cvtest::randInt(rng) % 5; - - if( depth == CV_8U ) - { - thresh_val = (cvtest::randReal(rng)*350. - 50.); - max_val = (cvtest::randReal(rng)*350. - 50.); - if( cvtest::randInt(rng)%4 == 0 ) - max_val = 255.f; - } - else if( depth == CV_16S ) - { - double min_val = SHRT_MIN-100.f; - max_val = SHRT_MAX+100.f; - thresh_val = (cvtest::randReal(rng)*(max_val - min_val) + min_val); - max_val = (cvtest::randReal(rng)*(max_val - min_val) + min_val); - if( cvtest::randInt(rng)%4 == 0 ) - max_val = (double)SHRT_MAX; - } - else if( depth == CV_16U ) - { - double min_val = -100.f; - max_val = USHRT_MAX+100.f; - thresh_val = (cvtest::randReal(rng)*(max_val - min_val) + min_val); - max_val = (cvtest::randReal(rng)*(max_val - min_val) + min_val); - if( cvtest::randInt(rng)%4 == 0 ) - max_val = (double)USHRT_MAX; - } - else - { - thresh_val = (cvtest::randReal(rng)*1000. - 500.); - max_val = (cvtest::randReal(rng)*1000. - 500.); - } -} - - -double CV_ThreshTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return FLT_EPSILON*10; -} - - -void CV_ThreshTest::run_func() -{ - cvThreshold( test_array[INPUT][0], test_array[OUTPUT][0], - thresh_val, max_val, thresh_type | extra_type); -} - - -static double compute_otsu_thresh(const Mat& _src) -{ - int depth = _src.depth(); - int width = _src.cols, height = _src.rows; - const int N = 65536; - std::vector h(N, 0); - int i, j; - double mu = 0, scale = 1./(width*height); - for(i = 0; i < height; ++i) - { - for(j = 0; j < width; ++j) - { - const int val = depth == CV_16UC1 ? (int)_src.at(i, j) : (int)_src.at(i,j); - h[val]++; - } - } - for( i = 0; i < N; i++ ) - { - mu += i*(double)h[i]; - } - - mu *= scale; - double mu1 = 0, q1 = 0; - double max_sigma = 0, max_val = 0; - - for( i = 0; i < N; i++ ) - { - double p_i, q2, mu2, sigma; - - p_i = h[i]*scale; - mu1 *= q1; - q1 += p_i; - q2 = 1. - q1; - - if( std::min(q1,q2) < FLT_EPSILON || std::max(q1,q2) > 1. - FLT_EPSILON ) - continue; - - mu1 = (mu1 + i*p_i)/q1; - mu2 = (mu - q1*mu1)/q2; - sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2); - if( sigma > max_sigma ) - { - max_sigma = sigma; - max_val = i; - } - } - - return max_val; -} - -static void test_threshold( const Mat& _src, Mat& _dst, - double thresh, double maxval, int thresh_type, int extra_type ) -{ - int i, j; - int depth = _src.depth(), cn = _src.channels(); - int width_n = _src.cols*cn, height = _src.rows; - int ithresh = cvFloor(thresh); - int imaxval, ithresh2; - if (extra_type == CV_THRESH_OTSU) - { - thresh = compute_otsu_thresh(_src); - ithresh = cvFloor(thresh); - } - - if( depth == CV_8U ) - { - ithresh2 = saturate_cast(ithresh); - imaxval = saturate_cast(maxval); - } - else if( depth == CV_16S ) - { - ithresh2 = saturate_cast(ithresh); - imaxval = saturate_cast(maxval); - } - else if( depth == CV_16U ) - { - ithresh2 = saturate_cast(ithresh); - imaxval = saturate_cast(maxval); - } - else - { - ithresh2 = cvRound(ithresh); - imaxval = cvRound(maxval); - } - - CV_Assert( depth == CV_8U || depth == CV_16S || depth == CV_16U || depth == CV_32F || depth == CV_64F ); - - switch( thresh_type ) - { - case CV_THRESH_BINARY: - for( i = 0; i < height; i++ ) - { - if( depth == CV_8U ) - { - const uchar* src = _src.ptr(i); - uchar* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (uchar)(src[j] > ithresh ? imaxval : 0); - } - else if( depth == CV_16S ) - { - const short* src = _src.ptr(i); - short* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (short)(src[j] > ithresh ? imaxval : 0); - } - else if( depth == CV_16U ) - { - const ushort* src = _src.ptr(i); - ushort* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (ushort)(src[j] > ithresh ? imaxval : 0); - } - else if( depth == CV_32F ) - { - const float* src = _src.ptr(i); - float* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (float)(src[j] > thresh ? maxval : 0.f); - } - else - { - const double* src = _src.ptr(i); - double* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = src[j] > thresh ? maxval : 0.0; - } - } - break; - case CV_THRESH_BINARY_INV: - for( i = 0; i < height; i++ ) - { - if( depth == CV_8U ) - { - const uchar* src = _src.ptr(i); - uchar* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (uchar)(src[j] > ithresh ? 0 : imaxval); - } - else if( depth == CV_16S ) - { - const short* src = _src.ptr(i); - short* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (short)(src[j] > ithresh ? 0 : imaxval); - } - else if( depth == CV_16U ) - { - const ushort* src = _src.ptr(i); - ushort* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (ushort)(src[j] > ithresh ? 0 : imaxval); - } - else if( depth == CV_32F ) - { - const float* src = _src.ptr(i); - float* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = (float)(src[j] > thresh ? 0.f : maxval); - } - else - { - const double* src = _src.ptr(i); - double* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - dst[j] = src[j] > thresh ? 0.0 : maxval; - } - } - break; - case CV_THRESH_TRUNC: - for( i = 0; i < height; i++ ) - { - if( depth == CV_8U ) - { - const uchar* src = _src.ptr(i); - uchar* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? ithresh2 : s); - } - } - else if( depth == CV_16S ) - { - const short* src = _src.ptr(i); - short* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (short)(s > ithresh ? ithresh2 : s); - } - } - else if( depth == CV_16U ) - { - const ushort* src = _src.ptr(i); - ushort* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (ushort)(s > ithresh ? ithresh2 : s); - } - } - else if( depth == CV_32F ) - { - const float* src = _src.ptr(i); - float* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - float s = src[j]; - dst[j] = (float)(s > thresh ? thresh : s); - } - } - else - { - const double* src = _src.ptr(i); - double* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - double s = src[j]; - dst[j] = s > thresh ? thresh : s; - } - } - } - break; - case CV_THRESH_TOZERO: - for( i = 0; i < height; i++ ) - { - if( depth == CV_8U ) - { - const uchar* src = _src.ptr(i); - uchar* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? s : 0); - } - } - else if( depth == CV_16S ) - { - const short* src = _src.ptr(i); - short* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (short)(s > ithresh ? s : 0); - } - } - else if( depth == CV_16U ) - { - const ushort* src = _src.ptr(i); - ushort* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (ushort)(s > ithresh ? s : 0); - } - } - else if( depth == CV_32F ) - { - const float* src = _src.ptr(i); - float* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - float s = src[j]; - dst[j] = s > thresh ? s : 0.f; - } - } - else - { - const double* src = _src.ptr(i); - double* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - double s = src[j]; - dst[j] = s > thresh ? s : 0.0; - } - } - } - break; - case CV_THRESH_TOZERO_INV: - for( i = 0; i < height; i++ ) - { - if( depth == CV_8U ) - { - const uchar* src = _src.ptr(i); - uchar* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (uchar)(s > ithresh ? 0 : s); - } - } - else if( depth == CV_16S ) - { - const short* src = _src.ptr(i); - short* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (short)(s > ithresh ? 0 : s); - } - } - else if( depth == CV_16U ) - { - const ushort* src = _src.ptr(i); - ushort* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - int s = src[j]; - dst[j] = (ushort)(s > ithresh ? 0 : s); - } - } - else if (depth == CV_32F) - { - const float* src = _src.ptr(i); - float* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - float s = src[j]; - dst[j] = s > thresh ? 0.f : s; - } - } - else - { - const double* src = _src.ptr(i); - double* dst = _dst.ptr(i); - for( j = 0; j < width_n; j++ ) - { - double s = src[j]; - dst[j] = s > thresh ? 0.0 : s; - } - } - } - break; - default: - CV_Assert(0); - } -} - - -void CV_ThreshTest::prepare_to_validation( int /*test_case_idx*/ ) -{ - test_threshold( test_mat[INPUT][0], test_mat[REF_OUTPUT][0], - thresh_val, max_val, thresh_type, extra_type ); -} - -TEST(Imgproc_Threshold, accuracy) { CV_ThreshTest test; test.safe_run(); } -TEST(Imgproc_Threshold, accuracyOtsu) { CV_ThreshTest test(CV_THRESH_OTSU); test.safe_run(); } - BIGDATA_TEST(Imgproc_Threshold, huge) { Mat m(65000, 40000, CV_8U); diff --git a/modules/imgproc/test/test_watershed.cpp b/modules/imgproc/test/test_watershed.cpp index 90307ca30c..0fb6521809 100644 --- a/modules/imgproc/test/test_watershed.cpp +++ b/modules/imgproc/test/test_watershed.cpp @@ -41,90 +41,3 @@ //M*/ #include "test_precomp.hpp" - -#if 0 -namespace opencv_test { namespace { - -class CV_WatershedTest : public cvtest::BaseTest -{ -public: - CV_WatershedTest(); - ~CV_WatershedTest(); -protected: - void run(int); -}; - -CV_WatershedTest::CV_WatershedTest() {} -CV_WatershedTest::~CV_WatershedTest() {} - -void CV_WatershedTest::run( int /* start_from */) -{ - string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png"; - Mat exp = imread(exp_path, 0); - Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.png"); - FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ); - - if (orig.empty() || !fs.isOpened()) - { - ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); - return; - } - - CvSeq* cnts = (CvSeq*)fs["contours"].readObj(); - - Mat markers(orig.size(), CV_32SC1); - markers = Scalar(0); - IplImage iplmrks = cvIplImage(markers); - - vector colors(1); - for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i ) - { - cvDrawContours( &iplmrks, cnts, cvScalar(Scalar::all(i + 1)), cvScalar(Scalar::all(i + 1)), -1, CV_FILLED); - Point* p = (Point*)cvGetSeqElem(cnts, 0); - - //expected image was added with 1 in order to save to png - //so now we subtract 1 to get real color - if(!exp.empty()) - colors.push_back(exp.ptr(p->y)[p->x] - 1); - } - fs.release(); - const int compNum = (int)(colors.size() - 1); - - watershed(orig, markers); - - for(int j = 0; j < markers.rows; ++j) - { - int* line = markers.ptr(j); - for(int i = 0; i < markers.cols; ++i) - { - int& pixel = line[i]; - - if (pixel == -1) // border - continue; - - if (pixel <= 0 || pixel > compNum) - continue; // bad result, doing nothing and going to get error latter; - - // repaint in saved color to compare with expected; - if(!exp.empty()) - pixel = colors[pixel]; - } - } - - Mat markers8U; - markers.convertTo(markers8U, CV_8U, 1, 1); - - if( exp.empty() || orig.size() != exp.size() ) - { - imwrite(exp_path, markers8U); - exp = markers8U; - } - - ASSERT_EQ(0, cvtest::norm(markers8U, exp, NORM_INF)); -} - -TEST(Imgproc_Watershed, regression) { CV_WatershedTest test; test.safe_run(); } - -}} // namespace - -#endif diff --git a/modules/photo/src/inpaint.cpp b/modules/photo/src/inpaint.cpp index f3fcb47094..b436168212 100644 --- a/modules/photo/src/inpaint.cpp +++ b/modules/photo/src/inpaint.cpp @@ -735,17 +735,13 @@ icvNSInpaintFMM(const CvMat *f, CvMat *t, CvMat *out, int range, CvPriorityQueue }\ } -namespace cv { -template<> struct DefaultDeleter{ void operator ()(IplConvKernel* obj) const { cvReleaseStructuringElement(&obj); } }; -} - static void icvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_img, double inpaintRange, int flags ) { cv::Ptr mask, band, f, t, out; cv::Ptr Heap, Out; - cv::Ptr el_cross, el_range; + cv::Mat el_range, el_cross; // structuring elements for dilate CvMat input_hdr, mask_hdr, output_hdr; CvMat* input_img, *inpaint_mask, *output_img; @@ -780,7 +776,7 @@ icvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_ t.reset(cvCreateMat(erows, ecols, CV_32FC1)); band.reset(cvCreateMat(erows, ecols, CV_8UC1)); mask.reset(cvCreateMat(erows, ecols, CV_8UC1)); - el_cross.reset(cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_CROSS,NULL)); + el_cross = cv::getStructuringElement(cv::MORPH_CROSS, cv::Size(3, 3), cv::Point(1, 1)); cvCopy( input_img, output_img ); cvSet(mask,cvScalar(KNOWN,0,0,0)); @@ -788,7 +784,7 @@ icvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_ SET_BORDER1_C1(mask,uchar,0); cvSet(f,cvScalar(KNOWN,0,0,0)); cvSet(t,cvScalar(1.0e6f,0,0,0)); - cvDilate(mask,band,el_cross,1); // image with narrow band + cv::dilate(cv::cvarrToMat(mask), cv::cvarrToMat(band), el_cross, cv::Point(1, 1)); Heap=cv::makePtr(); if (!Heap->Init(band)) return; @@ -803,9 +799,8 @@ icvInpaint( const CvArr* _input_img, const CvArr* _inpaint_mask, CvArr* _output_ if( flags == cv::INPAINT_TELEA ) { out.reset(cvCreateMat(erows, ecols, CV_8UC1)); - el_range.reset(cvCreateStructuringElementEx(2*range+1,2*range+1, - range,range,CV_SHAPE_RECT,NULL)); - cvDilate(mask,out,el_range,1); + el_range = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2 * range + 1, 2 * range + 1)); + cv::dilate(cv::cvarrToMat(mask), cv::cvarrToMat(out), el_range); cvSub(out,mask,out,NULL); Out=cv::makePtr(); if (!Out->Init(out)) diff --git a/modules/ts/src/ocl_test.cpp b/modules/ts/src/ocl_test.cpp index 6d5ff26d7f..07fb1cdc4a 100644 --- a/modules/ts/src/ocl_test.cpp +++ b/modules/ts/src/ocl_test.cpp @@ -81,7 +81,7 @@ double TestUtils::checkNorm2(InputArray m1, InputArray m2, InputArray mask) double TestUtils::checkSimilarity(InputArray m1, InputArray m2) { Mat diff; - matchTemplate(m1.getMat(), m2.getMat(), diff, CV_TM_CCORR_NORMED); + matchTemplate(m1.getMat(), m2.getMat(), diff, cv::TM_CCORR_NORMED); return std::abs(diff.at(0, 0) - 1.f); } diff --git a/modules/ts/src/ts_func.cpp b/modules/ts/src/ts_func.cpp index d64f52927b..cd02766148 100644 --- a/modules/ts/src/ts_func.cpp +++ b/modules/ts/src/ts_func.cpp @@ -3061,7 +3061,7 @@ void threshold( const Mat& _src, Mat& _dst, switch( thresh_type ) { - case CV_THRESH_BINARY: + case cv::THRESH_BINARY: for( i = 0; i < height; i++ ) { if( depth == CV_8U ) @@ -3087,7 +3087,7 @@ void threshold( const Mat& _src, Mat& _dst, } } break; - case CV_THRESH_BINARY_INV: + case cv::THRESH_BINARY_INV: for( i = 0; i < height; i++ ) { if( depth == CV_8U ) @@ -3113,7 +3113,7 @@ void threshold( const Mat& _src, Mat& _dst, } } break; - case CV_THRESH_TRUNC: + case cv::THRESH_TRUNC: for( i = 0; i < height; i++ ) { if( depth == CV_8U ) @@ -3148,7 +3148,7 @@ void threshold( const Mat& _src, Mat& _dst, } } break; - case CV_THRESH_TOZERO: + case cv::THRESH_TOZERO: for( i = 0; i < height; i++ ) { if( depth == CV_8U ) @@ -3183,7 +3183,7 @@ void threshold( const Mat& _src, Mat& _dst, } } break; - case CV_THRESH_TOZERO_INV: + case cv::THRESH_TOZERO_INV: for( i = 0; i < height; i++ ) { if( depth == CV_8U ) diff --git a/modules/video/test/test_accum.cpp b/modules/video/test/test_accum.cpp index 9941f20359..e69de29bb2 100644 --- a/modules/video/test/test_accum.cpp +++ b/modules/video/test/test_accum.cpp @@ -1,249 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "test_precomp.hpp" -#include "opencv2/imgproc/imgproc_c.h" - -namespace opencv_test { namespace { - -class CV_AccumBaseTest : public cvtest::ArrayTest -{ -public: - CV_AccumBaseTest(); - -protected: - void get_test_array_types_and_sizes( int test_case_idx, vector >& sizes, vector >& types ); - double get_success_error_level( int test_case_idx, int i, int j ); - double alpha; -}; - - -CV_AccumBaseTest::CV_AccumBaseTest() -{ - test_array[INPUT].push_back(NULL); - test_array[INPUT_OUTPUT].push_back(NULL); - test_array[REF_INPUT_OUTPUT].push_back(NULL); - test_array[MASK].push_back(NULL); - optional_mask = true; - element_wise_relative_error = false; -} // ctor - - -void CV_AccumBaseTest::get_test_array_types_and_sizes( int test_case_idx, - vector >& sizes, vector >& types ) -{ - RNG& rng = ts->get_rng(); - int depth = cvtest::randInt(rng) % 4, cn = cvtest::randInt(rng) & 1 ? 3 : 1; - int accdepth = (int)(cvtest::randInt(rng) % 2 + 1); - int i, input_count = (int)test_array[INPUT].size(); - cvtest::ArrayTest::get_test_array_types_and_sizes( test_case_idx, sizes, types ); - depth = depth == 0 ? CV_8U : depth == 1 ? CV_16U : depth == 2 ? CV_32F : CV_64F; - accdepth = accdepth == 1 ? CV_32F : CV_64F; - accdepth = MAX(accdepth, depth); - - for( i = 0; i < input_count; i++ ) - types[INPUT][i] = CV_MAKETYPE(depth,cn); - - types[INPUT_OUTPUT][0] = types[REF_INPUT_OUTPUT][0] = CV_MAKETYPE(accdepth,cn); - - alpha = cvtest::randReal(rng); -} - - -double CV_AccumBaseTest::get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ) -{ - return test_mat[INPUT_OUTPUT][0].depth() < CV_64F || - test_mat[INPUT][0].depth() == CV_32F ? FLT_EPSILON*100 : DBL_EPSILON*1000; -} - - -/// acc -class CV_AccTest : public CV_AccumBaseTest -{ -public: - CV_AccTest() { } -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -void CV_AccTest::run_func(void) -{ - cvAcc( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_AccTest::prepare_to_validation( int ) -{ - const Mat& src = test_mat[INPUT][0]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - const Mat& mask = test_array[MASK][0] ? test_mat[MASK][0] : Mat(); - Mat temp; - cvtest::add( src, 1, dst, 1, cvScalarAll(0.), temp, dst.type() ); - cvtest::copy( temp, dst, mask ); -} - - -/// square acc -class CV_SquareAccTest : public CV_AccumBaseTest -{ -public: - CV_SquareAccTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_SquareAccTest::CV_SquareAccTest() -{ -} - - -void CV_SquareAccTest::run_func() -{ - cvSquareAcc( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_SquareAccTest::prepare_to_validation( int ) -{ - const Mat& src = test_mat[INPUT][0]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - const Mat& mask = test_array[MASK][0] ? test_mat[MASK][0] : Mat(); - Mat temp; - - cvtest::convert( src, temp, dst.type() ); - cvtest::multiply( temp, temp, temp, 1 ); - cvtest::add( temp, 1, dst, 1, cvScalarAll(0.), temp, dst.depth() ); - cvtest::copy( temp, dst, mask ); -} - - -/// multiply acc -class CV_MultiplyAccTest : public CV_AccumBaseTest -{ -public: - CV_MultiplyAccTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_MultiplyAccTest::CV_MultiplyAccTest() -{ - test_array[INPUT].push_back(NULL); -} - - -void CV_MultiplyAccTest::run_func() -{ - cvMultiplyAcc( test_array[INPUT][0], test_array[INPUT][1], - test_array[INPUT_OUTPUT][0], test_array[MASK][0] ); -} - - -void CV_MultiplyAccTest::prepare_to_validation( int ) -{ - const Mat& src1 = test_mat[INPUT][0]; - const Mat& src2 = test_mat[INPUT][1]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - const Mat& mask = test_array[MASK][0] ? test_mat[MASK][0] : Mat(); - Mat temp1, temp2; - - cvtest::convert( src1, temp1, dst.type() ); - cvtest::convert( src2, temp2, dst.type() ); - - cvtest::multiply( temp1, temp2, temp1, 1 ); - cvtest::add( temp1, 1, dst, 1, cvScalarAll(0.), temp1, dst.depth() ); - cvtest::copy( temp1, dst, mask ); -} - - -/// running average -class CV_RunningAvgTest : public CV_AccumBaseTest -{ -public: - CV_RunningAvgTest(); -protected: - void run_func(); - void prepare_to_validation( int ); -}; - - -CV_RunningAvgTest::CV_RunningAvgTest() -{ -} - - -void CV_RunningAvgTest::run_func() -{ - cvRunningAvg( test_array[INPUT][0], test_array[INPUT_OUTPUT][0], - alpha, test_array[MASK][0] ); -} - - -void CV_RunningAvgTest::prepare_to_validation( int ) -{ - const Mat& src = test_mat[INPUT][0]; - Mat& dst = test_mat[REF_INPUT_OUTPUT][0]; - Mat temp; - const Mat& mask = test_array[MASK][0] ? test_mat[MASK][0] : Mat(); - double a[1], b[1]; - int accdepth = test_mat[INPUT_OUTPUT][0].depth(); - CvMat A = cvMat(1,1,accdepth,a), B = cvMat(1,1,accdepth,b); - cvSetReal1D( &A, 0, alpha); - cvSetReal1D( &B, 0, 1 - cvGetReal1D(&A, 0)); - - cvtest::convert( src, temp, dst.type() ); - cvtest::add( src, cvGetReal1D(&A, 0), dst, cvGetReal1D(&B, 0), cvScalarAll(0.), temp, temp.depth() ); - cvtest::copy( temp, dst, mask ); -} - - -TEST(Video_Acc, accuracy) { CV_AccTest test; test.safe_run(); } -TEST(Video_AccSquared, accuracy) { CV_SquareAccTest test; test.safe_run(); } -TEST(Video_AccProduct, accuracy) { CV_MultiplyAccTest test; test.safe_run(); } -TEST(Video_RunningAvg, accuracy) { CV_RunningAvgTest test; test.safe_run(); } - -}} // namespace diff --git a/modules/video/test/test_camshift.cpp b/modules/video/test/test_camshift.cpp index 24d2ec6c24..57e5bf4c59 100644 --- a/modules/video/test/test_camshift.cpp +++ b/modules/video/test/test_camshift.cpp @@ -274,7 +274,7 @@ int CV_CamShiftTest::validate_test_results( int /*test_case_idx*/ ) cvIsNaN(box.center.y) || cvIsInf(box.center.y) || cvIsNaN(box.angle) || cvIsInf(box.angle) || box.angle < -180 || box.angle > 180 ) { - ts->printf( cvtest::TS::LOG, "Invalid CvBox2D or CvConnectedComp was returned by cvCamShift\n" ); + ts->printf( cvtest::TS::LOG, "Invalid RotatedRect was returned by CamShift\n" ); code = cvtest::TS::FAIL_INVALID_OUTPUT; goto _exit_; } @@ -317,19 +317,6 @@ _exit_: if( code < 0 ) { -#if 0 //defined _DEBUG && defined _WIN32 - IplImage* dst = cvCreateImage( img_size, 8, 3 ); - cvNamedWindow( "test", 1 ); - cvCmpS( img, 0, img, CV_CMP_GT ); - cvCvtColor( img, dst, CV_GRAY2BGR ); - cvRectangle( dst, cvPoint(init_rect.x, init_rect.y), - cvPoint(init_rect.x + init_rect.width, init_rect.y + init_rect.height), - CV_RGB(255,0,0), 3, 8, 0 ); - cvEllipseBox( dst, box, CV_RGB(0,255,0), 3, 8, 0 ); - cvShowImage( "test", dst ); - cvReleaseImage( &dst ); - cvWaitKey(); -#endif ts->set_failed_test_info( code ); } return code; @@ -428,7 +415,7 @@ int CV_MeanShiftTest::validate_test_results( int /*test_case_idx*/ ) rect.y + rect.height > box0.center.y + delta ) { ts->printf( cvtest::TS::LOG, - "Incorrect CvConnectedComp ((%d,%d,%d,%d) is not within (%.1f,%.1f,%.1f,%.1f))\n", + "Incorrect ConnectedComp ((%d,%d,%d,%d) is not within (%.1f,%.1f,%.1f,%.1f))\n", rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, box0.center.x - delta, box0.center.y - delta, box0.center.x + delta, box0.center.y + delta ); code = cvtest::TS::FAIL_BAD_ACCURACY; @@ -438,21 +425,6 @@ _exit_: if( code < 0 ) { -#if 0// defined _DEBUG && defined _WIN32 - IplImage* dst = cvCreateImage( img_size, 8, 3 ); - cvNamedWindow( "test", 1 ); - cvCmpS( img, 0, img, CV_CMP_GT ); - cvCvtColor( img, dst, CV_GRAY2BGR ); - cvRectangle( dst, cvPoint(init_rect.x, init_rect.y), - cvPoint(init_rect.x + init_rect.width, init_rect.y + init_rect.height), - CV_RGB(255,0,0), 3, 8, 0 ); - cvRectangle( dst, cvPoint(comp.rect.x, comp.rect.y), - cvPoint(comp.rect.x + comp.rect.width, comp.rect.y + comp.rect.height), - CV_RGB(0,255,0), 3, 8, 0 ); - cvShowImage( "test", dst ); - cvReleaseImage( &dst ); - cvWaitKey(); -#endif ts->set_failed_test_info( code ); } return code; diff --git a/modules/videoio/src/cap_avfoundation.mm b/modules/videoio/src/cap_avfoundation.mm index 17c5879014..8959c124fa 100644 --- a/modules/videoio/src/cap_avfoundation.mm +++ b/modules/videoio/src/cap_avfoundation.mm @@ -750,7 +750,7 @@ fromConnection:(AVCaptureConnection *)connection{ bgr_image->imageData = bgr_imagedata; bgr_image->imageSize = (int)currSize; - cvCvtColor(image, bgr_image, CV_BGRA2BGR); + cv::cvtColor(cv::cvarrToMat(image), cv::cvarrToMat(bgr_image), cv::COLOR_BGRA2BGR); // image taken from the buffer is incorrected rotated. I'm using cvTranspose + cvFlip. // There should be an option in iOS API to rotate the buffer output orientation. @@ -1000,11 +1000,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 4; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_BGRA2BGR; + cvtCode = cv::COLOR_BGRA2BGR; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_BGRA2RGB; + cvtCode = cv::COLOR_BGRA2RGB; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_BGRA2GRAY; + cvtCode = cv::COLOR_BGRA2GRAY; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -1016,11 +1016,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 3; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_RGB2BGR; + cvtCode = cv::COLOR_RGB2BGR; } else if (mMode == CV_CAP_MODE_RGB) { cvtCode = 0; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_RGB2GRAY; + cvtCode = cv::COLOR_RGB2GRAY; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -1032,11 +1032,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 2; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_YUV2BGR_UYVY; + cvtCode = cv::COLOR_YUV2BGR_UYVY; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_YUV2RGB_UYVY; + cvtCode = cv::COLOR_YUV2RGB_UYVY; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_YUV2GRAY_UYVY; + cvtCode = cv::COLOR_YUV2GRAY_UYVY; } else if (mMode == CV_CAP_MODE_YUYV) { cvtCode = -1; // Copy } else { @@ -1052,11 +1052,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 1; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_YUV2BGR_YV12; + cvtCode = cv::COLOR_YUV2BGR_YV12; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_YUV2RGB_YV12; + cvtCode = cv::COLOR_YUV2RGB_YV12; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_YUV2GRAY_420; + cvtCode = cv::COLOR_YUV2GRAY_420; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -1088,7 +1088,7 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { if (cvtCode == -1) { cv::cvarrToMat(mDeviceImage).copyTo(cv::cvarrToMat(mOutImage)); } else { - cvCvtColor(mDeviceImage, mOutImage, cvtCode); + cv::cvtColor(cv::cvarrToMat(mDeviceImage), cv::cvarrToMat(mOutImage), cvtCode); } CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); @@ -1373,10 +1373,10 @@ bool CvVideoWriter_AVFoundation::writeFrame(const IplImage* iplimage) { if (movieColor) { //assert(iplimage->nChannels == 3); - cvCvtColor(iplimage, argbimage, CV_BGR2BGRA); + cv::cvtColor(cv::cvarrToMat(iplimage), cv::cvarrToMat(argbimage), cv::COLOR_BGR2BGRA); }else{ //assert(iplimage->nChannels == 1); - cvCvtColor(iplimage, argbimage, CV_GRAY2BGRA); + cv::cvtColor(cv::cvarrToMat(iplimage), cv::cvarrToMat(argbimage), cv::COLOR_GRAY2BGRA); } //IplImage -> CGImage conversion CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); diff --git a/modules/videoio/src/cap_avfoundation_mac.mm b/modules/videoio/src/cap_avfoundation_mac.mm index f33574104f..a41fad2cbe 100644 --- a/modules/videoio/src/cap_avfoundation_mac.mm +++ b/modules/videoio/src/cap_avfoundation_mac.mm @@ -687,7 +687,7 @@ didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer mDeviceImage->imageData = reinterpret_cast(baseaddress); mDeviceImage->imageSize = int(rowBytes*height); - cvCvtColor(mDeviceImage, mOutImage, CV_BGRA2BGR); + cvtColor(cv::cvarrToMat(mDeviceImage), cv::cvarrToMat(mOutImage), cv::COLOR_BGRA2BGR); } else if ( pixelFormat == kCVPixelFormatType_422YpCbCr8 ) { if ( currSize != width*3*height ) { currSize = width*3*height; @@ -706,7 +706,7 @@ didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer mDeviceImage->imageData = reinterpret_cast(baseaddress); mDeviceImage->imageSize = int(rowBytes*height); - cvCvtColor(mDeviceImage, mOutImage, CV_YUV2BGR_UYVY); + cvtColor(cv::cvarrToMat(mDeviceImage), cv::cvarrToMat(mOutImage), cv::COLOR_YUV2BGR_UYVY); } else { fprintf(stderr, "OpenCV: unknown pixel format 0x%08X\n", pixelFormat); CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); @@ -817,7 +817,7 @@ bool CvCaptureFile::setupReadingAt(CMTime position) { // Capture in a pixel format that can be converted efficiently to the output mode. OSType pixelFormat; if (mMode == CV_CAP_MODE_BGR || mMode == CV_CAP_MODE_RGB) { - // For CV_CAP_MODE_BGR, read frames as BGRA (AV Foundation's YUV->RGB conversion is slightly faster than OpenCV's CV_YUV2BGR_YV12) + // For CV_CAP_MODE_BGR, read frames as BGRA (AV Foundation's YUV->RGB conversion is slightly faster than OpenCV's cv::COLOR_YUV2BGR_YV12) // kCVPixelFormatType_32ABGR is reportedly faster on OS X, but OpenCV doesn't have a CV_ABGR2BGR conversion. // kCVPixelFormatType_24RGB is significantly slower than kCVPixelFormatType_32BGRA. pixelFormat = kCVPixelFormatType_32BGRA; @@ -962,11 +962,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 4; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_BGRA2BGR; + cvtCode = cv::COLOR_BGRA2BGR; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_BGRA2RGB; + cvtCode = cv::COLOR_BGRA2RGB; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_BGRA2GRAY; + cvtCode = cv::COLOR_BGRA2GRAY; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -978,11 +978,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 3; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_RGB2BGR; + cvtCode = cv::COLOR_RGB2BGR; } else if (mMode == CV_CAP_MODE_RGB) { cvtCode = 0; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_RGB2GRAY; + cvtCode = cv::COLOR_RGB2GRAY; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -994,11 +994,11 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { deviceChannels = 2; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_YUV2BGR_UYVY; + cvtCode = cv::COLOR_YUV2BGR_UYVY; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_YUV2RGB_UYVY; + cvtCode = cv::COLOR_YUV2RGB_UYVY; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_YUV2GRAY_UYVY; + cvtCode = cv::COLOR_YUV2GRAY_UYVY; } else if (mMode == CV_CAP_MODE_YUYV) { cvtCode = -1; // Copy } else { @@ -1010,17 +1010,17 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { } } else if ( pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || // 420v pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange ) { // 420f - // cvCvtColor(CV_YUV2GRAY_420) is expecting a single buffer with both the Y plane and the CrCb planes. - // So, lie about the height of the buffer. cvCvtColor(CV_YUV2GRAY_420) will only read the first 2/3 of it. + // cvtColor(cv::COLOR_YUV2GRAY_420) is expecting a single buffer with both the Y plane and the CrCb planes. + // So, lie about the height of the buffer. cvtColor(cv::COLOR_YUV2GRAY_420) will only read the first 2/3 of it. height = height * 3 / 2; deviceChannels = 1; if (mMode == CV_CAP_MODE_BGR) { - cvtCode = CV_YUV2BGR_YV12; + cvtCode = cv::COLOR_YUV2BGR_YV12; } else if (mMode == CV_CAP_MODE_RGB) { - cvtCode = CV_YUV2RGB_YV12; + cvtCode = cv::COLOR_YUV2RGB_YV12; } else if (mMode == CV_CAP_MODE_GRAY) { - cvtCode = CV_YUV2GRAY_420; + cvtCode = cv::COLOR_YUV2GRAY_420; } else { CVPixelBufferUnlockBaseAddress(mGrabbedPixels, 0); CVBufferRelease(mGrabbedPixels); @@ -1053,7 +1053,7 @@ IplImage* CvCaptureFile::retrieveFramePixelBuffer() { // Copy. cv::cvarrToMat(mDeviceImage).copyTo(cv::cvarrToMat(mOutImage)); } else { - cvCvtColor(mDeviceImage, mOutImage, cvtCode); + cvtColor(cv::cvarrToMat(mDeviceImage), cv::cvarrToMat(mOutImage), cvtCode); } @@ -1333,10 +1333,10 @@ bool CvVideoWriter_AVFoundation::writeFrame(const IplImage* iplimage) { if (movieColor) { //assert(iplimage->nChannels == 3); - cvCvtColor(iplimage, argbimage, CV_BGR2BGRA); + cvtColor(cv::cvarrToMat(iplimage), cv::cvarrToMat(argbimage), cv::COLOR_BGR2BGRA); }else{ //assert(iplimage->nChannels == 1); - cvCvtColor(iplimage, argbimage, CV_GRAY2BGRA); + cvtColor(cv::cvarrToMat(iplimage), cv::cvarrToMat(argbimage), cv::COLOR_GRAY2BGRA); } //IplImage -> CGImage conversion CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); diff --git a/modules/videoio/src/cap_openni2.cpp b/modules/videoio/src/cap_openni2.cpp index bc17b01a48..d4b3ae4153 100644 --- a/modules/videoio/src/cap_openni2.cpp +++ b/modules/videoio/src/cap_openni2.cpp @@ -1052,7 +1052,7 @@ IplImage* CvCapture_OpenNI2::retrieveGrayImage() cv::Mat rgbImage; getBGRImageFromMetaData(streamFrames[CV_COLOR_STREAM], rgbImage); - cv::cvtColor( rgbImage, outputMaps[CV_CAP_OPENNI_GRAY_IMAGE].mat, CV_BGR2GRAY ); + cv::cvtColor( rgbImage, outputMaps[CV_CAP_OPENNI_GRAY_IMAGE].mat, cv::COLOR_BGR2GRAY ); return outputMaps[CV_CAP_OPENNI_GRAY_IMAGE].getIplImagePtr(); } diff --git a/platforms/scripts/valgrind.supp b/platforms/scripts/valgrind.supp index c71cdf965d..7a77870669 100644 --- a/platforms/scripts/valgrind.supp +++ b/platforms/scripts/valgrind.supp @@ -230,7 +230,7 @@ Memcheck:Leak ... fun:gtk_init - fun:cvInitSystem + fun:gtk_InitSystem } { diff --git a/samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java b/samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java index 83c62f4638..5e1ab01b62 100644 --- a/samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java +++ b/samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java @@ -64,7 +64,7 @@ public class Puzzle15Processor { } for (int i = 0; i < GRID_AREA; i++) { - Size s = Imgproc.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null); + Size s = Imgproc.getTextSize(Integer.toString(i + 1), Imgproc.FONT_HERSHEY_COMPLEX, 1, 2, null); mTextHeights[i] = (int) s.height; mTextWidths[i] = (int) s.width; } @@ -100,7 +100,7 @@ public class Puzzle15Processor { cells[idx].copyTo(mCells15[i]); if (mShowTileNumbers) { Imgproc.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / GRID_SIZE - mTextWidths[idx]) / 2, - (rows / GRID_SIZE + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2); + (rows / GRID_SIZE + mTextHeights[idx]) / 2), Imgproc.FONT_HERSHEY_COMPLEX, 1, new Scalar(255, 0, 0, 255), 2); } } } diff --git a/samples/cpp/mask_tmpl.cpp b/samples/cpp/mask_tmpl.cpp index 0e4720c58e..5ac15cd6fe 100644 --- a/samples/cpp/mask_tmpl.cpp +++ b/samples/cpp/mask_tmpl.cpp @@ -52,7 +52,7 @@ int main( int argc, const char** argv ) return -1; } - int method = parser.get("cm"); // default 3 (CV_TM_CCORR_NORMED) + int method = parser.get("cm"); // default 3 (cv::TM_CCORR_NORMED) matchTemplate(img, tmpl, res, method, mask); double minVal, maxVal; diff --git a/samples/java/tutorial_code/ImgProc/erosion_dilatation/MorphologyDemo1.java b/samples/java/tutorial_code/ImgProc/erosion_dilatation/MorphologyDemo1.java index e71400f737..084fc9544d 100644 --- a/samples/java/tutorial_code/ImgProc/erosion_dilatation/MorphologyDemo1.java +++ b/samples/java/tutorial_code/ImgProc/erosion_dilatation/MorphologyDemo1.java @@ -28,7 +28,7 @@ public class MorphologyDemo1 { private static final int MAX_KERNEL_SIZE = 21; private Mat matImgSrc; private Mat matImgDst = new Mat(); - private int elementType = Imgproc.CV_SHAPE_RECT; + private int elementType = Imgproc.MORPH_RECT; private int kernelSize = 0; private boolean doErosion = true; private JFrame frame; @@ -74,11 +74,11 @@ public class MorphologyDemo1 { @SuppressWarnings("unchecked") JComboBox cb = (JComboBox)e.getSource(); if (cb.getSelectedIndex() == 0) { - elementType = Imgproc.CV_SHAPE_RECT; + elementType = Imgproc.MORPH_RECT; } else if (cb.getSelectedIndex() == 1) { - elementType = Imgproc.CV_SHAPE_CROSS; + elementType = Imgproc.MORPH_CROSS; } else if (cb.getSelectedIndex() == 2) { - elementType = Imgproc.CV_SHAPE_ELLIPSE; + elementType = Imgproc.MORPH_ELLIPSE; } update(); }