From b3bbe7704d160ca9678b57dc17c4a9074122fdfd Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Wed, 23 Dec 2015 13:06:56 +0100 Subject: [PATCH 01/95] add jaccardDistance measure for rectangle overlap computes the complement of the Jaccard Index as described in https://en.wikipedia.org/wiki/Jaccard_index. For rectangles this reduces to computing the intersection over the union. --- modules/core/include/opencv2/core/types.hpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/modules/core/include/opencv2/core/types.hpp b/modules/core/include/opencv2/core/types.hpp index e166556af7..6909676dc3 100644 --- a/modules/core/include/opencv2/core/types.hpp +++ b/modules/core/include/opencv2/core/types.hpp @@ -51,6 +51,7 @@ #include #include #include +#include #include "opencv2/core/cvdef.h" #include "opencv2/core/cvstd.hpp" @@ -1832,7 +1833,26 @@ Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) return c |= b; } +/** + * @brief measure dissimilarity between two sample sets + * + * computes the complement of the Jaccard Index as described in . + * For rectangles this reduces to computing the intersection over the union. + */ +template static inline +double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { + _Tp Aa = a.area(); + _Tp Ab = b.area(); + if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { + // jaccard_index = 1 -> distance = 0 + return 0.0; + } + + double Aab = (a & b).area(); + // distance = 1 - jaccard_index + return 1.0 - Aab / (Aa + Ab - Aab); +} ////////////////////////////// RotatedRect ////////////////////////////// From e607a85df61581db88202a40f69f646d7237c9d6 Mon Sep 17 00:00:00 2001 From: Ishank gulati Date: Wed, 23 Dec 2015 23:37:32 +0530 Subject: [PATCH 02/95] png-image-compatibility --- modules/videoio/src/cap_images.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/videoio/src/cap_images.cpp b/modules/videoio/src/cap_images.cpp index 00d5af47d1..e379561593 100644 --- a/modules/videoio/src/cap_images.cpp +++ b/modules/videoio/src/cap_images.cpp @@ -124,7 +124,7 @@ bool CvCapture_Images::grabFrame() } cvReleaseImage(&frame); - frame = cvLoadImage(str, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); + frame = cvLoadImage(str, CV_LOAD_IMAGE_UNCHANGED); if( frame ) currentframe++; From 551b5d3e1af5891959d797f947c850dbe9055ccd Mon Sep 17 00:00:00 2001 From: Kai Hugo Hustoft Endresen Date: Fri, 8 Jan 2016 00:32:52 +0100 Subject: [PATCH 03/95] StereoSGBM.cpp - use SSE2 for pass 2 using MODE_HH With a test image set of 2800x1400 bytes on a Intel Core i7 5960X this improves runtime of MODE_HH with about 10%. (this particular replaced code segment is approx 3 times faster than the non-SSE2 variant). I was able to reduce runtime by 130 ms by this simple fix. The second part of the SSE2 optimized part could probably be optimized further by using shift SSE2 operations, but I imagine this would improve performance 10-20 ms at best. --- modules/calib3d/src/stereosgbm.cpp | 50 +++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/modules/calib3d/src/stereosgbm.cpp b/modules/calib3d/src/stereosgbm.cpp index 1c085f9b3a..9b783e9d65 100644 --- a/modules/calib3d/src/stereosgbm.cpp +++ b/modules/calib3d/src/stereosgbm.cpp @@ -759,14 +759,50 @@ static void computeDisparitySGBM( const Mat& img1, const Mat& img2, } else { - for( d = 0; d < D; d++ ) + #if CV_SSE2 + if( useSIMD ) { - int Sval = Sp[d]; - if( Sval < minS ) - { - minS = Sval; - bestDisp = d; - } + __m128i _minS = _mm_set1_epi16(MAX_COST), _bestDisp = _mm_set1_epi16(-1); + __m128i _d8 = _mm_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7), _8 = _mm_set1_epi16(8); + + for( d = 0; d < D; d+= 8 ) + { + __m128i L0 = _mm_load_si128((const __m128i*)( Sp + d )); + __m128i mask = _mm_cmplt_epi16( L0, _minS ); + _minS = _mm_min_epi16( L0, _minS ); + _bestDisp = _mm_xor_si128(_bestDisp, _mm_and_si128(_mm_xor_si128( _bestDisp, _d8), mask)); + _d8 = _mm_adds_epi16(_d8, _8 ); + } + short CV_DECL_ALIGNED(16) bestDispBuf[8]; + _mm_store_si128((__m128i*)bestDispBuf, _bestDisp); + short CV_DECL_ALIGNED(16) minSBuf[8]; + _mm_store_si128((__m128i*)minSBuf, _minS ); + + for( int i = 0; i < 8; i++ ) + { + int Sval = minSBuf[ i ]; + if( Sval <= minS ) + { + if( ( Sval < minS ) || ( bestDispBuf[i] < bestDisp ) ) + { + bestDisp = bestDispBuf[i]; + } + minS = Sval; + } + } + } + else + #endif + { + for( d = 0; d < D; d++ ) + { + int Sval = Sp[d]; + if( Sval < minS ) + { + minS = Sval; + bestDisp = d; + } + } } } From b030ac0433768b2e9eef1e53849a7a719023db6f Mon Sep 17 00:00:00 2001 From: Mathieu Barnachon Date: Mon, 8 Feb 2016 13:17:08 +0100 Subject: [PATCH 04/95] Ensure the Cuda context is initialized correctly as long as the setDevice is not called in a multi-thread environment. --- modules/core/src/cuda_info.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/core/src/cuda_info.cpp b/modules/core/src/cuda_info.cpp index 5ad33ce8a1..08013ca988 100644 --- a/modules/core/src/cuda_info.cpp +++ b/modules/core/src/cuda_info.cpp @@ -70,6 +70,7 @@ void cv::cuda::setDevice(int device) (void) device; throw_no_cuda(); #else + cudaFree(0); cudaSafeCall( cudaSetDevice(device) ); #endif } From 6a0d3b3e42a1afd8f63b7e4b290c8227b93d7735 Mon Sep 17 00:00:00 2001 From: Mathieu Barnachon Date: Tue, 9 Feb 2016 14:40:09 +0100 Subject: [PATCH 05/95] Called after setDevice. Wrap in a cudaSafeCall. --- modules/core/src/cuda_info.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/core/src/cuda_info.cpp b/modules/core/src/cuda_info.cpp index 08013ca988..b412438581 100644 --- a/modules/core/src/cuda_info.cpp +++ b/modules/core/src/cuda_info.cpp @@ -70,8 +70,8 @@ void cv::cuda::setDevice(int device) (void) device; throw_no_cuda(); #else - cudaFree(0); cudaSafeCall( cudaSetDevice(device) ); + cudaSafeCall( cudaFree(0) ); #endif } From 5e9192287d98f70f0859f2358c4c2c774eb7716c Mon Sep 17 00:00:00 2001 From: Maksim Shabunin Date: Mon, 18 Apr 2016 16:34:25 +0300 Subject: [PATCH 06/95] Added HAL cvtColor interface --- modules/core/src/hal_replacement.hpp | 8 +- modules/core/src/stat.cpp | 6 + .../include/opencv2/imgproc/hal/hal.hpp | 102 + modules/imgproc/src/color.cpp | 2314 +++++++++-------- modules/imgproc/src/hal_replacement.hpp | 289 +- 5 files changed, 1648 insertions(+), 1071 deletions(-) diff --git a/modules/core/src/hal_replacement.hpp b/modules/core/src/hal_replacement.hpp index ef221b600c..7f826b4096 100644 --- a/modules/core/src/hal_replacement.hpp +++ b/modules/core/src/hal_replacement.hpp @@ -703,21 +703,25 @@ inline int hal_ni_gemm64fc(const double* src1, size_t src1_step, const double* s //! @cond IGNORED #define CALL_HAL_RET(name, fun, retval, ...) \ +{ \ int res = fun(__VA_ARGS__, &retval); \ if (res == CV_HAL_ERROR_OK) \ return retval; \ else if (res != CV_HAL_ERROR_NOT_IMPLEMENTED) \ CV_Error_(cv::Error::StsInternal, \ - ("HAL implementation " CVAUX_STR(name) " ==> " CVAUX_STR(fun) " returned %d (0x%08x)", res, res)); + ("HAL implementation " CVAUX_STR(name) " ==> " CVAUX_STR(fun) " returned %d (0x%08x)", res, res)); \ +} #define CALL_HAL(name, fun, ...) \ +{ \ int res = fun(__VA_ARGS__); \ if (res == CV_HAL_ERROR_OK) \ return; \ else if (res != CV_HAL_ERROR_NOT_IMPLEMENTED) \ CV_Error_(cv::Error::StsInternal, \ - ("HAL implementation " CVAUX_STR(name) " ==> " CVAUX_STR(fun) " returned %d (0x%08x)", res, res)); + ("HAL implementation " CVAUX_STR(name) " ==> " CVAUX_STR(fun) " returned %d (0x%08x)", res, res)); \ +} //! @endcond #endif diff --git a/modules/core/src/stat.cpp b/modules/core/src/stat.cpp index e3525752e5..339c6aed40 100644 --- a/modules/core/src/stat.cpp +++ b/modules/core/src/stat.cpp @@ -2718,19 +2718,25 @@ static bool ipp_norm(Mat &src, int normType, Mat &mask, double &result) ippiMaskNormFuncC3 ippFuncC3 = normType == NORM_INF ? (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_8u_C3CMR : +#if IPP_VERSION_X100 < 900 type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_8s_C3CMR : +#endif type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_16u_C3CMR : type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_32f_C3CMR : 0) : normType == NORM_L1 ? (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_8u_C3CMR : +#if IPP_VERSION_X100 < 900 type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_8s_C3CMR : +#endif type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_16u_C3CMR : type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_32f_C3CMR : 0) : normType == NORM_L2 || normType == NORM_L2SQR ? (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_8u_C3CMR : +#if IPP_VERSION_X100 < 900 type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_8s_C3CMR : +#endif type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_16u_C3CMR : type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_32f_C3CMR : 0) : 0; diff --git a/modules/imgproc/include/opencv2/imgproc/hal/hal.hpp b/modules/imgproc/include/opencv2/imgproc/hal/hal.hpp index 6ed492bcb6..0943a2dfa2 100644 --- a/modules/imgproc/include/opencv2/imgproc/hal/hal.hpp +++ b/modules/imgproc/include/opencv2/imgproc/hal/hal.hpp @@ -75,6 +75,108 @@ CV_EXPORTS void warpPerspectve(int src_type, uchar * dst_data, size_t dst_step, int dst_width, int dst_height, const double M[9], int interpolation, int borderType, const double borderValue[4]); +CV_EXPORTS void cvtBGRtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGRtoGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtGraytoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn); + +CV_EXPORTS void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); + +CV_EXPORTS void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); +CV_EXPORTS void cvtBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isCbCr); + +CV_EXPORTS void cvtYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isCbCr); + +CV_EXPORTS void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtXYZtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoHSV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtHSVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtBGRtoLab(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtLabtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx); + +CV_EXPORTS void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx); + +CV_EXPORTS void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx); + +CV_EXPORTS void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int uIdx, int ycn); + +CV_EXPORTS void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + +CV_EXPORTS void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + //! @} }} diff --git a/modules/imgproc/src/color.cpp b/modules/imgproc/src/color.cpp index 95197ec03c..cb71a13407 100644 --- a/modules/imgproc/src/color.cpp +++ b/modules/imgproc/src/color.cpp @@ -93,6 +93,7 @@ #include "precomp.hpp" #include "opencl_kernels_imgproc.hpp" #include +#include "hal_replacement.hpp" #define CV_DESCALE(x,n) (((x) + (1 << ((n)-1))) >> (n)) @@ -171,32 +172,38 @@ class CvtColorLoop_Invoker : public ParallelLoopBody typedef typename Cvt::channel_type _Tp; public: - CvtColorLoop_Invoker(const Mat& _src, Mat& _dst, const Cvt& _cvt) : - ParallelLoopBody(), src(_src), dst(_dst), cvt(_cvt) + CvtColorLoop_Invoker(const uchar * src_data_, size_t src_step_, uchar * dst_data_, size_t dst_step_, int width_, const Cvt& _cvt) : + ParallelLoopBody(), src_data(src_data_), src_step(src_step_), dst_data(dst_data_), dst_step(dst_step_), + width(width_), cvt(_cvt) { } virtual void operator()(const Range& range) const { - const uchar* yS = src.ptr(range.start); - uchar* yD = dst.ptr(range.start); + const uchar* yS = src_data + static_cast(range.start) * src_step; + uchar* yD = dst_data + static_cast(range.start) * dst_step; - for( int i = range.start; i < range.end; ++i, yS += src.step, yD += dst.step ) - cvt((const _Tp*)yS, (_Tp*)yD, src.cols); + for( int i = range.start; i < range.end; ++i, yS += src_step, yD += dst_step ) + cvt(reinterpret_cast(yS), reinterpret_cast<_Tp*>(yD), width); } private: - const Mat& src; - Mat& dst; + const uchar * src_data; + size_t src_step; + uchar * dst_data; + size_t dst_step; + int width; const Cvt& cvt; const CvtColorLoop_Invoker& operator= (const CvtColorLoop_Invoker&); }; template -void CvtColorLoop(const Mat& src, Mat& dst, const Cvt& cvt) +void CvtColorLoop(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, const Cvt& cvt) { - parallel_for_(Range(0, src.rows), CvtColorLoop_Invoker(src, dst, cvt), src.total()/(double)(1<<16) ); + parallel_for_(Range(0, height), + CvtColorLoop_Invoker(src_data, src_step, dst_data, dst_step, width, cvt), + (width * height) / static_cast(1<<16)); } #if defined (HAVE_IPP) && (IPP_VERSION_X100 >= 700) @@ -211,17 +218,17 @@ class CvtColorIPPLoop_Invoker : { public: - CvtColorIPPLoop_Invoker(const Mat& _src, Mat& _dst, const Cvt& _cvt, bool *_ok) : - ParallelLoopBody(), src(_src), dst(_dst), cvt(_cvt), ok(_ok) + CvtColorIPPLoop_Invoker(const uchar * src_data_, size_t src_step_, uchar * dst_data_, size_t dst_step_, int width_, const Cvt& _cvt, bool *_ok) : + ParallelLoopBody(), src_data(src_data_), src_step(src_step_), dst_data(dst_data_), dst_step(dst_step_), width(width_), cvt(_cvt), ok(_ok) { *ok = true; } virtual void operator()(const Range& range) const { - const void *yS = src.ptr(range.start); - void *yD = dst.ptr(range.start); - if( !cvt(yS, (int)src.step[0], yD, (int)dst.step[0], src.cols, range.end - range.start) ) + const void *yS = src_data + src_step * range.start; + void *yD = dst_data + dst_step * range.start; + if( !cvt(yS, static_cast(src_step), yD, static_cast(dst_step), width, range.end - range.start) ) *ok = false; else { @@ -230,8 +237,11 @@ public: } private: - const Mat& src; - Mat& dst; + const uchar * src_data; + size_t src_step; + uchar * dst_data; + size_t dst_step; + int width; const Cvt& cvt; bool *ok; @@ -239,25 +249,28 @@ private: }; template -bool CvtColorIPPLoop(const Mat& src, Mat& dst, const Cvt& cvt) +bool CvtColorIPPLoop(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, const Cvt& cvt) { bool ok; - parallel_for_(Range(0, src.rows), CvtColorIPPLoop_Invoker(src, dst, cvt, &ok), src.total()/(double)(1<<16) ); + parallel_for_(Range(0, height), CvtColorIPPLoop_Invoker(src_data, src_step, dst_data, dst_step, width, cvt, &ok), (width * height)/(double)(1<<16) ); return ok; } template -bool CvtColorIPPLoopCopy(Mat& src, Mat& dst, const Cvt& cvt) +bool CvtColorIPPLoopCopy(const uchar * src_data, size_t src_step, int src_type, uchar * dst_data, size_t dst_step, int width, int height, const Cvt& cvt) { Mat temp; - Mat &source = src; - if( src.data == dst.data ) + Mat src(Size(width, height), src_type, const_cast(src_data), src_step); + Mat source = src; + if( src_data == dst_data ) { src.copyTo(temp); source = temp; } bool ok; - parallel_for_(Range(0, source.rows), CvtColorIPPLoop_Invoker(source, dst, cvt, &ok), + parallel_for_(Range(0, source.rows), + CvtColorIPPLoop_Invoker(source.data, source.step, dst_data, dst_step, + source.cols, cvt, &ok), source.total()/(double)(1<<16) ); return ok; } @@ -354,11 +367,13 @@ static ippiGeneralFunc ippiXYZ2RGBTab[] = 0, (ippiGeneralFunc)ippiXYZToRGB_32f_C3R, 0, 0 }; +#if IPP_DISABLE_BLOCK static ippiGeneralFunc ippiRGB2HSVTab[] = { (ippiGeneralFunc)ippiRGBToHSV_8u_C3R, 0, (ippiGeneralFunc)ippiRGBToHSV_16u_C3R, 0, 0, 0, 0, 0 }; +#endif static ippiGeneralFunc ippiHSV2RGBTab[] = { @@ -6106,12 +6121,14 @@ const int ITUR_BT_601_CBV = -74448; template struct YUV420sp2RGB888Invoker : ParallelLoopBody { - Mat* dst; + uchar * dst_data; + size_t dst_step; + int width; const uchar* my1, *muv; - int width, stride; + size_t stride; - YUV420sp2RGB888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _uv) - : dst(_dst), my1(_y1), muv(_uv), width(_dst->cols), stride(_stride) {} + YUV420sp2RGB888Invoker(uchar * _dst_data, size_t _dst_step, int _dst_width, size_t _stride, const uchar* _y1, const uchar* _uv) + : dst_data(_dst_data), dst_step(_dst_step), width(_dst_width), my1(_y1), muv(_uv), stride(_stride) {} void operator()(const Range& range) const { @@ -6128,15 +6145,10 @@ struct YUV420sp2RGB888Invoker : ParallelLoopBody const uchar* y1 = my1 + rangeBegin * stride, *uv = muv + rangeBegin * stride / 2; -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtYUV4202RGB(bIdx, uIdx, 3, y1, uv, stride, dst->ptr(rangeBegin), dst->step, rangeEnd - rangeBegin, dst->cols)) - return; -#endif - for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, uv += stride) { - uchar* row1 = dst->ptr(j); - uchar* row2 = dst->ptr(j + 1); + uchar* row1 = dst_data + dst_step * j; + uchar* row2 = dst_data + dst_step * (j + 1); const uchar* y2 = y1 + stride; for (int i = 0; i < width; i += 2, row1 += 6, row2 += 6) @@ -6175,12 +6187,14 @@ struct YUV420sp2RGB888Invoker : ParallelLoopBody template struct YUV420sp2RGBA8888Invoker : ParallelLoopBody { - Mat* dst; + uchar * dst_data; + size_t dst_step; + int width; const uchar* my1, *muv; - int width, stride; + size_t stride; - YUV420sp2RGBA8888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _uv) - : dst(_dst), my1(_y1), muv(_uv), width(_dst->cols), stride(_stride) {} + YUV420sp2RGBA8888Invoker(uchar * _dst_data, size_t _dst_step, int _dst_width, size_t _stride, const uchar* _y1, const uchar* _uv) + : dst_data(_dst_data), dst_step(_dst_step), width(_dst_width), my1(_y1), muv(_uv), stride(_stride) {} void operator()(const Range& range) const { @@ -6197,15 +6211,10 @@ struct YUV420sp2RGBA8888Invoker : ParallelLoopBody const uchar* y1 = my1 + rangeBegin * stride, *uv = muv + rangeBegin * stride / 2; -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtYUV4202RGB(bIdx, uIdx, 4, y1, uv, stride, dst->ptr(rangeBegin), dst->step, rangeEnd - rangeBegin, dst->cols)) - return; -#endif - for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, uv += stride) { - uchar* row1 = dst->ptr(j); - uchar* row2 = dst->ptr(j + 1); + uchar* row1 = dst_data + dst_step * j; + uchar* row2 = dst_data + dst_step * (j + 1); const uchar* y2 = y1 + stride; for (int i = 0; i < width; i += 2, row1 += 8, row2 += 8) @@ -6248,20 +6257,22 @@ struct YUV420sp2RGBA8888Invoker : ParallelLoopBody template struct YUV420p2RGB888Invoker : ParallelLoopBody { - Mat* dst; + uchar * dst_data; + size_t dst_step; + int width; const uchar* my1, *mu, *mv; - int width, stride; + size_t stride; int ustepIdx, vstepIdx; - YUV420p2RGB888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx) - : dst(_dst), my1(_y1), mu(_u), mv(_v), width(_dst->cols), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {} + YUV420p2RGB888Invoker(uchar * _dst_data, size_t _dst_step, int _dst_width, size_t _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx) + : dst_data(_dst_data), dst_step(_dst_step), width(_dst_width), my1(_y1), mu(_u), mv(_v), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {} void operator()(const Range& range) const { const int rangeBegin = range.start * 2; const int rangeEnd = range.end * 2; - int uvsteps[2] = {width/2, stride - width/2}; + int uvsteps[2] = {width/2, static_cast(stride) - width/2}; int usIdx = ustepIdx, vsIdx = vstepIdx; const uchar* y1 = my1 + rangeBegin * stride; @@ -6276,8 +6287,8 @@ struct YUV420p2RGB888Invoker : ParallelLoopBody for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, u1 += uvsteps[(usIdx++) & 1], v1 += uvsteps[(vsIdx++) & 1]) { - uchar* row1 = dst->ptr(j); - uchar* row2 = dst->ptr(j + 1); + uchar* row1 = dst_data + dst_step * j; + uchar* row2 = dst_data + dst_step * (j + 1); const uchar* y2 = y1 + stride; for (int i = 0; i < width / 2; i += 1, row1 += 6, row2 += 6) @@ -6316,20 +6327,22 @@ struct YUV420p2RGB888Invoker : ParallelLoopBody template struct YUV420p2RGBA8888Invoker : ParallelLoopBody { - Mat* dst; + uchar * dst_data; + size_t dst_step; + int width; const uchar* my1, *mu, *mv; - int width, stride; + size_t stride; int ustepIdx, vstepIdx; - YUV420p2RGBA8888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx) - : dst(_dst), my1(_y1), mu(_u), mv(_v), width(_dst->cols), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {} + YUV420p2RGBA8888Invoker(uchar * _dst_data, size_t _dst_step, int _dst_width, size_t _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx) + : dst_data(_dst_data), dst_step(_dst_step), width(_dst_width), my1(_y1), mu(_u), mv(_v), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {} void operator()(const Range& range) const { int rangeBegin = range.start * 2; int rangeEnd = range.end * 2; - int uvsteps[2] = {width/2, stride - width/2}; + int uvsteps[2] = {width/2, static_cast(stride) - width/2}; int usIdx = ustepIdx, vsIdx = vstepIdx; const uchar* y1 = my1 + rangeBegin * stride; @@ -6344,8 +6357,8 @@ struct YUV420p2RGBA8888Invoker : ParallelLoopBody for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, u1 += uvsteps[(usIdx++) & 1], v1 += uvsteps[(vsIdx++) & 1]) { - uchar* row1 = dst->ptr(j); - uchar* row2 = dst->ptr(j + 1); + uchar* row1 = dst_data + dst_step * j; + uchar* row2 = dst_data + dst_step * (j + 1); const uchar* y2 = y1 + stride; for (int i = 0; i < width / 2; i += 1, row1 += 8, row2 += 8) @@ -6388,70 +6401,78 @@ struct YUV420p2RGBA8888Invoker : ParallelLoopBody #define MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION (320*240) template -inline void cvtYUV420sp2RGB(Mat& _dst, int _stride, const uchar* _y1, const uchar* _uv) +inline void cvtYUV420sp2RGB(uchar * dst_data, size_t dst_step, int dst_width, int dst_height, size_t _stride, const uchar* _y1, const uchar* _uv) { - YUV420sp2RGB888Invoker converter(&_dst, _stride, _y1, _uv); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) - parallel_for_(Range(0, _dst.rows/2), converter); + YUV420sp2RGB888Invoker converter(dst_data, dst_step, dst_width, _stride, _y1, _uv); + if (dst_width * dst_height >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) + parallel_for_(Range(0, dst_height/2), converter); else - converter(Range(0, _dst.rows/2)); + converter(Range(0, dst_height/2)); } template -inline void cvtYUV420sp2RGBA(Mat& _dst, int _stride, const uchar* _y1, const uchar* _uv) +inline void cvtYUV420sp2RGBA(uchar * dst_data, size_t dst_step, int dst_width, int dst_height, size_t _stride, const uchar* _y1, const uchar* _uv) { - YUV420sp2RGBA8888Invoker converter(&_dst, _stride, _y1, _uv); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) - parallel_for_(Range(0, _dst.rows/2), converter); + YUV420sp2RGBA8888Invoker converter(dst_data, dst_step, dst_width, _stride, _y1, _uv); + if (dst_width * dst_height >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) + parallel_for_(Range(0, dst_height/2), converter); else - converter(Range(0, _dst.rows/2)); + converter(Range(0, dst_height/2)); } template -inline void cvtYUV420p2RGB(Mat& _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx) +inline void cvtYUV420p2RGB(uchar * dst_data, size_t dst_step, int dst_width, int dst_height, size_t _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx) { - YUV420p2RGB888Invoker converter(&_dst, _stride, _y1, _u, _v, ustepIdx, vstepIdx); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) - parallel_for_(Range(0, _dst.rows/2), converter); + YUV420p2RGB888Invoker converter(dst_data, dst_step, dst_width, _stride, _y1, _u, _v, ustepIdx, vstepIdx); + if (dst_width * dst_height >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) + parallel_for_(Range(0, dst_height/2), converter); else - converter(Range(0, _dst.rows/2)); + converter(Range(0, dst_height/2)); } template -inline void cvtYUV420p2RGBA(Mat& _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx) +inline void cvtYUV420p2RGBA(uchar * dst_data, size_t dst_step, int dst_width, int dst_height, size_t _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx) { - YUV420p2RGBA8888Invoker converter(&_dst, _stride, _y1, _u, _v, ustepIdx, vstepIdx); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) - parallel_for_(Range(0, _dst.rows/2), converter); + YUV420p2RGBA8888Invoker converter(dst_data, dst_step, dst_width, _stride, _y1, _u, _v, ustepIdx, vstepIdx); + if (dst_width * dst_height >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION) + parallel_for_(Range(0, dst_height/2), converter); else - converter(Range(0, _dst.rows/2)); + converter(Range(0, dst_height/2)); } ///////////////////////////////////// RGB -> YUV420p ///////////////////////////////////// -template +template +inline void swapUV(uchar * &, uchar * &) {} +template<> +inline void swapUV<2>(uchar * & u, uchar * & v) { std::swap(u, v); } + +template struct RGB888toYUV420pInvoker: public ParallelLoopBody { - RGB888toYUV420pInvoker( const Mat& src, Mat* dst, const int uIdx ) - : src_(src), - dst_(dst), - uIdx_(uIdx) { } + RGB888toYUV420pInvoker(const uchar * _src_data, size_t _src_step, uchar * _dst_data, size_t _dst_step, + int _src_width, int _src_height, int _scn) + : src_data(_src_data), src_step(_src_step), + dst_data(_dst_data), dst_step(_dst_step), + src_width(_src_width), src_height(_src_height), + scn(_scn) { } void operator()(const Range& rowRange) const { - const int w = src_.cols; - const int h = src_.rows; + const int w = src_width; + const int h = src_height; - const int cn = src_.channels(); + const int cn = scn; for( int i = rowRange.start; i < rowRange.end; i++ ) { - const uchar* row0 = src_.ptr(2 * i); - const uchar* row1 = src_.ptr(2 * i + 1); + const uchar* row0 = src_data + src_step * (2 * i); + const uchar* row1 = src_data + src_step * (2 * i + 1); - uchar* y = dst_->ptr(2*i); - uchar* u = dst_->ptr(h + i/2) + (i % 2) * (w/2); - uchar* v = dst_->ptr(h + (i + h/2)/2) + ((i + h/2) % 2) * (w/2); - if( uIdx_ == 2 ) std::swap(u, v); + uchar* y = dst_data + dst_step * (2*i); + uchar* u = dst_data + dst_step * (h + i/2) + (i % 2) * (w/2); + uchar* v = dst_data + dst_step * (h + (i + h/2)/2) + ((i + h/2) % 2) * (w/2); + + swapUV(u, v); for( int j = 0, k = 0; j < w * cn; j += 2 * cn, k++ ) { @@ -6469,8 +6490,8 @@ struct RGB888toYUV420pInvoker: public ParallelLoopBody y[2*k + 0] = saturate_cast(y00 >> ITUR_BT_601_SHIFT); y[2*k + 1] = saturate_cast(y01 >> ITUR_BT_601_SHIFT); - y[2*k + dst_->step + 0] = saturate_cast(y10 >> ITUR_BT_601_SHIFT); - y[2*k + dst_->step + 1] = saturate_cast(y11 >> ITUR_BT_601_SHIFT); + y[2*k + dst_step + 0] = saturate_cast(y10 >> ITUR_BT_601_SHIFT); + y[2*k + dst_step + 1] = saturate_cast(y11 >> ITUR_BT_601_SHIFT); const int shifted128 = (128 << ITUR_BT_601_SHIFT); int u00 = ITUR_BT_601_CRU * r00 + ITUR_BT_601_CGU * g00 + ITUR_BT_601_CBU * b00 + halfShift + shifted128; @@ -6482,27 +6503,33 @@ struct RGB888toYUV420pInvoker: public ParallelLoopBody } } - static bool isFit( const Mat& src ) + static bool isFit( int src_width, int src_height ) { - return (src.total() >= 320*240); + return (src_width * src_height >= 320*240); } private: RGB888toYUV420pInvoker& operator=(const RGB888toYUV420pInvoker&); - const Mat& src_; - Mat* const dst_; - const int uIdx_; + const uchar * src_data; + size_t src_step; + uchar * dst_data; + size_t dst_step; + int src_width; + int src_height; + const int scn; }; template -static void cvtRGBtoYUV420p(const Mat& src, Mat& dst) +static void cvtRGBtoYUV420p(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int src_width, int src_height, int scn) { - RGB888toYUV420pInvoker colorConverter(src, &dst, uIdx); - if( RGB888toYUV420pInvoker::isFit(src) ) - parallel_for_(Range(0, src.rows/2), colorConverter); + RGB888toYUV420pInvoker colorConverter(src_data, src_step, dst_data, dst_step, src_width, src_height, scn); + if( RGB888toYUV420pInvoker::isFit(src_width, src_height) ) + parallel_for_(Range(0, src_height/2), colorConverter); else - colorConverter(Range(0, src.rows/2)); + colorConverter(Range(0, src_height/2)); } ///////////////////////////////////// YUV422 -> RGB ///////////////////////////////////// @@ -6510,12 +6537,16 @@ static void cvtRGBtoYUV420p(const Mat& src, Mat& dst) template struct YUV422toRGB888Invoker : ParallelLoopBody { - Mat* dst; - const uchar* src; - int width, stride; + uchar * dst_data; + size_t dst_step; + const uchar * src_data; + size_t src_step; + int width; - YUV422toRGB888Invoker(Mat* _dst, int _stride, const uchar* _yuv) - : dst(_dst), src(_yuv), width(_dst->cols), stride(_stride) {} + YUV422toRGB888Invoker(uchar * _dst_data, size_t _dst_step, + const uchar * _src_data, size_t _src_step, + int _width) + : dst_data(_dst_data), dst_step(_dst_step), src_data(_src_data), src_step(_src_step), width(_width) {} void operator()(const Range& range) const { @@ -6524,11 +6555,11 @@ struct YUV422toRGB888Invoker : ParallelLoopBody const int uidx = 1 - yIdx + uIdx * 2; const int vidx = (2 + uidx) % 4; - const uchar* yuv_src = src + rangeBegin * stride; + const uchar* yuv_src = src_data + rangeBegin * src_step; - for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += stride) + for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += src_step) { - uchar* row = dst->ptr(j); + uchar* row = dst_data + dst_step * j; for (int i = 0; i < 2 * width; i += 4, row += 6) { @@ -6556,12 +6587,16 @@ struct YUV422toRGB888Invoker : ParallelLoopBody template struct YUV422toRGBA8888Invoker : ParallelLoopBody { - Mat* dst; - const uchar* src; - int width, stride; + uchar * dst_data; + size_t dst_step; + const uchar * src_data; + size_t src_step; + int width; - YUV422toRGBA8888Invoker(Mat* _dst, int _stride, const uchar* _yuv) - : dst(_dst), src(_yuv), width(_dst->cols), stride(_stride) {} + YUV422toRGBA8888Invoker(uchar * _dst_data, size_t _dst_step, + const uchar * _src_data, size_t _src_step, + int _width) + : dst_data(_dst_data), dst_step(_dst_step), src_data(_src_data), src_step(_src_step), width(_width) {} void operator()(const Range& range) const { @@ -6570,11 +6605,11 @@ struct YUV422toRGBA8888Invoker : ParallelLoopBody const int uidx = 1 - yIdx + uIdx * 2; const int vidx = (2 + uidx) % 4; - const uchar* yuv_src = src + rangeBegin * stride; + const uchar* yuv_src = src_data + rangeBegin * src_step; - for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += stride) + for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += src_step) { - uchar* row = dst->ptr(j); + uchar* row = dst_data + dst_step * j; for (int i = 0; i < 2 * width; i += 4, row += 8) { @@ -6604,23 +6639,25 @@ struct YUV422toRGBA8888Invoker : ParallelLoopBody #define MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION (320*240) template -inline void cvtYUV422toRGB(Mat& _dst, int _stride, const uchar* _yuv) +inline void cvtYUV422toRGB(uchar * dst_data, size_t dst_step, const uchar * src_data, size_t src_step, + int width, int height) { - YUV422toRGB888Invoker converter(&_dst, _stride, _yuv); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION) - parallel_for_(Range(0, _dst.rows), converter); + YUV422toRGB888Invoker converter(dst_data, dst_step, src_data, src_step, width); + if (width * height >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION) + parallel_for_(Range(0, height), converter); else - converter(Range(0, _dst.rows)); + converter(Range(0, height)); } template -inline void cvtYUV422toRGBA(Mat& _dst, int _stride, const uchar* _yuv) +inline void cvtYUV422toRGBA(uchar * dst_data, size_t dst_step, const uchar * src_data, size_t src_step, + int width, int height) { - YUV422toRGBA8888Invoker converter(&_dst, _stride, _yuv); - if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION) - parallel_for_(Range(0, _dst.rows), converter); + YUV422toRGBA8888Invoker converter(dst_data, dst_step, src_data, src_step, width); + if (width * height >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION) + parallel_for_(Range(0, height), converter); else - converter(Range(0, _dst.rows)); + converter(Range(0, height)); } /////////////////////////// RGBA <-> mRGBA (alpha premultiplied) ////////////// @@ -7324,598 +7361,1025 @@ static bool ocl_cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) #endif -#ifdef HAVE_IPP -static bool ipp_cvtColor( Mat &src, OutputArray _dst, int code, int dcn ) +} + +// +// HAL functions +// + +namespace cv { +namespace hal { + +// 8u, 16u, 32f +void cvtBGRtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, int dcn, bool swapBlue) { - int stype = src.type(); - int scn = CV_MAT_CN(stype), depth = CV_MAT_DEPTH(stype); + CALL_HAL(cvtBGRtoBGR, cv_hal_cvtBGRtoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, scn, dcn, swapBlue); - Mat dst; - Size sz = src.size(); - - switch( code ) +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() { -#if IPP_VERSION_X100 >= 700 - case CV_BGR2BGRA: case CV_RGB2BGRA: case CV_BGRA2BGR: - case CV_RGBA2BGR: case CV_RGB2BGR: case CV_BGRA2RGBA: - CV_Assert( scn == 3 || scn == 4 ); - dcn = code == CV_BGR2BGRA || code == CV_RGB2BGRA || code == CV_BGRA2RGBA ? 4 : 3; - _dst.create( sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( code == CV_BGR2BGRA) - { - if ( CvtColorIPPLoop(src, dst, IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 0, 1, 2)) ) - return true; - } - else if( code == CV_BGRA2BGR ) - { - if ( CvtColorIPPLoop(src, dst, IPPGeneralFunctor(ippiCopyAC4C3RTab[depth])) ) - return true; - } - else if( code == CV_BGR2RGBA ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 2, 1, 0)) ) - return true; - } - else if( code == CV_RGBA2BGR ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderFunctor(ippiSwapChannelsC4C3RTab[depth], 2, 1, 0)) ) - return true; - } - else if( code == CV_RGB2BGR ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderFunctor(ippiSwapChannelsC3RTab[depth], 2, 1, 0)) ) - return true; - } + if(scn == 3 && dcn == 4 && !swapBlue) + { + if ( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 0, 1, 2)) ) + return; + } + else if(scn == 4 && dcn == 3 && !swapBlue) + { + if ( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiCopyAC4C3RTab[depth])) ) + return; + } + else if(scn == 3 && dcn == 4 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderFunctor(ippiSwapChannelsC3C4RTab[depth], 2, 1, 0)) ) + return; + } + else if(scn == 4 && dcn == 3 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderFunctor(ippiSwapChannelsC4C3RTab[depth], 2, 1, 0)) ) + return; + } + else if(scn == 3 && dcn == 3 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height, + IPPReorderFunctor(ippiSwapChannelsC3RTab[depth], 2, 1, 0)) ) + return; + } #if IPP_VERSION_X100 >= 810 - else if( code == CV_RGBA2BGRA ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderFunctor(ippiSwapChannelsC4RTab[depth], 2, 1, 0)) ) - return true; - } + else if(scn == 4 && dcn == 4 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height, + IPPReorderFunctor(ippiSwapChannelsC4RTab[depth], 2, 1, 0)) ) + return; + } + } #endif - return false; #endif + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2RGB(scn, dcn, blueIdx)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2RGB(scn, dcn, blueIdx)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2RGB(scn, dcn, blueIdx)); +} + +// only 8u +void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int greenBits) +{ + CALL_HAL(cvtBGRtoBGR5x5, cv_hal_cvtBGRtoBGR5x5, src_data, src_step, dst_data, dst_step, width, height, scn, swapBlue, greenBits); + +#if defined(HAVE_IPP) && IPP_DISABLE_BLOCK // breaks OCL accuracy tests + CV_IPP_CHECK() + { + CV_SUPPRESS_DEPRECATED_START; + if (scn == 3 && greenBits == 6 && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R))) + return; + } + else if (scn == 4 && greenBits == 6 && !swapBlue) + { + if (CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(CV_8U, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[CV_8U], + (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 0, 1, 2, CV_8U))) + return; + } + else if (scn == 3 && greenBits == 6 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(CV_8U, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[CV_8U], + (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 2, 1, 0, CV_8U)) ) + return; + } + else if (scn == 4 && greenBits == 6 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(CV_8U, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[CV_8U], + (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 2, 1, 0, CV_8U)) ) + return; + } + CV_SUPPRESS_DEPRECATED_END; + } +#endif + + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2RGB5x5(scn, swapBlue ? 2 : 0, greenBits)); +} + +// only 8u +void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int greenBits) +{ + CALL_HAL(cvtBGR5x5toBGR, cv_hal_cvtBGR5x5toBGR, src_data, src_step, dst_data, dst_step, width, height, dcn, swapBlue, greenBits); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 < 900 + CV_IPP_CHECK() + { + CV_SUPPRESS_DEPRECATED_START; + if (dcn == 3 && greenBits == 6 && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R))) + return; + } + else if (dcn == 3 && greenBits == 6 && swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, + ippiSwapChannelsC3RTab[CV_8U], 2, 1, 0, CV_8U))) + return; + } + else if (dcn == 4 && greenBits == 6 && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, + ippiSwapChannelsC3C4RTab[CV_8U], 0, 1, 2, CV_8U))) + return; + } + else if (dcn == 4 && greenBits == 6 && swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, + ippiSwapChannelsC3C4RTab[CV_8U], 2, 1, 0, CV_8U))) + return; + } + CV_SUPPRESS_DEPRECATED_END; + } +#endif + + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB5x52RGB(dcn, swapBlue ? 2 : 0, greenBits)); +} + +// 8u, 16u, 32f +void cvtBGRtoGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue) +{ + CALL_HAL(cvtBGRtoGray, cv_hal_cvtBGRtoGray, src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if(depth == CV_32F && scn == 3 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPColor2GrayFunctor(ippiColor2GrayC3Tab[depth])) ) + return; + } + else if(depth == CV_32F && scn == 3 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiRGB2GrayC3Tab[depth])) ) + return; + } + else if(depth == CV_32F && scn == 4 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPColor2GrayFunctor(ippiColor2GrayC4Tab[depth])) ) + return; + } + else if(depth == CV_32F && scn == 4 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiRGB2GrayC4Tab[depth])) ) + return; + } + } +#endif + + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Gray(scn, blueIdx, 0)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Gray(scn, blueIdx, 0)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Gray(scn, blueIdx, 0)); +} + +// 8u, 16u, 32f +void cvtGraytoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn) +{ + CALL_HAL(cvtGraytoBGR, cv_hal_cvtGraytoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, dcn); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if(dcn == 3) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGray2BGRFunctor(ippiCopyP3C3RTab[depth])) ) + return; + } + else if(dcn == 4) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGray2BGRAFunctor(ippiCopyP3C3RTab[depth], ippiSwapChannelsC3C4RTab[depth], depth)) ) + return; + } + } +#endif + + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Gray2RGB(dcn)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Gray2RGB(dcn)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Gray2RGB(dcn)); +} + +// only 8u +void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits) +{ + CALL_HAL(cvtBGR5x5toGray, cv_hal_cvtBGR5x5toGray, src_data, src_step, dst_data, dst_step, width, height, greenBits); + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB5x52Gray(greenBits)); +} + +// only 8u +void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits) +{ + CALL_HAL(cvtGraytoBGR5x5, cv_hal_cvtGraytoBGR5x5, src_data, src_step, dst_data, dst_step, width, height, greenBits); + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Gray2RGB5x5(greenBits)); +} + +// 8u, 16u, 32f +void cvtBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isCbCr) +{ + CALL_HAL(cvtBGRtoYUV, cv_hal_cvtBGRtoYUV, src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue, isCbCr); + +#if defined(HAVE_IPP) && IPP_DISABLE_BLOCK + CV_IPP_CHECK() + { + if (scn == 3 && depth == CV_8U && swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiRGBToYUV_8u_C3R))) + return; + } + else if (scn == 3 && depth == CV_8U && !swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], + (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth))) + return; + } + else if (scn == 4 && depth == CV_8U && swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 0, 1, 2, depth))) + return; + } + else if (scn == 4 && depth == CV_8U && !swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth))) + return; + } + } +#endif + + static const float yuv_f[] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f }; + static const int yuv_i[] = { B2Y, G2Y, R2Y, 8061, 14369 }; + const float* coeffs_f = isCbCr ? 0 : yuv_f; + const int* coeffs_i = isCbCr ? 0 : yuv_i; + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2YCrCb_i(scn, blueIdx, coeffs_i)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2YCrCb_i(scn, blueIdx, coeffs_i)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2YCrCb_f(scn, blueIdx, coeffs_f)); +} + +void cvtYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isCbCr) +{ + CALL_HAL(cvtYUVtoBGR, cv_hal_cvtYUVtoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, dcn, swapBlue, isCbCr); + + +#if defined(HAVE_IPP) && IPP_DISABLE_BLOCK + CV_IPP_CHECK() + { + if (dcn == 3 && depth == CV_8U && swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R))) + return; + } + else if (dcn == 3 && depth == CV_8U && !swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, + ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth))) + return; + } + else if (dcn == 4 && depth == CV_8U && swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, + ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth))) + return; + } + else if (dcn == 4 && depth == CV_8U && !swapBlue && !isCbCr) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, + ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth))) + return; + } + } +#endif + + static const float yuv_f[] = { 2.032f, -0.395f, -0.581f, 1.140f }; + static const int yuv_i[] = { 33292, -6472, -9519, 18678 }; + const float* coeffs_f = isCbCr ? 0 : yuv_f; + const int* coeffs_i = isCbCr ? 0 : yuv_i; + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, YCrCb2RGB_i(dcn, blueIdx, coeffs_i)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, YCrCb2RGB_i(dcn, blueIdx, coeffs_i)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, YCrCb2RGB_f(dcn, blueIdx, coeffs_f)); +} + +void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue) +{ + CALL_HAL(cvtBGRtoXYZ, cv_hal_cvtBGRtoXYZ, src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if(scn == 3 && depth != CV_32F && !swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(scn == 4 && depth != CV_32F && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(scn == 3 && depth != CV_32F && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, scn), dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiRGB2XYZTab[depth])) ) + return; + } + else if(scn == 4 && depth != CV_32F && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 0, 1, 2, depth)) ) + return; + } + } +#endif + + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2XYZ_i(scn, blueIdx, 0)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2XYZ_i(scn, blueIdx, 0)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2XYZ_f(scn, blueIdx, 0)); +} + +void cvtXYZtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue) +{ + CALL_HAL(cvtXYZtoBGR, cv_hal_cvtXYZtoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, dcn, swapBlue); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if(dcn == 3 && depth != CV_32F && !swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(dcn == 4 && depth != CV_32F && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) + return; + } + if(dcn == 3 && depth != CV_32F && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiXYZ2RGBTab[depth])) ) + return; + } + else if(dcn == 4 && depth != CV_32F && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) + return; + } + } +#endif + + int blueIdx = swapBlue ? 2 : 0; + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, XYZ2RGB_i(dcn, blueIdx, 0)); + else if( depth == CV_16U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, XYZ2RGB_i(dcn, blueIdx, 0)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, XYZ2RGB_f(dcn, blueIdx, 0)); +} + +// 8u, 32f +void cvtBGRtoHSV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV) +{ + CALL_HAL(cvtBGRtoHSV, cv_hal_cvtBGRtoHSV, src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue, isFullRange, isHSV); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if (depth == CV_8U && isFullRange) + { + if (isHSV) + { #if IPP_DISABLE_BLOCK // breaks OCL accuracy tests - case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_RGB2BGR565: case CV_RGB2BGR555: - case CV_BGRA2BGR565: case CV_BGRA2BGR555: case CV_RGBA2BGR565: case CV_RGBA2BGR555: - CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U ); - _dst.create(sz, CV_8UC2); - dst = _dst.getMat(); - - CV_SUPPRESS_DEPRECATED_START - - if (code == CV_BGR2BGR565 && scn == 3) + if(scn == 3 && !swapBlue) { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R))) - return true; + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) ) + return; } - else if (code == CV_BGRA2BGR565 && scn == 4) + else if(scn == 4 && !swapBlue) { - if (CvtColorIPPLoopCopy(src, dst, - IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 0, 1, 2, depth))) - return true; + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) ) + return; } - else if (code == CV_RGB2BGR565 && scn == 3) + else if(scn == 4 && swapBlue) { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], - (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 2, 1, 0, depth)) ) - return true; + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 0, 1, 2, depth)) ) + return; } - else if (code == CV_RGBA2BGR565 && scn == 4) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiBGRToBGR565_8u16u_C3R, 2, 1, 0, depth)) ) - return true; - } - CV_SUPPRESS_DEPRECATED_END - return false; #endif - -#if IPP_VERSION_X100 < 900 - case CV_BGR5652BGR: case CV_BGR5552BGR: case CV_BGR5652RGB: case CV_BGR5552RGB: - case CV_BGR5652BGRA: case CV_BGR5552BGRA: case CV_BGR5652RGBA: case CV_BGR5552RGBA: - if(dcn <= 0) dcn = (code==CV_BGR5652BGRA || code==CV_BGR5552BGRA || code==CV_BGR5652RGBA || code==CV_BGR5552RGBA) ? 4 : 3; - CV_Assert( (dcn == 3 || dcn == 4) && scn == 2 && depth == CV_8U ); - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - CV_SUPPRESS_DEPRECATED_START - if (code == CV_BGR5652BGR && dcn == 3) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R))) - return true; - } - else if (code == CV_BGR5652RGB && dcn == 3) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, - ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth))) - return true; - } - else if (code == CV_BGR5652BGRA && dcn == 4) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth))) - return true; - } - else if (code == CV_BGR5652RGBA && dcn == 4) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiBGR565ToBGR_16u8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth))) - return true; - } - CV_SUPPRESS_DEPRECATED_END - return false; -#endif - -#if IPP_VERSION_X100 >= 700 - case CV_BGR2GRAY: case CV_BGRA2GRAY: case CV_RGB2GRAY: case CV_RGBA2GRAY: - CV_Assert( scn == 3 || scn == 4 ); - _dst.create(sz, CV_MAKETYPE(depth, 1)); - dst = _dst.getMat(); - - if( code == CV_BGR2GRAY && depth == CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPColor2GrayFunctor(ippiColor2GrayC3Tab[depth])) ) - return true; - } - else if( code == CV_RGB2GRAY && depth == CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralFunctor(ippiRGB2GrayC3Tab[depth])) ) - return true; - } - else if( code == CV_BGRA2GRAY && depth == CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPColor2GrayFunctor(ippiColor2GrayC4Tab[depth])) ) - return true; - } - else if( code == CV_RGBA2GRAY && depth == CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralFunctor(ippiRGB2GrayC4Tab[depth])) ) - return true; - } - return false; - - case CV_GRAY2BGR: case CV_GRAY2BGRA: - if( dcn <= 0 ) dcn = (code==CV_GRAY2BGRA) ? 4 : 3; - CV_Assert( scn == 1 && (dcn == 3 || dcn == 4)); - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( code == CV_GRAY2BGR ) - { - if( CvtColorIPPLoop(src, dst, IPPGray2BGRFunctor(ippiCopyP3C3RTab[depth])) ) - return true; - } - else if( code == CV_GRAY2BGRA ) - { - if( CvtColorIPPLoop(src, dst, IPPGray2BGRAFunctor(ippiCopyP3C3RTab[depth], ippiSwapChannelsC3C4RTab[depth], depth)) ) - return true; - } - return false; -#endif - -#if IPP_DISABLE_BLOCK - case CV_BGR2YCrCb: case CV_RGB2YCrCb: - case CV_BGR2YUV: case CV_RGB2YUV: - { - CV_Assert( scn == 3 || scn == 4 ); - static const float yuv_f[] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f }; - static const int yuv_i[] = { B2Y, G2Y, R2Y, 8061, 14369 }; - const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f; - const int* coeffs_i = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_i; - - _dst.create(sz, CV_MAKETYPE(depth, 3)); - dst = _dst.getMat(); - - if (code == CV_RGB2YUV && scn == 3 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiRGBToYUV_8u_C3R))) - return true; - } - else if (code == CV_BGR2YUV && scn == 3 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], - (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth))) - return true; - } - else if (code == CV_RGB2YUV && scn == 4 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 0, 1, 2, depth))) - return true; - } - else if (code == CV_BGR2YUV && scn == 4 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiRGBToYUV_8u_C3R, 2, 1, 0, depth))) - return true; - } - return false; } -#endif - -#if IPP_DISABLE_BLOCK - case CV_YCrCb2BGR: case CV_YCrCb2RGB: - case CV_YUV2BGR: case CV_YUV2RGB: + else { - if( dcn <= 0 ) dcn = 3; - CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); - static const float yuv_f[] = { 2.032f, -0.395f, -0.581f, 1.140f }; - static const int yuv_i[] = { 33292, -6472, -9519, 18678 }; - const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f; - const int* coeffs_i = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_i; - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if (code == CV_YUV2RGB && dcn == 3 && depth == CV_8U) + if(scn == 3 && !swapBlue) { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R))) - return true; + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) ) + return; } - else if (code == CV_YUV2BGR && dcn == 3 && depth == CV_8U) + else if(scn == 4 && !swapBlue) { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, - ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth))) - return true; + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) ) + return; } - else if (code == CV_YUV2RGB && dcn == 4 && depth == CV_8U) + else if(scn == 3 && swapBlue) { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth))) - return true; + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKE_TYPE(depth, scn), dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiRGB2HLSTab[depth])) ) + return; } - else if (code == CV_YUV2BGR && dcn == 4 && depth == CV_8U) + else if(scn == 4 && swapBlue) { - if (CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiYUVToRGB_8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth))) - return true; + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 0, 1, 2, depth)) ) + return; } - return false; } + } + } #endif -#if IPP_VERSION_X100 >= 700 - case CV_BGR2XYZ: case CV_RGB2XYZ: - CV_Assert( scn == 3 || scn == 4 ); - _dst.create(sz, CV_MAKETYPE(depth, 3)); - dst = _dst.getMat(); - - if( code == CV_BGR2XYZ && scn == 3 && depth != CV_32F ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_BGR2XYZ && scn == 4 && depth != CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_RGB2XYZ && scn == 3 && depth != CV_32F ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiRGB2XYZTab[depth])) ) - return true; - } - else if( code == CV_RGB2XYZ && scn == 4 && depth != CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2XYZTab[depth], 0, 1, 2, depth)) ) - return true; - } - return false; -#endif - -#if IPP_VERSION_X100 >= 700 - case CV_XYZ2BGR: case CV_XYZ2RGB: - if( dcn <= 0 ) dcn = 3; - CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( code == CV_XYZ2BGR && dcn == 3 && depth != CV_32F ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_XYZ2BGR && dcn == 4 && depth != CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) - return true; - } - if( code == CV_XYZ2RGB && dcn == 3 && depth != CV_32F ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiXYZ2RGBTab[depth])) ) - return true; - } - else if( code == CV_XYZ2RGB && dcn == 4 && depth != CV_32F ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiXYZ2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) - return true; - } - return false; -#endif - -#if IPP_VERSION_X100 >= 700 - case CV_BGR2HSV: case CV_RGB2HSV: case CV_BGR2HSV_FULL: case CV_RGB2HSV_FULL: - case CV_BGR2HLS: case CV_RGB2HLS: case CV_BGR2HLS_FULL: case CV_RGB2HLS_FULL: - { - CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) ); - _dst.create(sz, CV_MAKETYPE(depth, 3)); - dst = _dst.getMat(); - - if( depth == CV_8U || depth == CV_16U ) - { -#if IPP_DISABLE_BLOCK // breaks OCL accuracy tests - if( code == CV_BGR2HSV_FULL && scn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_BGR2HSV_FULL && scn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_RGB2HSV_FULL && scn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HSVTab[depth], 0, 1, 2, depth)) ) - return true; - } else -#endif - if( code == CV_RGB2HSV_FULL && scn == 3 && depth == CV_16U ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiRGB2HSVTab[depth])) ) - return true; - } - else if( code == CV_BGR2HLS_FULL && scn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_BGR2HLS_FULL && scn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_RGB2HLS_FULL && scn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiRGB2HLSTab[depth])) ) - return true; - } - else if( code == CV_RGB2HLS_FULL && scn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], ippiRGB2HLSTab[depth], 0, 1, 2, depth)) ) - return true; - } - } - return false; - } -#endif - -#if IPP_VERSION_X100 >= 700 - case CV_HSV2BGR: case CV_HSV2RGB: case CV_HSV2BGR_FULL: case CV_HSV2RGB_FULL: - case CV_HLS2BGR: case CV_HLS2RGB: case CV_HLS2BGR_FULL: case CV_HLS2RGB_FULL: - { - if( dcn <= 0 ) dcn = 3; - CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) ); - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( depth == CV_8U || depth == CV_16U ) - { - if( code == CV_HSV2BGR_FULL && dcn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_HSV2BGR_FULL && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_HSV2RGB_FULL && dcn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiHSV2RGBTab[depth])) ) - return true; - } - else if( code == CV_HSV2RGB_FULL && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) - return true; - } - else if( code == CV_HLS2BGR_FULL && dcn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_HLS2BGR_FULL && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_HLS2RGB_FULL && dcn == 3 ) - { - if( CvtColorIPPLoopCopy(src, dst, IPPGeneralFunctor(ippiHLS2RGBTab[depth])) ) - return true; - } - else if( code == CV_HLS2RGB_FULL && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) - return true; - } - } - return false; - } -#endif - -#if IPP_DISABLE_BLOCK - case CV_BGR2Lab: case CV_RGB2Lab: case CV_LBGR2Lab: case CV_LRGB2Lab: - case CV_BGR2Luv: case CV_RGB2Luv: case CV_LBGR2Luv: case CV_LRGB2Luv: - { - CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) ); - bool srgb = code == CV_BGR2Lab || code == CV_RGB2Lab || - code == CV_BGR2Luv || code == CV_RGB2Luv; - - _dst.create(sz, CV_MAKETYPE(depth, 3)); - dst = _dst.getMat(); - - if (code == CV_LBGR2Lab && scn == 3 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiBGRToLab_8u_C3R))) - return true; - } - else if (code == CV_LBGR2Lab && scn == 4 && depth == CV_8U) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 0, 1, 2, depth))) - return true; - } - else - if (code == CV_LRGB2Lab && scn == 3 && depth == CV_8U) // slower than OpenCV - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], - (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth))) - return true; - } - else if (code == CV_LRGB2Lab && scn == 4 && depth == CV_8U) // slower than OpenCV - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth))) - return true; - } - else if (code == CV_LRGB2Luv && scn == 3) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor(ippiRGBToLUVTab[depth]))) - return true; - } - else if (code == CV_LRGB2Luv && scn == 4) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - ippiRGBToLUVTab[depth], 0, 1, 2, depth))) - return true; - } - else if (code == CV_LBGR2Luv && scn == 3) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], - ippiRGBToLUVTab[depth], 2, 1, 0, depth))) - return true; - } - else if (code == CV_LBGR2Luv && scn == 4) - { - if (CvtColorIPPLoop(src, dst, IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], - ippiRGBToLUVTab[depth], 2, 1, 0, depth))) - return true; - } - return false; - } -#endif - -#if IPP_DISABLE_BLOCK - case CV_Lab2BGR: case CV_Lab2RGB: case CV_Lab2LBGR: case CV_Lab2LRGB: - case CV_Luv2BGR: case CV_Luv2RGB: case CV_Luv2LBGR: case CV_Luv2LRGB: - { - if( dcn <= 0 ) dcn = 3; - CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) ); - bool srgb = code == CV_Lab2BGR || code == CV_Lab2RGB || - code == CV_Luv2BGR || code == CV_Luv2RGB; - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( code == CV_Lab2LBGR && dcn == 3 && depth == CV_8U) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R)) ) - return true; - } - else if( code == CV_Lab2LBGR && dcn == 4 && depth == CV_8U ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) - return true; - } - if( code == CV_Lab2LRGB && dcn == 3 && depth == CV_8U ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, - ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_Lab2LRGB && dcn == 4 && depth == CV_8U ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, - ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) - return true; - } - if( code == CV_Luv2LRGB && dcn == 3 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralFunctor(ippiLUVToRGBTab[depth])) ) - return true; - } - else if( code == CV_Luv2LRGB && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], - ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) - return true; - } - if( code == CV_Luv2LBGR && dcn == 3 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], - ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) - return true; - } - else if( code == CV_Luv2LBGR && dcn == 4 ) - { - if( CvtColorIPPLoop(src, dst, IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], - ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) - return true; - } - return false; - } -#endif - - case CV_YUV2GRAY_420: - { - if (dcn <= 0) dcn = 1; - - CV_Assert( dcn == 1 ); - CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U ); - - Size dstSz(sz.width, sz.height * 2 / 3); - _dst.create(dstSz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if (ippStsNoErr == ippiCopy_8u_C1R(src.data, (int)src.step, dst.data, (int)dst.step, - ippiSize(dstSz.width, dstSz.height))) - return true; - return false; - } - - case CV_RGBA2mRGBA: - { - if (dcn <= 0) dcn = 4; - CV_Assert( scn == 4 && dcn == 4 ); - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( depth == CV_8U ) - { - if (CvtColorIPPLoop(src, dst, IPPGeneralFunctor((ippiGeneralFunc)ippiAlphaPremul_8u_AC4R))) - return true; - return false; - } - - return false; - } - - default: - return false; + int hrange = depth == CV_32F ? 360 : isFullRange ? 256 : 180; + int blueIdx = swapBlue ? 2 : 0; + if(isHSV) + { + if(depth == CV_8U) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2HSV_b(scn, blueIdx, hrange)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2HSV_f(scn, blueIdx, static_cast(hrange))); + } + else + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2HLS_b(scn, blueIdx, hrange)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2HLS_f(scn, blueIdx, static_cast(hrange))); } } + +// 8u, 32f +void cvtHSVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV) +{ + CALL_HAL(cvtHSVtoBGR, cv_hal_cvtHSVtoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, dcn, swapBlue, isFullRange, isHSV); + +#if defined(HAVE_IPP) && IPP_VERSION_X100 >= 700 + CV_IPP_CHECK() + { + if (depth == CV_8U && isFullRange) + { + if (isHSV) + { + if(dcn == 3 && !swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(dcn == 4 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(dcn == 3 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiHSV2RGBTab[depth])) ) + return; + } + else if(dcn == 4 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHSV2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) + return; + } + } + else + { + if(dcn == 3 && !swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(dcn == 4 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if(dcn == 3 && swapBlue) + { + if( CvtColorIPPLoopCopy(src_data, src_step, CV_MAKETYPE(depth, 3), dst_data, dst_step, width, height, + IPPGeneralFunctor(ippiHLS2RGBTab[depth])) ) + return; + } + else if(dcn == 4 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralReorderFunctor(ippiHLS2RGBTab[depth], ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) + return; + } + } + } + } #endif + + int hrange = depth == CV_32F ? 360 : isFullRange ? 255 : 180; + int blueIdx = swapBlue ? 2 : 0; + if(isHSV) + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, HSV2RGB_b(dcn, blueIdx, hrange)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, HSV2RGB_f(dcn, blueIdx, static_cast(hrange))); + } + else + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, HLS2RGB_b(dcn, blueIdx, hrange)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, HLS2RGB_f(dcn, blueIdx, static_cast(hrange))); + } +} + +// 8u, 32f +void cvtBGRtoLab(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isLab, bool srgb) +{ + CALL_HAL(cvtBGRtoLab, cv_hal_cvtBGRtoLab, src_data, src_step, dst_data, dst_step, width, height, depth, scn, swapBlue, isLab, srgb); + +#if defined(HAVE_IPP) && IPP_DISABLE_BLOCK + CV_IPP_CHECK() + { + if (!srgb) + { + if (isLab) + { + if (scn == 3 && depth == CV_8U && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiBGRToLab_8u_C3R))) + return; + } + else if (scn == 4 && depth == CV_8U && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 0, 1, 2, depth))) + return; + } + else if (scn == 3 && depth == CV_8U && swapBlue) // slower than OpenCV + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], + (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth))) + return; + } + else if (scn == 4 && depth == CV_8U && swapBlue) // slower than OpenCV + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + (ippiGeneralFunc)ippiBGRToLab_8u_C3R, 2, 1, 0, depth))) + return; + } + } + else + { + if (scn == 3 && swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralFunctor(ippiRGBToLUVTab[depth]))) + return; + } + else if (scn == 4 && swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + ippiRGBToLUVTab[depth], 0, 1, 2, depth))) + return; + } + else if (scn == 3 && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC3RTab[depth], + ippiRGBToLUVTab[depth], 2, 1, 0, depth))) + return; + } + else if (scn == 4 && !swapBlue) + { + if (CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPReorderGeneralFunctor(ippiSwapChannelsC4C3RTab[depth], + ippiRGBToLUVTab[depth], 2, 1, 0, depth))) + return; + } + } + } + } +#endif + + + int blueIdx = swapBlue ? 2 : 0; + if(isLab) + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Lab_b(scn, blueIdx, 0, 0, srgb)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Lab_f(scn, blueIdx, 0, 0, srgb)); + } + else + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Luv_b(scn, blueIdx, 0, 0, srgb)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGB2Luv_f(scn, blueIdx, 0, 0, srgb)); + } +} + +// 8u, 32f +void cvtLabtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isLab, bool srgb) +{ + CALL_HAL(cvtLabtoBGR, cv_hal_cvtLabtoBGR, src_data, src_step, dst_data, dst_step, width, height, depth, dcn, swapBlue, isLab, srgb); + +#if defined(HAVE_IPP) && IPP_DISABLE_BLOCK + CV_IPP_CHECK() + { + if (!srgb) + { + if (isLab) + { + if( dcn == 3 && depth == CV_8U && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R)) ) + return; + } + else if( dcn == 4 && depth == CV_8U && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, + ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) + return; + } + if( dcn == 3 && depth == CV_8U && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, + ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if( dcn == 4 && depth == CV_8U && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor((ippiGeneralFunc)ippiLabToBGR_8u_C3R, + ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) + return; + } + } + else + { + if( dcn == 3 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralFunctor(ippiLUVToRGBTab[depth])) ) + return; + } + else if( dcn == 4 && swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], + ippiSwapChannelsC3C4RTab[depth], 0, 1, 2, depth)) ) + return; + } + if( dcn == 3 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], + ippiSwapChannelsC3RTab[depth], 2, 1, 0, depth)) ) + return; + } + else if( dcn == 4 && !swapBlue) + { + if( CvtColorIPPLoop(src_data, src_step, dst_data,dst_step, width, height, + IPPGeneralReorderFunctor(ippiLUVToRGBTab[depth], + ippiSwapChannelsC3C4RTab[depth], 2, 1, 0, depth)) ) + return; + } + } + } + } +#endif + + int blueIdx = swapBlue ? 2 : 0; + if(isLab) + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Lab2RGB_b(dcn, blueIdx, 0, 0, srgb)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Lab2RGB_f(dcn, blueIdx, 0, 0, srgb)); + } + else + { + if( depth == CV_8U ) + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Luv2RGB_b(dcn, blueIdx, 0, 0, srgb)); + else + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, Luv2RGB_f(dcn, blueIdx, 0, 0, srgb)); + } +} + +void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx) +{ + CALL_HAL(cvtTwoPlaneYUVtoBGR, cv_hal_cvtTwoPlaneYUVtoBGR, src_data, src_step, dst_data, dst_step, dst_width, dst_height, dcn, swapBlue, uIdx); + int blueIdx = swapBlue ? 2 : 0; + const uchar* uv = src_data + src_step * static_cast(dst_height); + switch(dcn*100 + blueIdx * 10 + uIdx) + { + case 300: cvtYUV420sp2RGB<0, 0> (dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 301: cvtYUV420sp2RGB<0, 1> (dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 320: cvtYUV420sp2RGB<2, 0> (dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 321: cvtYUV420sp2RGB<2, 1> (dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 400: cvtYUV420sp2RGBA<0, 0>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 401: cvtYUV420sp2RGBA<0, 1>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 420: cvtYUV420sp2RGBA<2, 0>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + case 421: cvtYUV420sp2RGBA<2, 1>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, uv); break; + default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; + }; +} + +void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx) +{ + CALL_HAL(cvtThreePlaneYUVtoBGR, cv_hal_cvtThreePlaneYUVtoBGR, src_data, src_step, dst_data, dst_step, dst_width, dst_height, dcn, swapBlue, uIdx); + const uchar* u = src_data + src_step * static_cast(dst_height); + const uchar* v = src_data + src_step * static_cast(dst_height + dst_height/4) + (dst_width/2) * ((dst_height % 4)/2); + + int ustepIdx = 0; + int vstepIdx = dst_height % 4 == 2 ? 1 : 0; + + if(uIdx == 1) { std::swap(u ,v), std::swap(ustepIdx, vstepIdx); } + int blueIdx = swapBlue ? 2 : 0; + + switch(dcn*10 + blueIdx) + { + case 30: cvtYUV420p2RGB<0>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, u, v, ustepIdx, vstepIdx); break; + case 32: cvtYUV420p2RGB<2>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, u, v, ustepIdx, vstepIdx); break; + case 40: cvtYUV420p2RGBA<0>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, u, v, ustepIdx, vstepIdx); break; + case 42: cvtYUV420p2RGBA<2>(dst_data, dst_step, dst_width, dst_height, src_step, src_data, u, v, ustepIdx, vstepIdx); break; + default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; + }; +} + +void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx) +{ + CALL_HAL(cvtBGRtoThreePlaneYUV, cv_hal_cvtBGRtoThreePlaneYUV, src_data, src_step, dst_data, dst_step, width, height, scn, swapBlue, uIdx); + int blueIdx = swapBlue ? 2 : 0; + switch(blueIdx + uIdx*10) + { + case 10: cvtRGBtoYUV420p<0, 1>(src_data, src_step, dst_data, dst_step, width, height, scn); break; + case 12: cvtRGBtoYUV420p<2, 1>(src_data, src_step, dst_data, dst_step, width, height, scn); break; + case 20: cvtRGBtoYUV420p<0, 2>(src_data, src_step, dst_data, dst_step, width, height, scn); break; + case 22: cvtRGBtoYUV420p<2, 2>(src_data, src_step, dst_data, dst_step, width, height, scn); break; + default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; + }; +} + +void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int uIdx, int ycn) +{ + CALL_HAL(cvtOnePlaneYUVtoBGR, cv_hal_cvtOnePlaneYUVtoBGR, src_data, src_step, dst_data, dst_step, width, height, dcn, swapBlue, uIdx, ycn); + int blueIdx = swapBlue ? 2 : 0; + switch(dcn*1000 + blueIdx*100 + uIdx*10 + ycn) + { + case 3000: cvtYUV422toRGB<0,0,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 3001: cvtYUV422toRGB<0,0,1>(dst_data, dst_step, src_data, src_step, width, height); break; + case 3010: cvtYUV422toRGB<0,1,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 3200: cvtYUV422toRGB<2,0,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 3201: cvtYUV422toRGB<2,0,1>(dst_data, dst_step, src_data, src_step, width, height); break; + case 3210: cvtYUV422toRGB<2,1,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4000: cvtYUV422toRGBA<0,0,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4001: cvtYUV422toRGBA<0,0,1>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4010: cvtYUV422toRGBA<0,1,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4200: cvtYUV422toRGBA<2,0,0>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4201: cvtYUV422toRGBA<2,0,1>(dst_data, dst_step, src_data, src_step, width, height); break; + case 4210: cvtYUV422toRGBA<2,1,0>(dst_data, dst_step, src_data, src_step, width, height); break; + default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; + }; +} + +void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height) +{ + CALL_HAL(cvtRGBAtoMultipliedRGBA, cv_hal_cvtRGBAtoMultipliedRGBA, src_data, src_step, dst_data, dst_step, width, height); + +#ifdef HAVE_IPP + CV_IPP_CHECK() + { + if (CvtColorIPPLoop(src_data, src_step, dst_data, dst_step, width, height, + IPPGeneralFunctor((ippiGeneralFunc)ippiAlphaPremul_8u_AC4R))) + return; + } +#endif + + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, RGBA2mRGBA()); +} + +void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height) +{ + CALL_HAL(cvtMultipliedRGBAtoRGBA, cv_hal_cvtMultipliedRGBAtoRGBA, src_data, src_step, dst_data, dst_step, width, height); + CvtColorLoop(src_data, src_step, dst_data, dst_step, width, height, mRGBA2RGBA()); +} + +}} // cv::hal:: + +// +// Helper functions +// + +inline bool isHSV(int code) +{ + switch(code) + { + case CV_HSV2BGR: case CV_HSV2RGB: case CV_HSV2BGR_FULL: case CV_HSV2RGB_FULL: + case CV_BGR2HSV: case CV_RGB2HSV: case CV_BGR2HSV_FULL: case CV_RGB2HSV_FULL: + return true; + default: + return false; + } +} + +inline bool isLab(int code) +{ + switch (code) + { + case CV_Lab2BGR: case CV_Lab2RGB: case CV_Lab2LBGR: case CV_Lab2LRGB: + case CV_BGR2Lab: case CV_RGB2Lab: case CV_LBGR2Lab: case CV_LRGB2Lab: + return true; + default: + return false; + } +} + +inline bool issRGB(int code) +{ + switch (code) + { + case CV_BGR2Lab: case CV_RGB2Lab: case CV_BGR2Luv: case CV_RGB2Luv: + case CV_Lab2BGR: case CV_Lab2RGB: case CV_Luv2BGR: case CV_Luv2RGB: + return true; + default: + return false; + } +} + +inline bool swapBlue(int code) +{ + switch (code) + { + case CV_BGR2BGRA: case CV_BGRA2BGR: + case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_BGRA2BGR565: case CV_BGRA2BGR555: + case CV_BGR5652BGR: case CV_BGR5552BGR: case CV_BGR5652BGRA: case CV_BGR5552BGRA: + case CV_BGR2GRAY: case CV_BGRA2GRAY: + case CV_BGR2YCrCb: case CV_BGR2YUV: + case CV_YCrCb2BGR: case CV_YUV2BGR: + case CV_BGR2XYZ: case CV_XYZ2BGR: + case CV_BGR2HSV: case CV_BGR2HLS: case CV_BGR2HSV_FULL: case CV_BGR2HLS_FULL: + case CV_YUV2BGR_YV12: case CV_YUV2BGRA_YV12: case CV_YUV2BGR_IYUV: case CV_YUV2BGRA_IYUV: + case CV_YUV2BGR_NV21: case CV_YUV2BGRA_NV21: case CV_YUV2BGR_NV12: case CV_YUV2BGRA_NV12: + case CV_Lab2BGR: case CV_Luv2BGR: case CV_Lab2LBGR: case CV_Luv2LBGR: + case CV_BGR2Lab: case CV_BGR2Luv: case CV_LBGR2Lab: case CV_LBGR2Luv: + case CV_HSV2BGR: case CV_HLS2BGR: case CV_HSV2BGR_FULL: case CV_HLS2BGR_FULL: + case CV_YUV2BGR_UYVY: case CV_YUV2BGRA_UYVY: case CV_YUV2BGR_YUY2: + case CV_YUV2BGRA_YUY2: case CV_YUV2BGR_YVYU: case CV_YUV2BGRA_YVYU: + case CV_BGR2YUV_IYUV: case CV_BGRA2YUV_IYUV: case CV_BGR2YUV_YV12: case CV_BGRA2YUV_YV12: + return false; + default: + return true; + } +} + +inline bool isFullRange(int code) +{ + switch (code) + { + case CV_BGR2HSV_FULL: case CV_RGB2HSV_FULL: case CV_BGR2HLS_FULL: case CV_RGB2HLS_FULL: + case CV_HSV2BGR_FULL: case CV_HSV2RGB_FULL: case CV_HLS2BGR_FULL: case CV_HLS2RGB_FULL: + return true; + default: + return false; + } } ////////////////////////////////////////////////////////////////////////////////////////// @@ -7925,7 +8389,7 @@ static bool ipp_cvtColor( Mat &src, OutputArray _dst, int code, int dcn ) void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) { int stype = _src.type(); - int scn = CV_MAT_CN(stype), depth = CV_MAT_DEPTH(stype), bidx; + int scn = CV_MAT_CN(stype), depth = CV_MAT_DEPTH(stype), uidx, gbits, ycn; CV_OCL_RUN( _src.dims() <= 2 && _dst.isUMat() && !(depth == CV_8U && (code == CV_Luv2BGR || code == CV_Luv2RGB)), ocl_cvtColor(_src, _dst, code, dcn) ) @@ -7934,95 +8398,55 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) Size sz = src.size(); CV_Assert( depth == CV_8U || depth == CV_16U || depth == CV_32F ); - CV_IPP_RUN(true, ipp_cvtColor(src, _dst, code, dcn)); - switch( code ) { case CV_BGR2BGRA: case CV_RGB2BGRA: case CV_BGRA2BGR: case CV_RGBA2BGR: case CV_RGB2BGR: case CV_BGRA2RGBA: CV_Assert( scn == 3 || scn == 4 ); dcn = code == CV_BGR2BGRA || code == CV_RGB2BGRA || code == CV_BGRA2RGBA ? 4 : 3; - bidx = code == CV_BGR2BGRA || code == CV_BGRA2BGR ? 0 : 2; - _dst.create( sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( depth == CV_8U ) - { -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtBGR2RGB(src, dst, bidx)) - break; -#endif - CvtColorLoop(src, dst, RGB2RGB(scn, dcn, bidx)); - } - else if( depth == CV_16U ) - CvtColorLoop(src, dst, RGB2RGB(scn, dcn, bidx)); - else - CvtColorLoop(src, dst, RGB2RGB(scn, dcn, bidx)); + hal::cvtBGRtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, scn, dcn, swapBlue(code)); break; case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_RGB2BGR565: case CV_RGB2BGR555: case CV_BGRA2BGR565: case CV_BGRA2BGR555: case CV_RGBA2BGR565: case CV_RGBA2BGR555: CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U ); + gbits = code == CV_BGR2BGR565 || code == CV_RGB2BGR565 || + code == CV_BGRA2BGR565 || code == CV_RGBA2BGR565 ? 6 : 5; _dst.create(sz, CV_8UC2); dst = _dst.getMat(); - -#ifdef HAVE_TEGRA_OPTIMIZATION - if(code == CV_BGR2BGR565 || code == CV_BGRA2BGR565 || code == CV_RGB2BGR565 || code == CV_RGBA2BGR565) - if(tegra::useTegra() && tegra::cvtRGB2RGB565(src, dst, code == CV_RGB2BGR565 || code == CV_RGBA2BGR565 ? 0 : 2)) - break; -#endif - - CvtColorLoop(src, dst, RGB2RGB5x5(scn, - code == CV_BGR2BGR565 || code == CV_BGR2BGR555 || - code == CV_BGRA2BGR565 || code == CV_BGRA2BGR555 ? 0 : 2, - code == CV_BGR2BGR565 || code == CV_RGB2BGR565 || - code == CV_BGRA2BGR565 || code == CV_RGBA2BGR565 ? 6 : 5 // green bits - )); + hal::cvtBGRtoBGR5x5(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + scn, swapBlue(code), gbits); break; case CV_BGR5652BGR: case CV_BGR5552BGR: case CV_BGR5652RGB: case CV_BGR5552RGB: case CV_BGR5652BGRA: case CV_BGR5552BGRA: case CV_BGR5652RGBA: case CV_BGR5552RGBA: if(dcn <= 0) dcn = (code==CV_BGR5652BGRA || code==CV_BGR5552BGRA || code==CV_BGR5652RGBA || code==CV_BGR5552RGBA) ? 4 : 3; CV_Assert( (dcn == 3 || dcn == 4) && scn == 2 && depth == CV_8U ); + gbits = code == CV_BGR5652BGR || code == CV_BGR5652RGB || + code == CV_BGR5652BGRA || code == CV_BGR5652RGBA ? 6 : 5; _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - CvtColorLoop(src, dst, RGB5x52RGB(dcn, - code == CV_BGR5652BGR || code == CV_BGR5552BGR || - code == CV_BGR5652BGRA || code == CV_BGR5552BGRA ? 0 : 2, // blue idx - code == CV_BGR5652BGR || code == CV_BGR5652RGB || - code == CV_BGR5652BGRA || code == CV_BGR5652RGBA ? 6 : 5 // green bits - )); + hal::cvtBGR5x5toBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + dcn, swapBlue(code), gbits); break; case CV_BGR2GRAY: case CV_BGRA2GRAY: case CV_RGB2GRAY: case CV_RGBA2GRAY: CV_Assert( scn == 3 || scn == 4 ); _dst.create(sz, CV_MAKETYPE(depth, 1)); dst = _dst.getMat(); - - bidx = code == CV_BGR2GRAY || code == CV_BGRA2GRAY ? 0 : 2; - - if( depth == CV_8U ) - { -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtRGB2Gray(src, dst, bidx)) - break; -#endif - CvtColorLoop(src, dst, RGB2Gray(scn, bidx, 0)); - } - else if( depth == CV_16U ) - CvtColorLoop(src, dst, RGB2Gray(scn, bidx, 0)); - else - CvtColorLoop(src, dst, RGB2Gray(scn, bidx, 0)); + hal::cvtBGRtoGray(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, scn, swapBlue(code)); break; case CV_BGR5652GRAY: case CV_BGR5552GRAY: CV_Assert( scn == 2 && depth == CV_8U ); + gbits = code == CV_BGR5652GRAY ? 6 : 5; _dst.create(sz, CV_8UC1); dst = _dst.getMat(); - - CvtColorLoop(src, dst, RGB5x52Gray(code == CV_BGR5652GRAY ? 6 : 5)); + hal::cvtBGR5x5toGray(src.data, src.step, dst.data, dst.step, src.cols, src.rows, gbits); break; case CV_GRAY2BGR: case CV_GRAY2BGRA: @@ -8030,235 +8454,87 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) CV_Assert( scn == 1 && (dcn == 3 || dcn == 4)); _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( depth == CV_8U ) - { -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtGray2RGB(src, dst)) - break; -#endif - CvtColorLoop(src, dst, Gray2RGB(dcn)); - } - else if( depth == CV_16U ) - CvtColorLoop(src, dst, Gray2RGB(dcn)); - else - CvtColorLoop(src, dst, Gray2RGB(dcn)); + hal::cvtGraytoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, depth, dcn); break; case CV_GRAY2BGR565: case CV_GRAY2BGR555: CV_Assert( scn == 1 && depth == CV_8U ); + gbits = code == CV_GRAY2BGR565 ? 6 : 5; _dst.create(sz, CV_8UC2); dst = _dst.getMat(); - - CvtColorLoop(src, dst, Gray2RGB5x5(code == CV_GRAY2BGR565 ? 6 : 5)); + hal::cvtGraytoBGR5x5(src.data, src.step, dst.data, dst.step, src.cols, src.rows, gbits); break; case CV_BGR2YCrCb: case CV_RGB2YCrCb: case CV_BGR2YUV: case CV_RGB2YUV: - { CV_Assert( scn == 3 || scn == 4 ); - bidx = code == CV_BGR2YCrCb || code == CV_BGR2YUV ? 0 : 2; - static const float yuv_f[] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f }; - static const int yuv_i[] = { B2Y, G2Y, R2Y, 8061, 14369 }; - const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f; - const int* coeffs_i = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_i; - _dst.create(sz, CV_MAKETYPE(depth, 3)); dst = _dst.getMat(); - - if( depth == CV_8U ) - { -#ifdef HAVE_TEGRA_OPTIMIZATION - if((code == CV_RGB2YCrCb || code == CV_BGR2YCrCb) && tegra::useTegra() && tegra::cvtRGB2YCrCb(src, dst, bidx)) - break; -#endif - CvtColorLoop(src, dst, RGB2YCrCb_i(scn, bidx, coeffs_i)); - } - else if( depth == CV_16U ) - CvtColorLoop(src, dst, RGB2YCrCb_i(scn, bidx, coeffs_i)); - else - CvtColorLoop(src, dst, RGB2YCrCb_f(scn, bidx, coeffs_f)); - } + hal::cvtBGRtoYUV(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, scn, swapBlue(code), code == CV_BGR2YCrCb || code == CV_RGB2YCrCb); break; case CV_YCrCb2BGR: case CV_YCrCb2RGB: case CV_YUV2BGR: case CV_YUV2RGB: - { if( dcn <= 0 ) dcn = 3; CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); - bidx = code == CV_YCrCb2BGR || code == CV_YUV2BGR ? 0 : 2; - static const float yuv_f[] = { 2.032f, -0.395f, -0.581f, 1.140f }; - static const int yuv_i[] = { 33292, -6472, -9519, 18678 }; - const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f; - const int* coeffs_i = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_i; - _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( depth == CV_8U ) - CvtColorLoop(src, dst, YCrCb2RGB_i(dcn, bidx, coeffs_i)); - else if( depth == CV_16U ) - CvtColorLoop(src, dst, YCrCb2RGB_i(dcn, bidx, coeffs_i)); - else - CvtColorLoop(src, dst, YCrCb2RGB_f(dcn, bidx, coeffs_f)); - } + hal::cvtYUVtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, dcn, swapBlue(code), code == CV_YCrCb2BGR || code == CV_YCrCb2RGB); break; case CV_BGR2XYZ: case CV_RGB2XYZ: CV_Assert( scn == 3 || scn == 4 ); - bidx = code == CV_BGR2XYZ ? 0 : 2; - _dst.create(sz, CV_MAKETYPE(depth, 3)); dst = _dst.getMat(); - - if( depth == CV_8U ) - CvtColorLoop(src, dst, RGB2XYZ_i(scn, bidx, 0)); - else if( depth == CV_16U ) - CvtColorLoop(src, dst, RGB2XYZ_i(scn, bidx, 0)); - else - CvtColorLoop(src, dst, RGB2XYZ_f(scn, bidx, 0)); + hal::cvtBGRtoXYZ(src.data, src.step, dst.data, dst.step, src.cols, src.rows, depth, scn, swapBlue(code)); break; case CV_XYZ2BGR: case CV_XYZ2RGB: if( dcn <= 0 ) dcn = 3; CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); - bidx = code == CV_XYZ2BGR ? 0 : 2; - _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( depth == CV_8U ) - CvtColorLoop(src, dst, XYZ2RGB_i(dcn, bidx, 0)); - else if( depth == CV_16U ) - CvtColorLoop(src, dst, XYZ2RGB_i(dcn, bidx, 0)); - else - CvtColorLoop(src, dst, XYZ2RGB_f(dcn, bidx, 0)); + hal::cvtXYZtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, depth, dcn, swapBlue(code)); break; case CV_BGR2HSV: case CV_RGB2HSV: case CV_BGR2HSV_FULL: case CV_RGB2HSV_FULL: case CV_BGR2HLS: case CV_RGB2HLS: case CV_BGR2HLS_FULL: case CV_RGB2HLS_FULL: - { CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) ); - bidx = code == CV_BGR2HSV || code == CV_BGR2HLS || - code == CV_BGR2HSV_FULL || code == CV_BGR2HLS_FULL ? 0 : 2; - int hrange = depth == CV_32F ? 360 : code == CV_BGR2HSV || code == CV_RGB2HSV || - code == CV_BGR2HLS || code == CV_RGB2HLS ? 180 : 256; - _dst.create(sz, CV_MAKETYPE(depth, 3)); dst = _dst.getMat(); - - if( code == CV_BGR2HSV || code == CV_RGB2HSV || - code == CV_BGR2HSV_FULL || code == CV_RGB2HSV_FULL ) - { -#ifdef HAVE_TEGRA_OPTIMIZATION - if(tegra::useTegra() && tegra::cvtRGB2HSV(src, dst, bidx, hrange)) - break; -#endif - if( depth == CV_8U ) - CvtColorLoop(src, dst, RGB2HSV_b(scn, bidx, hrange)); - else - CvtColorLoop(src, dst, RGB2HSV_f(scn, bidx, (float)hrange)); - } - else - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, RGB2HLS_b(scn, bidx, hrange)); - else - CvtColorLoop(src, dst, RGB2HLS_f(scn, bidx, (float)hrange)); - } - } + hal::cvtBGRtoHSV(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, scn, swapBlue(code), isFullRange(code), isHSV(code)); break; case CV_HSV2BGR: case CV_HSV2RGB: case CV_HSV2BGR_FULL: case CV_HSV2RGB_FULL: case CV_HLS2BGR: case CV_HLS2RGB: case CV_HLS2BGR_FULL: case CV_HLS2RGB_FULL: - { if( dcn <= 0 ) dcn = 3; CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) ); - bidx = code == CV_HSV2BGR || code == CV_HLS2BGR || - code == CV_HSV2BGR_FULL || code == CV_HLS2BGR_FULL ? 0 : 2; - int hrange = depth == CV_32F ? 360 : code == CV_HSV2BGR || code == CV_HSV2RGB || - code == CV_HLS2BGR || code == CV_HLS2RGB ? 180 : 255; - _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( code == CV_HSV2BGR || code == CV_HSV2RGB || - code == CV_HSV2BGR_FULL || code == CV_HSV2RGB_FULL ) - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, HSV2RGB_b(dcn, bidx, hrange)); - else - CvtColorLoop(src, dst, HSV2RGB_f(dcn, bidx, (float)hrange)); - } - else - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, HLS2RGB_b(dcn, bidx, hrange)); - else - CvtColorLoop(src, dst, HLS2RGB_f(dcn, bidx, (float)hrange)); - } - } + hal::cvtHSVtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, dcn, swapBlue(code), isFullRange(code), isHSV(code)); break; case CV_BGR2Lab: case CV_RGB2Lab: case CV_LBGR2Lab: case CV_LRGB2Lab: case CV_BGR2Luv: case CV_RGB2Luv: case CV_LBGR2Luv: case CV_LRGB2Luv: - { CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) ); - bidx = code == CV_BGR2Lab || code == CV_BGR2Luv || - code == CV_LBGR2Lab || code == CV_LBGR2Luv ? 0 : 2; - bool srgb = code == CV_BGR2Lab || code == CV_RGB2Lab || - code == CV_BGR2Luv || code == CV_RGB2Luv; - _dst.create(sz, CV_MAKETYPE(depth, 3)); dst = _dst.getMat(); - - if( code == CV_BGR2Lab || code == CV_RGB2Lab || - code == CV_LBGR2Lab || code == CV_LRGB2Lab ) - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, RGB2Lab_b(scn, bidx, 0, 0, srgb)); - else - CvtColorLoop(src, dst, RGB2Lab_f(scn, bidx, 0, 0, srgb)); - } - else - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, RGB2Luv_b(scn, bidx, 0, 0, srgb)); - else - CvtColorLoop(src, dst, RGB2Luv_f(scn, bidx, 0, 0, srgb)); - } - } + hal::cvtBGRtoLab(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, scn, swapBlue(code), isLab(code), issRGB(code)); break; case CV_Lab2BGR: case CV_Lab2RGB: case CV_Lab2LBGR: case CV_Lab2LRGB: case CV_Luv2BGR: case CV_Luv2RGB: case CV_Luv2LBGR: case CV_Luv2LRGB: - { if( dcn <= 0 ) dcn = 3; CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) ); - bidx = code == CV_Lab2BGR || code == CV_Luv2BGR || - code == CV_Lab2LBGR || code == CV_Luv2LBGR ? 0 : 2; - bool srgb = code == CV_Lab2BGR || code == CV_Lab2RGB || - code == CV_Luv2BGR || code == CV_Luv2RGB; - _dst.create(sz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); - - if( code == CV_Lab2BGR || code == CV_Lab2RGB || - code == CV_Lab2LBGR || code == CV_Lab2LRGB ) - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, Lab2RGB_b(dcn, bidx, 0, 0, srgb)); - else - CvtColorLoop(src, dst, Lab2RGB_f(dcn, bidx, 0, 0, srgb)); - } - else - { - if( depth == CV_8U ) - CvtColorLoop(src, dst, Luv2RGB_b(dcn, bidx, 0, 0, srgb)); - else - CvtColorLoop(src, dst, Luv2RGB_f(dcn, bidx, 0, 0, srgb)); - } - } + hal::cvtLabtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + depth, dcn, swapBlue(code), isLab(code), issRGB(code)); break; case CV_BayerBG2GRAY: case CV_BayerGB2GRAY: case CV_BayerRG2GRAY: case CV_BayerGR2GRAY: @@ -8270,76 +8546,31 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) case CV_YUV2BGR_NV21: case CV_YUV2RGB_NV21: case CV_YUV2BGR_NV12: case CV_YUV2RGB_NV12: case CV_YUV2BGRA_NV21: case CV_YUV2RGBA_NV21: case CV_YUV2BGRA_NV12: case CV_YUV2RGBA_NV12: - { - // http://www.fourcc.org/yuv.php#NV21 == yuv420sp -> a plane of 8 bit Y samples followed by an interleaved V/U plane containing 8 bit 2x2 subsampled chroma samples - // http://www.fourcc.org/yuv.php#NV12 -> a plane of 8 bit Y samples followed by an interleaved U/V plane containing 8 bit 2x2 subsampled colour difference samples - - if (dcn <= 0) dcn = (code==CV_YUV420sp2BGRA || code==CV_YUV420sp2RGBA || code==CV_YUV2BGRA_NV12 || code==CV_YUV2RGBA_NV12) ? 4 : 3; - const int bIdx = (code==CV_YUV2BGR_NV21 || code==CV_YUV2BGRA_NV21 || code==CV_YUV2BGR_NV12 || code==CV_YUV2BGRA_NV12) ? 0 : 2; - const int uIdx = (code==CV_YUV2BGR_NV21 || code==CV_YUV2BGRA_NV21 || code==CV_YUV2RGB_NV21 || code==CV_YUV2RGBA_NV21) ? 1 : 0; - - CV_Assert( dcn == 3 || dcn == 4 ); - CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U ); - - Size dstSz(sz.width, sz.height * 2 / 3); - _dst.create(dstSz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - int srcstep = (int)src.step; - const uchar* y = src.ptr(); - const uchar* uv = y + srcstep * dstSz.height; - - switch(dcn*100 + bIdx * 10 + uIdx) - { - case 300: cvtYUV420sp2RGB<0, 0> (dst, srcstep, y, uv); break; - case 301: cvtYUV420sp2RGB<0, 1> (dst, srcstep, y, uv); break; - case 320: cvtYUV420sp2RGB<2, 0> (dst, srcstep, y, uv); break; - case 321: cvtYUV420sp2RGB<2, 1> (dst, srcstep, y, uv); break; - case 400: cvtYUV420sp2RGBA<0, 0>(dst, srcstep, y, uv); break; - case 401: cvtYUV420sp2RGBA<0, 1>(dst, srcstep, y, uv); break; - case 420: cvtYUV420sp2RGBA<2, 0>(dst, srcstep, y, uv); break; - case 421: cvtYUV420sp2RGBA<2, 1>(dst, srcstep, y, uv); break; - default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; - }; - } + // http://www.fourcc.org/yuv.php#NV21 == yuv420sp -> a plane of 8 bit Y samples followed by an interleaved V/U plane containing 8 bit 2x2 subsampled chroma samples + // http://www.fourcc.org/yuv.php#NV12 -> a plane of 8 bit Y samples followed by an interleaved U/V plane containing 8 bit 2x2 subsampled colour difference samples + if (dcn <= 0) dcn = (code==CV_YUV420sp2BGRA || code==CV_YUV420sp2RGBA || code==CV_YUV2BGRA_NV12 || code==CV_YUV2RGBA_NV12) ? 4 : 3; + uidx = (code==CV_YUV2BGR_NV21 || code==CV_YUV2BGRA_NV21 || code==CV_YUV2RGB_NV21 || code==CV_YUV2RGBA_NV21) ? 1 : 0; + CV_Assert( dcn == 3 || dcn == 4 ); + CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U ); + _dst.create(Size(sz.width, sz.height * 2 / 3), CV_MAKETYPE(depth, dcn)); + dst = _dst.getMat(); + hal::cvtTwoPlaneYUVtoBGR(src.data, src.step, dst.data, dst.step, dst.cols, dst.rows, + dcn, swapBlue(code), uidx); break; case CV_YUV2BGR_YV12: case CV_YUV2RGB_YV12: case CV_YUV2BGRA_YV12: case CV_YUV2RGBA_YV12: case CV_YUV2BGR_IYUV: case CV_YUV2RGB_IYUV: case CV_YUV2BGRA_IYUV: case CV_YUV2RGBA_IYUV: - { - //http://www.fourcc.org/yuv.php#YV12 == yuv420p -> It comprises an NxM Y plane followed by (N/2)x(M/2) V and U planes. - //http://www.fourcc.org/yuv.php#IYUV == I420 -> It comprises an NxN Y plane followed by (N/2)x(N/2) U and V planes - - if (dcn <= 0) dcn = (code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12 || code==CV_YUV2RGBA_IYUV || code==CV_YUV2BGRA_IYUV) ? 4 : 3; - const int bIdx = (code==CV_YUV2BGR_YV12 || code==CV_YUV2BGRA_YV12 || code==CV_YUV2BGR_IYUV || code==CV_YUV2BGRA_IYUV) ? 0 : 2; - const int uIdx = (code==CV_YUV2BGR_YV12 || code==CV_YUV2RGB_YV12 || code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12) ? 1 : 0; - - CV_Assert( dcn == 3 || dcn == 4 ); - CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U ); - - Size dstSz(sz.width, sz.height * 2 / 3); - _dst.create(dstSz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - int srcstep = (int)src.step; - const uchar* y = src.ptr(); - const uchar* u = y + srcstep * dstSz.height; - const uchar* v = y + srcstep * (dstSz.height + dstSz.height/4) + (dstSz.width/2) * ((dstSz.height % 4)/2); - - int ustepIdx = 0; - int vstepIdx = dstSz.height % 4 == 2 ? 1 : 0; - - if(uIdx == 1) { std::swap(u ,v), std::swap(ustepIdx, vstepIdx); } - - switch(dcn*10 + bIdx) - { - case 30: cvtYUV420p2RGB<0>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break; - case 32: cvtYUV420p2RGB<2>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break; - case 40: cvtYUV420p2RGBA<0>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break; - case 42: cvtYUV420p2RGBA<2>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break; - default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; - }; - } + //http://www.fourcc.org/yuv.php#YV12 == yuv420p -> It comprises an NxM Y plane followed by (N/2)x(M/2) V and U planes. + //http://www.fourcc.org/yuv.php#IYUV == I420 -> It comprises an NxN Y plane followed by (N/2)x(N/2) U and V planes + if (dcn <= 0) dcn = (code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12 || code==CV_YUV2RGBA_IYUV || code==CV_YUV2BGRA_IYUV) ? 4 : 3; + uidx = (code==CV_YUV2BGR_YV12 || code==CV_YUV2RGB_YV12 || code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12) ? 1 : 0; + CV_Assert( dcn == 3 || dcn == 4 ); + CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U ); + _dst.create(Size(sz.width, sz.height * 2 / 3), CV_MAKETYPE(depth, dcn)); + dst = _dst.getMat(); + hal::cvtThreePlaneYUVtoBGR(src.data, src.step, dst.data, dst.step, dst.cols, dst.rows, + dcn, swapBlue(code), uidx); break; + case CV_YUV2GRAY_420: { if (dcn <= 0) dcn = 1; @@ -8350,74 +8581,41 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) Size dstSz(sz.width, sz.height * 2 / 3); _dst.create(dstSz, CV_MAKETYPE(depth, dcn)); dst = _dst.getMat(); +#ifdef HAVE_IPP + if (ippStsNoErr == ippiCopy_8u_C1R(src.data, (int)src.step, dst.data, (int)dst.step, + ippiSize(dstSz.width, dstSz.height))) + break; +#endif src(Range(0, dstSz.height), Range::all()).copyTo(dst); } break; case CV_RGB2YUV_YV12: case CV_BGR2YUV_YV12: case CV_RGBA2YUV_YV12: case CV_BGRA2YUV_YV12: case CV_RGB2YUV_IYUV: case CV_BGR2YUV_IYUV: case CV_RGBA2YUV_IYUV: case CV_BGRA2YUV_IYUV: - { - if (dcn <= 0) dcn = 1; - const int bIdx = (code == CV_BGR2YUV_IYUV || code == CV_BGRA2YUV_IYUV || code == CV_BGR2YUV_YV12 || code == CV_BGRA2YUV_YV12) ? 0 : 2; - const int uIdx = (code == CV_BGR2YUV_IYUV || code == CV_BGRA2YUV_IYUV || code == CV_RGB2YUV_IYUV || code == CV_RGBA2YUV_IYUV) ? 1 : 2; - - CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U ); - CV_Assert( dcn == 1 ); - CV_Assert( sz.width % 2 == 0 && sz.height % 2 == 0 ); - - Size dstSz(sz.width, sz.height / 2 * 3); - _dst.create(dstSz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - switch(bIdx + uIdx*10) - { - case 10: cvtRGBtoYUV420p<0, 1>(src, dst); break; - case 12: cvtRGBtoYUV420p<2, 1>(src, dst); break; - case 20: cvtRGBtoYUV420p<0, 2>(src, dst); break; - case 22: cvtRGBtoYUV420p<2, 2>(src, dst); break; - default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; - }; - } + if (dcn <= 0) dcn = 1; + uidx = (code == CV_BGR2YUV_IYUV || code == CV_BGRA2YUV_IYUV || code == CV_RGB2YUV_IYUV || code == CV_RGBA2YUV_IYUV) ? 1 : 2; + CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U ); + CV_Assert( dcn == 1 ); + CV_Assert( sz.width % 2 == 0 && sz.height % 2 == 0 ); + _dst.create(Size(sz.width, sz.height / 2 * 3), CV_MAKETYPE(depth, dcn)); + dst = _dst.getMat(); + hal::cvtBGRtoThreePlaneYUV(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + scn, swapBlue(code), uidx); break; case CV_YUV2RGB_UYVY: case CV_YUV2BGR_UYVY: case CV_YUV2RGBA_UYVY: case CV_YUV2BGRA_UYVY: case CV_YUV2RGB_YUY2: case CV_YUV2BGR_YUY2: case CV_YUV2RGB_YVYU: case CV_YUV2BGR_YVYU: case CV_YUV2RGBA_YUY2: case CV_YUV2BGRA_YUY2: case CV_YUV2RGBA_YVYU: case CV_YUV2BGRA_YVYU: - { - //http://www.fourcc.org/yuv.php#UYVY - //http://www.fourcc.org/yuv.php#YUY2 - //http://www.fourcc.org/yuv.php#YVYU - - if (dcn <= 0) dcn = (code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY || code==CV_YUV2RGBA_YUY2 || code==CV_YUV2BGRA_YUY2 || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 4 : 3; - const int bIdx = (code==CV_YUV2BGR_UYVY || code==CV_YUV2BGRA_UYVY || code==CV_YUV2BGR_YUY2 || code==CV_YUV2BGRA_YUY2 || code==CV_YUV2BGR_YVYU || code==CV_YUV2BGRA_YVYU) ? 0 : 2; - const int ycn = (code==CV_YUV2RGB_UYVY || code==CV_YUV2BGR_UYVY || code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY) ? 1 : 0; - const int uIdx = (code==CV_YUV2RGB_YVYU || code==CV_YUV2BGR_YVYU || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 1 : 0; - - CV_Assert( dcn == 3 || dcn == 4 ); - CV_Assert( scn == 2 && depth == CV_8U ); - - _dst.create(sz, CV_8UC(dcn)); - dst = _dst.getMat(); - - switch(dcn*1000 + bIdx*100 + uIdx*10 + ycn) - { - case 3000: cvtYUV422toRGB<0,0,0>(dst, (int)src.step, src.ptr()); break; - case 3001: cvtYUV422toRGB<0,0,1>(dst, (int)src.step, src.ptr()); break; - case 3010: cvtYUV422toRGB<0,1,0>(dst, (int)src.step, src.ptr()); break; - case 3011: cvtYUV422toRGB<0,1,1>(dst, (int)src.step, src.ptr()); break; - case 3200: cvtYUV422toRGB<2,0,0>(dst, (int)src.step, src.ptr()); break; - case 3201: cvtYUV422toRGB<2,0,1>(dst, (int)src.step, src.ptr()); break; - case 3210: cvtYUV422toRGB<2,1,0>(dst, (int)src.step, src.ptr()); break; - case 3211: cvtYUV422toRGB<2,1,1>(dst, (int)src.step, src.ptr()); break; - case 4000: cvtYUV422toRGBA<0,0,0>(dst, (int)src.step, src.ptr()); break; - case 4001: cvtYUV422toRGBA<0,0,1>(dst, (int)src.step, src.ptr()); break; - case 4010: cvtYUV422toRGBA<0,1,0>(dst, (int)src.step, src.ptr()); break; - case 4011: cvtYUV422toRGBA<0,1,1>(dst, (int)src.step, src.ptr()); break; - case 4200: cvtYUV422toRGBA<2,0,0>(dst, (int)src.step, src.ptr()); break; - case 4201: cvtYUV422toRGBA<2,0,1>(dst, (int)src.step, src.ptr()); break; - case 4210: cvtYUV422toRGBA<2,1,0>(dst, (int)src.step, src.ptr()); break; - case 4211: cvtYUV422toRGBA<2,1,1>(dst, (int)src.step, src.ptr()); break; - default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break; - }; - } + //http://www.fourcc.org/yuv.php#UYVY + //http://www.fourcc.org/yuv.php#YUY2 + //http://www.fourcc.org/yuv.php#YVYU + if (dcn <= 0) dcn = (code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY || code==CV_YUV2RGBA_YUY2 || code==CV_YUV2BGRA_YUY2 || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 4 : 3; + ycn = (code==CV_YUV2RGB_UYVY || code==CV_YUV2BGR_UYVY || code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY) ? 1 : 0; + uidx = (code==CV_YUV2RGB_YVYU || code==CV_YUV2BGR_YVYU || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 1 : 0; + CV_Assert( dcn == 3 || dcn == 4 ); + CV_Assert( scn == 2 && depth == CV_8U ); + _dst.create(sz, CV_8UC(dcn)); + dst = _dst.getMat(); + hal::cvtOnePlaneYUVtoBGR(src.data, src.step, dst.data, dst.step, src.cols, src.rows, + dcn, swapBlue(code), uidx, ycn); break; case CV_YUV2GRAY_UYVY: case CV_YUV2GRAY_YUY2: { @@ -8431,42 +8629,22 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) } break; case CV_RGBA2mRGBA: - { - if (dcn <= 0) dcn = 4; - CV_Assert( scn == 4 && dcn == 4 ); - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( depth == CV_8U ) - { - CvtColorLoop(src, dst, RGBA2mRGBA()); - } - else - { - CV_Error( CV_StsBadArg, "Unsupported image depth" ); - } - } + if (dcn <= 0) dcn = 4; + CV_Assert( scn == 4 && dcn == 4 && depth == CV_8U ); + _dst.create(sz, CV_MAKETYPE(depth, dcn)); + dst = _dst.getMat(); + hal::cvtRGBAtoMultipliedRGBA(src.data, src.step, dst.data, dst.step, src.cols, src.rows); break; case CV_mRGBA2RGBA: - { - if (dcn <= 0) dcn = 4; - CV_Assert( scn == 4 && dcn == 4 ); - - _dst.create(sz, CV_MAKETYPE(depth, dcn)); - dst = _dst.getMat(); - - if( depth == CV_8U ) - CvtColorLoop(src, dst, mRGBA2RGBA()); - else - { - CV_Error( CV_StsBadArg, "Unsupported image depth" ); - } - } + if (dcn <= 0) dcn = 4; + CV_Assert( scn == 4 && dcn == 4 && depth == CV_8U ); + _dst.create(sz, CV_MAKETYPE(depth, dcn)); + dst = _dst.getMat(); + hal::cvtMultipliedRGBAtoRGBA(src.data, src.step, dst.data, dst.step, src.cols, src.rows); break; default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); - } + } } CV_IMPL void diff --git a/modules/imgproc/src/hal_replacement.hpp b/modules/imgproc/src/hal_replacement.hpp index e42cc44ad9..f41e1acc95 100644 --- a/modules/imgproc/src/hal_replacement.hpp +++ b/modules/imgproc/src/hal_replacement.hpp @@ -298,6 +298,294 @@ inline int hal_ni_warpPerspectve(int src_type, const uchar *src_data, size_t src #define cv_hal_warpPerspective hal_ni_warpPerspectve //! @endcond +/** + @brief hal_cvtBGRtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U, CV_32F) + @param scn source image channels (3 or 4) + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R channels will be swapped (BGR->RGB or RGB->BGR) + Convert between BGR, BGRA, RGB and RGBA image formats. + */ +inline int hal_ni_cvtBGRtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, int dcn, bool swapBlue) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoBGR5x5 + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + @param greenBits number of bits for green channel (5 or 6) + Convert from BGR, BGRA, RGB and RGBA to packed BGR or RGB (16 bits per pixel, 555 or 565). + Support only CV_8U images (input 3 or 4 channels, output 2 channels). + */ +inline int hal_ni_cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int scn, bool swapBlue, int greenBits) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGR5x5toBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param greenBits number of bits for green channel (5 or 6) + Convert from packed BGR or RGB (16 bits per pixel, 555 or 565) to BGR, BGRA, RGB and RGBA. + Support only CV_8U images (input 2 channels, output 3 or 4 channels). + */ +inline int hal_ni_cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int dcn, bool swapBlue, int greenBits) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoGray + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + Convert from BGR, BGRA, RGB or RGBA to 1-channel gray. + */ +inline int hal_ni_cvtBGRtoGray(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, bool swapBlue) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtGraytoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param dcn destination image channels (3 or 4) + Convert from 1-channel gray to BGR, RGB, RGBA or BGRA. + */ +inline int hal_ni_cvtGraytoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int dcn) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGR5x5toGray + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param greenBits number of bits for green channel (5 or 6) + Convert from packed BGR (16 bits per pixel, 555 or 565) to 1-channel gray. + Support only CV_8U images. + */ +inline int hal_ni_cvtBGR5x5toGray(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int greenBits) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtGraytoBGR5x5 + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param greenBits number of bits for green channel (5 or 6) + Convert from 1-channel gray to packed BGR (16 bits per pixel, 555 or 565). + Support only CV_8U images. + */ +inline int hal_ni_cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int greenBits) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoYUV + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + @param isCbCr if set to true write output in YCbCr format + Convert from BGR, RGB, BGRA or RGBA to YUV or YCbCr. + */ +inline int hal_ni_cvtBGRtoYUV(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, bool swapBlue, bool isCbCr) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtYUVtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param isCbCr if set to true treat source as YCbCr + Convert from YUV or YCbCr to BGR, RGB, BGRA or RGBA. + */ +inline int hal_ni_cvtYUVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int dcn, bool swapBlue, bool isCbCr) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoXYZ + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + Convert from BGR, RGB, BGRA or RGBA to XYZ. + */ +inline int hal_ni_cvtBGRtoXYZ(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, bool swapBlue) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtXYZtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U, CV_16U or CV_32F) + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + Convert from XYZ to BGR, RGB, BGRA or RGBA. + */ +inline int hal_ni_cvtXYZtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int dcn, bool swapBlue) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoHSV + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U or CV_32F) + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + @param isFullRange if set to true write hue in range 0-255 (0-360 for float) otherwise in range 0-180 + @param isHSV if set to true write HSV otherwise HSL + Convert from BGR, RGB, BGRA or RGBA to HSV or HSL. + */ +inline int hal_ni_cvtBGRtoHSV(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtHSVtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U or CV_32F) + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param isFullRange if set to true read hue in range 0-255 (0-360 for float) otherwise in range 0-180 + @param isHSV if set to true treat source as HSV otherwise HSL + Convert from HSV or HSL to BGR, RGB, BGRA or RGBA. + */ +inline int hal_ni_cvtHSVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoLab + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U or CV_32F) + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + @param isLab if set to true write Lab otherwise Luv + @param srgb if set to true use sRGB gamma correction + Convert from BGR, RGB, BGRA or RGBA to Lab or Luv. + */ +inline int hal_ni_cvtBGRtoLab(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int scn, bool swapBlue, bool isLab, bool srgb) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtLabtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param depth image depth (one of CV_8U or CV_32F) + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param isLab if set to true treat input as Lab otherwise Luv + @param srgb if set to true use sRGB gamma correction + Convert from Lab or Luv to BGR, RGB, BGRA or RGBA. + */ +inline int hal_ni_cvtLabtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int depth, int dcn, bool swapBlue, bool isLab, bool srgb) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtTwoPlaneYUVtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param dst_width,dst_height destination image size + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param uIdx U-channel index in the interleaved U/V plane (0 or 1) + Convert from YUV (YUV420sp (or NV12/NV21) - Y plane followed by interleaved U/V plane) to BGR, RGB, BGRA or RGBA. + Only for CV_8U. + */ +inline int hal_ni_cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int dst_width, int dst_height, int dcn, bool swapBlue, int uIdx) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtThreePlaneYUVtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param dst_width,dst_height destination image size + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param uIdx U-channel plane index (0 or 1) + Convert from YUV (YUV420p (or YV12/YV21) - Y plane followed by U and V planes) to BGR, RGB, BGRA or RGBA. + Only for CV_8U. + */ +inline int hal_ni_cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int dst_width, int dst_height, int dcn, bool swapBlue, int uIdx) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtBGRtoThreePlaneYUV + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param scn source image channels (3 or 4) + @param swapBlue if set to true B and R source channels will be swapped (treat as RGB) + @param uIdx U-channel plane index (0 or 1) + Convert from BGR, RGB, BGRA or RGBA to YUV (YUV420p (or YV12/YV21) - Y plane followed by U and V planes). + Only for CV_8U. + */ +inline int hal_ni_cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int scn, bool swapBlue, int uIdx) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtOnePlaneYUVtoBGR + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + @param dcn destination image channels (3 or 4) + @param swapBlue if set to true B and R destination channels will be swapped (write RGB) + @param uIdx U-channel index (0 or 1) + @param ycn Y-channel index (0 or 1) + Convert from UYVY, YUY2 or YVYU to BGR, RGB, BGRA or RGBA. + Only for CV_8U. + */ +inline int hal_ni_cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height, int dcn, bool swapBlue, int uIdx, int ycn) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + + +/** + @brief hal_cvtRGBAtoMultipliedRGBA + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + Convert from BGRA or RGBA to format with multiplied alpha channel. + Only for CV_8U. + */ +inline int hal_ni_cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +/** + @brief hal_cvtMultipliedRGBAtoRGBA + @param src_data,src_step source image data and step + @param dst_data,dst_step destination image data and step + @param width,height image size + Convert from format with multiplied alpha channel to BGRA or RGBA. + Only for CV_8U. + */ +inline int hal_ni_cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, uchar * dst_data, size_t dst_step, int width, int height) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } + +//! @cond IGNORED +#define cv_hal_cvtBGRtoBGR hal_ni_cvtBGRtoBGR +#define cv_hal_cvtBGRtoBGR5x5 hal_ni_cvtBGRtoBGR5x5 +#define cv_hal_cvtBGR5x5toBGR hal_ni_cvtBGR5x5toBGR +#define cv_hal_cvtBGRtoGray hal_ni_cvtBGRtoGray +#define cv_hal_cvtGraytoBGR hal_ni_cvtGraytoBGR +#define cv_hal_cvtBGR5x5toGray hal_ni_cvtBGR5x5toGray +#define cv_hal_cvtGraytoBGR5x5 hal_ni_cvtGraytoBGR5x5 +#define cv_hal_cvtBGRtoYUV hal_ni_cvtBGRtoYUV +#define cv_hal_cvtYUVtoBGR hal_ni_cvtYUVtoBGR +#define cv_hal_cvtBGRtoXYZ hal_ni_cvtBGRtoXYZ +#define cv_hal_cvtXYZtoBGR hal_ni_cvtXYZtoBGR +#define cv_hal_cvtBGRtoHSV hal_ni_cvtBGRtoHSV +#define cv_hal_cvtHSVtoBGR hal_ni_cvtHSVtoBGR +#define cv_hal_cvtBGRtoLab hal_ni_cvtBGRtoLab +#define cv_hal_cvtLabtoBGR hal_ni_cvtLabtoBGR +#define cv_hal_cvtTwoPlaneYUVtoBGR hal_ni_cvtTwoPlaneYUVtoBGR +#define cv_hal_cvtThreePlaneYUVtoBGR hal_ni_cvtThreePlaneYUVtoBGR +#define cv_hal_cvtBGRtoThreePlaneYUV hal_ni_cvtBGRtoThreePlaneYUV +#define cv_hal_cvtOnePlaneYUVtoBGR hal_ni_cvtOnePlaneYUVtoBGR +#define cv_hal_cvtRGBAtoMultipliedRGBA hal_ni_cvtRGBAtoMultipliedRGBA +#define cv_hal_cvtMultipliedRGBAtoRGBA hal_ni_cvtMultipliedRGBAtoRGBA +//! @endcond + //! @} #if defined __GNUC__ @@ -306,7 +594,6 @@ inline int hal_ni_warpPerspectve(int src_type, const uchar *src_data, size_t src # pragma warning( pop ) #endif - #include "custom_hal.hpp" //! @cond IGNORED From 86959310f900b19a0510d60990bd45e59baf6c3a Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Tue, 26 Apr 2016 18:02:47 +0200 Subject: [PATCH 07/95] calibrationMatrixValues: bind C++ function in C instead of vice versa --- modules/calib3d/src/calibration.cpp | 85 +++++++++++++---------------- 1 file changed, 38 insertions(+), 47 deletions(-) diff --git a/modules/calib3d/src/calibration.cpp b/modules/calib3d/src/calibration.cpp index b8f569aeb8..bd759d294b 100644 --- a/modules/calib3d/src/calibration.cpp +++ b/modules/calib3d/src/calibration.cpp @@ -1626,58 +1626,24 @@ void cvCalibrationMatrixValues( const CvMat *calibMatr, CvSize imgSize, double apertureWidth, double apertureHeight, double *fovx, double *fovy, double *focalLength, CvPoint2D64f *principalPoint, double *pasp ) { - double alphax, alphay, mx, my; - int imgWidth = imgSize.width, imgHeight = imgSize.height; - /* Validate parameters. */ - if(calibMatr == 0) CV_Error(CV_StsNullPtr, "Some of parameters is a NULL pointer!"); if(!CV_IS_MAT(calibMatr)) CV_Error(CV_StsUnsupportedFormat, "Input parameters must be a matrices!"); - if(calibMatr->cols != 3 || calibMatr->rows != 3) - CV_Error(CV_StsUnmatchedSizes, "Size of matrices must be 3x3!"); - - alphax = cvmGet(calibMatr, 0, 0); - alphay = cvmGet(calibMatr, 1, 1); - assert(imgWidth != 0 && imgHeight != 0 && alphax != 0.0 && alphay != 0.0); - - /* Calculate pixel aspect ratio. */ - if(pasp) - *pasp = alphay / alphax; - - /* Calculate number of pixel per realworld unit. */ - - if(apertureWidth != 0.0 && apertureHeight != 0.0) { - mx = imgWidth / apertureWidth; - my = imgHeight / apertureHeight; - } else { - mx = 1.0; - if(pasp) - my = *pasp; - else - my = 1.0; - } - - /* Calculate fovx and fovy. */ - - if(fovx) - *fovx = 2 * atan(imgWidth / (2 * alphax)) * 180.0 / CV_PI; - - if(fovy) - *fovy = 2 * atan(imgHeight / (2 * alphay)) * 180.0 / CV_PI; - - /* Calculate focal length. */ - - if(focalLength) - *focalLength = alphax / mx; - - /* Calculate principle point. */ + double dummy; + Point2d pp; + cv::calibrationMatrixValues(cvarrToMat(calibMatr), imgSize, apertureWidth, apertureHeight, + fovx ? *fovx : dummy, + fovy ? *fovy : dummy, + focalLength ? *focalLength : dummy, + pp, + pasp ? *pasp : dummy); if(principalPoint) - *principalPoint = cvPoint2D64f(cvmGet(calibMatr, 0, 2) / mx, cvmGet(calibMatr, 1, 2) / my); + *principalPoint = cvPoint2D64f(pp.x, pp.y); } @@ -3369,10 +3335,35 @@ void cv::calibrationMatrixValues( InputArray _cameraMatrix, Size imageSize, double& fovx, double& fovy, double& focalLength, Point2d& principalPoint, double& aspectRatio ) { - Mat cameraMatrix = _cameraMatrix.getMat(); - CvMat c_cameraMatrix = cameraMatrix; - cvCalibrationMatrixValues( &c_cameraMatrix, imageSize, apertureWidth, apertureHeight, - &fovx, &fovy, &focalLength, (CvPoint2D64f*)&principalPoint, &aspectRatio ); + if(_cameraMatrix.size() != Size(3, 3)) + CV_Error(CV_StsUnmatchedSizes, "Size of cameraMatrix must be 3x3!"); + + Matx33d K = _cameraMatrix.getMat(); + + CV_DbgAssert(imageSize.width != 0 && imageSize.height != 0 && K(0, 0) != 0.0 && K(1, 1) != 0.0); + + /* Calculate pixel aspect ratio. */ + aspectRatio = K(1, 1) / K(0, 0); + + /* Calculate number of pixel per realworld unit. */ + double mx, my; + if(apertureWidth != 0.0 && apertureHeight != 0.0) { + mx = imageSize.width / apertureWidth; + my = imageSize.height / apertureHeight; + } else { + mx = 1.0; + my = aspectRatio; + } + + /* Calculate fovx and fovy. */ + fovx = 2 * atan(imageSize.width / (2 * K(0, 0))) * 180.0 / CV_PI; + fovy = 2 * atan(imageSize.height / (2 * K(1, 1))) * 180.0 / CV_PI; + + /* Calculate focal length. */ + focalLength = K(0, 0) / mx; + + /* Calculate principle point. */ + principalPoint = Point2d(K(0, 2) / mx, K(1, 2) / my); } double cv::stereoCalibrate( InputArrayOfArrays _objectPoints, From 8ed1945ccd52501f5ab22bdec6aa1f91f1e2cfd4 Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Wed, 27 Apr 2016 14:47:52 +0200 Subject: [PATCH 08/95] calibrationMatrixValues: consider principalPoint in FOV computation The FOV depends on the principal point location. Use formula of viz::Camera. --- modules/calib3d/src/calibration.cpp | 6 ++++-- modules/calib3d/test/test_cameracalibration.cpp | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/calib3d/src/calibration.cpp b/modules/calib3d/src/calibration.cpp index bd759d294b..8ae9bb2c12 100644 --- a/modules/calib3d/src/calibration.cpp +++ b/modules/calib3d/src/calibration.cpp @@ -3356,8 +3356,10 @@ void cv::calibrationMatrixValues( InputArray _cameraMatrix, Size imageSize, } /* Calculate fovx and fovy. */ - fovx = 2 * atan(imageSize.width / (2 * K(0, 0))) * 180.0 / CV_PI; - fovy = 2 * atan(imageSize.height / (2 * K(1, 1))) * 180.0 / CV_PI; + fovx = atan2(K(0, 2), K(0, 0)) + atan2(imageSize.width - K(0, 2), K(0, 0)); + fovy = atan2(K(1, 2), K(1, 1)) + atan2(imageSize.height - K(1, 2), K(1, 1)); + fovx *= 180.0 / CV_PI; + fovy *= 180.0 / CV_PI; /* Calculate focal length. */ focalLength = K(0, 0) / mx; diff --git a/modules/calib3d/test/test_cameracalibration.cpp b/modules/calib3d/test/test_cameracalibration.cpp index 49d73fc616..329a825245 100644 --- a/modules/calib3d/test/test_cameracalibration.cpp +++ b/modules/calib3d/test/test_cameracalibration.cpp @@ -875,8 +875,8 @@ void CV_CalibrationMatrixValuesTest::run(int) ny = goodAspectRatio; } - goodFovx = 2 * atan( imageSize.width / (2 * fx)) * 180.0 / CV_PI; - goodFovy = 2 * atan( imageSize.height / (2 * fy)) * 180.0 / CV_PI; + goodFovx = (atan2(cx, fx) + atan2(imageSize.width - cx, fx)) * 180.0 / CV_PI; + goodFovy = (atan2(cy, fy) + atan2(imageSize.height - cy, fy)) * 180.0 / CV_PI; goodFocalLength = fx / nx; From 3db19c046b376aff6274aeeb69ea751d9f7988d4 Mon Sep 17 00:00:00 2001 From: DozyC Date: Tue, 10 May 2016 17:20:59 -0700 Subject: [PATCH 09/95] Fix command line argument handling, fixes #6525 --- samples/tapi/hog.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/samples/tapi/hog.cpp b/samples/tapi/hog.cpp index e361c2b735..0529f24a1c 100644 --- a/samples/tapi/hog.cpp +++ b/samples/tapi/hog.cpp @@ -76,10 +76,8 @@ int main(int argc, char** argv) "{ s scale | 1.0 | resize the image before detect}" "{ o output | | specify output path when input is images}"; CommandLineParser cmd(argc, argv, keys); - if (cmd.has("help")) + if (cmd.get("help")) { - cout << "Usage : hog [options]" << endl; - cout << "Available options:" << endl; cmd.printMessage(); return EXIT_SUCCESS; } @@ -117,7 +115,7 @@ App::App(CommandLineParser& cmd) << "\t4/r - increase/decrease hit threshold\n" << endl; - make_gray = cmd.has("gray"); + make_gray = cmd.get("gray"); resize_scale = cmd.get("s"); vdo_source = cmd.get("v"); img_source = cmd.get("i"); From 6c4aae98f7b7d3f83014204ff7a276b01c99e294 Mon Sep 17 00:00:00 2001 From: DozyC Date: Thu, 19 May 2016 23:20:55 -0700 Subject: [PATCH 10/95] tapi examples - Removing defaults from all command line switches accessed with has() --- samples/tapi/bgfg_segm.cpp | 4 ++-- samples/tapi/clahe.cpp | 2 +- samples/tapi/hog.cpp | 8 ++++---- samples/tapi/pyrlk_optical_flow.cpp | 2 +- samples/tapi/squares.cpp | 4 ++-- samples/tapi/tvl1_optical_flow.cpp | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/samples/tapi/bgfg_segm.cpp b/samples/tapi/bgfg_segm.cpp index 40587713b7..8b944d184a 100644 --- a/samples/tapi/bgfg_segm.cpp +++ b/samples/tapi/bgfg_segm.cpp @@ -17,10 +17,10 @@ using namespace cv; int main(int argc, const char** argv) { CommandLineParser cmd(argc, argv, - "{ c camera | false | use camera }" + "{ c camera | | use camera }" "{ f file | ../data/768x576.avi | input video file }" "{ t type | mog2 | method's type (knn, mog2) }" - "{ h help | false | print help message }" + "{ h help | | print help message }" "{ m cpu_mode | false | press 'm' to switch OpenCL<->CPU}"); if (cmd.has("help")) diff --git a/samples/tapi/clahe.cpp b/samples/tapi/clahe.cpp index 905ea1f1ae..1b6c53b9b3 100644 --- a/samples/tapi/clahe.cpp +++ b/samples/tapi/clahe.cpp @@ -33,7 +33,7 @@ int main(int argc, char** argv) "{ i input | | specify input image }" "{ c camera | 0 | specify camera id }" "{ o output | clahe_output.jpg | specify output save path}" - "{ h help | false | print help message }"; + "{ h help | | print help message }"; cv::CommandLineParser cmd(argc, argv, keys); if (cmd.has("help")) diff --git a/samples/tapi/hog.cpp b/samples/tapi/hog.cpp index 0529f24a1c..db31396106 100644 --- a/samples/tapi/hog.cpp +++ b/samples/tapi/hog.cpp @@ -68,15 +68,15 @@ private: int main(int argc, char** argv) { const char* keys = - "{ h help | false | print help message }" + "{ h help | | print help message }" "{ i input | | specify input image}" "{ c camera | -1 | enable camera capturing }" "{ v video | ../data/768x576.avi | use video as input }" - "{ g gray | false | convert image to gray one or not}" + "{ g gray | | convert image to gray one or not}" "{ s scale | 1.0 | resize the image before detect}" "{ o output | | specify output path when input is images}"; CommandLineParser cmd(argc, argv, keys); - if (cmd.get("help")) + if (cmd.has("help")) { cmd.printMessage(); return EXIT_SUCCESS; @@ -115,7 +115,7 @@ App::App(CommandLineParser& cmd) << "\t4/r - increase/decrease hit threshold\n" << endl; - make_gray = cmd.get("gray"); + make_gray = cmd.has("gray"); resize_scale = cmd.get("s"); vdo_source = cmd.get("v"); img_source = cmd.get("i"); diff --git a/samples/tapi/pyrlk_optical_flow.cpp b/samples/tapi/pyrlk_optical_flow.cpp index 9cdbd7c5bf..bb426cbf76 100644 --- a/samples/tapi/pyrlk_optical_flow.cpp +++ b/samples/tapi/pyrlk_optical_flow.cpp @@ -75,7 +75,7 @@ static void drawArrows(UMat& _frame, const vector& prevPts, const vecto int main(int argc, const char* argv[]) { const char* keys = - "{ h help | false | print help message }" + "{ h help | | print help message }" "{ l left | | specify left image }" "{ r right | | specify right image }" "{ c camera | 0 | enable camera capturing }" diff --git a/samples/tapi/squares.cpp b/samples/tapi/squares.cpp index e18e533d66..7df4a42672 100644 --- a/samples/tapi/squares.cpp +++ b/samples/tapi/squares.cpp @@ -143,8 +143,8 @@ int main(int argc, char** argv) const char* keys = "{ i input | ../data/pic1.png | specify input image }" "{ o output | squares_output.jpg | specify output save path}" - "{ h help | false | print help message }" - "{ m cpu_mode | false | run without OpenCL }"; + "{ h help | | print help message }" + "{ m cpu_mode | | run without OpenCL }"; CommandLineParser cmd(argc, argv, keys); diff --git a/samples/tapi/tvl1_optical_flow.cpp b/samples/tapi/tvl1_optical_flow.cpp index f7bebacbeb..18c7a7f47b 100644 --- a/samples/tapi/tvl1_optical_flow.cpp +++ b/samples/tapi/tvl1_optical_flow.cpp @@ -83,12 +83,12 @@ static void getFlowField(const Mat& u, const Mat& v, Mat& flowField) int main(int argc, const char* argv[]) { const char* keys = - "{ h help | false | print help message }" + "{ h help | | print help message }" "{ l left | | specify left image }" "{ r right | | specify right image }" "{ o output | tvl1_output.jpg | specify output save path }" "{ c camera | 0 | enable camera capturing }" - "{ m cpu_mode | false | run without OpenCL }" + "{ m cpu_mode | | run without OpenCL }" "{ v video | | use video as input }"; CommandLineParser cmd(argc, argv, keys); From 7f52a553d47172eef1ebf7d0211bf3d6ebb92714 Mon Sep 17 00:00:00 2001 From: debjan Date: Mon, 30 May 2016 10:47:59 +0200 Subject: [PATCH 11/95] Update gen_pattern.py Save method should save, instead trying to run inkview --- doc/pattern_tools/gen_pattern.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/pattern_tools/gen_pattern.py b/doc/pattern_tools/gen_pattern.py index ebeeb123fe..85b3ea4955 100755 --- a/doc/pattern_tools/gen_pattern.py +++ b/doc/pattern_tools/gen_pattern.py @@ -61,7 +61,7 @@ class PatternMaker: def save(self): c = canvas(self.g,width="%d%s"%(self.width,self.units),height="%d%s"%(self.height,self.units),viewBox="0 0 %d %d"%(self.width,self.height)) - c.inkview(self.output) + c.save(self.output) def main(): From ef450050561b9107f3cb7eff57e27917dc4165dc Mon Sep 17 00:00:00 2001 From: Marek Smigielski Date: Tue, 31 May 2016 08:35:50 +0200 Subject: [PATCH 12/95] Adding support for pointer generation. Fixes #6605 --- modules/java/generator/gen_java.py | 14 +++++++------- modules/ml/include/opencv2/ml.hpp | 10 +++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/modules/java/generator/gen_java.py b/modules/java/generator/gen_java.py index d4560a972e..f8d3f7d0a5 100755 --- a/modules/java/generator/gen_java.py +++ b/modules/java/generator/gen_java.py @@ -991,12 +991,12 @@ class JavaWrapperGenerator(object): if classinfo.base: classinfo.addImports(classinfo.base) - type_dict["Ptr_"+name] = \ - { "j_type" : name, - "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),), - "jni_name" : "Ptr<"+name+">(("+name+"*)%(n)s_nativeObj)", "jni_type" : "jlong", - "suffix" : "J" } - logging.info('ok: %s', classinfo) + type_dict["Ptr_"+name] = \ + { "j_type" : name, + "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),), + "jni_name" : "Ptr<"+name+">(("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj)", "jni_type" : "jlong", + "suffix" : "J" } + logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base) def add_const(self, decl): # [ "const cname", val, [], [] ] constinfo = ConstInfo(decl, namespaces=self.namespaces) @@ -1347,7 +1347,7 @@ class JavaWrapperGenerator(object): ret = "return (jlong) new %s(_retval_);" % self.fullTypeName(fi.ctype) elif fi.ctype.startswith('Ptr_'): c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeName(fi.ctype[4:]), fi.ctype)) - ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype } + ret = "%(ctype)s* curval = new %(ctype)s(_retval_);return (jlong)curval->get();" % { 'ctype':fi.ctype } elif self.isWrapped(ret_type): # pointer to wrapped class: ret = "return (jlong) _retval_;" elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray": diff --git a/modules/ml/include/opencv2/ml.hpp b/modules/ml/include/opencv2/ml.hpp index cea8aec48c..d016810874 100644 --- a/modules/ml/include/opencv2/ml.hpp +++ b/modules/ml/include/opencv2/ml.hpp @@ -285,7 +285,7 @@ public: `, containing types of each input and output variable. See ml::VariableTypes. */ - CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, + CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), InputArray sampleWeights=noArray(), InputArray varType=noArray()); }; @@ -320,7 +320,7 @@ public: @param flags optional flags, depending on the model. Some of the models can be updated with the new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). */ - CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); + CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); /** @brief Trains the statistical model @@ -343,7 +343,7 @@ public: The method uses StatModel::predict to compute the error. For regression models the error is computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). */ - CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; + CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; /** @brief Predicts response(s) for the provided sample(s) @@ -357,7 +357,7 @@ public: The class must implement static `create()` method with no parameters or with all default parameter values */ - template static Ptr<_Tp> train(const Ptr& data, int flags=0) + template static Ptr<_Tp> train(const Ptr& data, int flags=0) { Ptr<_Tp> model = _Tp::create(); return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); @@ -667,7 +667,7 @@ public: regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and the usual %SVM with parameters specified in params is executed. */ - virtual bool trainAuto( const Ptr& data, int kFold = 10, + virtual bool trainAuto( const Ptr& data, int kFold = 10, ParamGrid Cgrid = SVM::getDefaultGrid(SVM::C), ParamGrid gammaGrid = SVM::getDefaultGrid(SVM::GAMMA), ParamGrid pGrid = SVM::getDefaultGrid(SVM::P), From 1e667de1f32ba6cfe53e05c7e80e75be88162353 Mon Sep 17 00:00:00 2001 From: Maksim Shabunin Date: Tue, 24 May 2016 13:57:27 +0300 Subject: [PATCH 13/95] HAL math interfaces: fastAtan2, magnitude, sqrt, invSqrt, log, exp --- modules/core/include/opencv2/core/hal/hal.hpp | 4 +- .../core/include/opencv2/core/hal/intrin.hpp | 94 +++++++ modules/core/perf/perf_math.cpp | 14 + modules/core/src/hal_replacement.hpp | 104 +++++++ modules/core/src/mathfuncs.cpp | 142 +--------- modules/core/src/mathfuncs_core.cpp | 257 ++++++++++++------ modules/core/test/test_intrin.cpp | 22 +- modules/core/test/test_intrin_utils.hpp | 76 ------ modules/core/test/test_math.cpp | 13 +- modules/features2d/src/kaze/AKAZEFeatures.cpp | 2 +- 10 files changed, 412 insertions(+), 316 deletions(-) diff --git a/modules/core/include/opencv2/core/hal/hal.hpp b/modules/core/include/opencv2/core/hal/hal.hpp index 09bcd72d5a..80bed397b2 100644 --- a/modules/core/include/opencv2/core/hal/hal.hpp +++ b/modules/core/include/opencv2/core/hal/hal.hpp @@ -85,7 +85,8 @@ CV_EXPORTS void exp64f(const double* src, double* dst, int n); CV_EXPORTS void log32f(const float* src, float* dst, int n); CV_EXPORTS void log64f(const double* src, double* dst, int n); -CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan32f(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan64f(const double* y, const double* x, double* dst, int n, bool angleInDegrees); CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); @@ -228,6 +229,7 @@ CV_EXPORTS void exp(const double* src, double* dst, int n); CV_EXPORTS void log(const float* src, float* dst, int n); CV_EXPORTS void log(const double* src, double* dst, int n); +CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); CV_EXPORTS void sqrt(const float* src, float* dst, int len); diff --git a/modules/core/include/opencv2/core/hal/intrin.hpp b/modules/core/include/opencv2/core/hal/intrin.hpp index 33e14b486a..6da8fdfd1d 100644 --- a/modules/core/include/opencv2/core/hal/intrin.hpp +++ b/modules/core/include/opencv2/core/hal/intrin.hpp @@ -317,4 +317,98 @@ template struct V_SIMD128Traits //! @} +//================================================================================================== + +//! @cond IGNORED + +namespace cv { + +template struct V_RegTrait128; + +template <> struct V_RegTrait128 { + typedef v_uint8x16 reg; + typedef v_uint16x8 w_reg; + typedef v_uint32x4 q_reg; + typedef v_uint8x16 u_reg; + static v_uint8x16 zero() { return v_setzero_u8(); } + static v_uint8x16 all(uchar val) { return v_setall_u8(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_int8x16 reg; + typedef v_int16x8 w_reg; + typedef v_int32x4 q_reg; + typedef v_uint8x16 u_reg; + static v_int8x16 zero() { return v_setzero_s8(); } + static v_int8x16 all(schar val) { return v_setall_s8(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_uint16x8 reg; + typedef v_uint32x4 w_reg; + typedef v_int16x8 int_reg; + typedef v_uint16x8 u_reg; + static v_uint16x8 zero() { return v_setzero_u16(); } + static v_uint16x8 all(ushort val) { return v_setall_u16(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_int16x8 reg; + typedef v_int32x4 w_reg; + typedef v_uint16x8 u_reg; + static v_int16x8 zero() { return v_setzero_s16(); } + static v_int16x8 all(short val) { return v_setall_s16(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_uint32x4 reg; + typedef v_uint64x2 w_reg; + typedef v_int32x4 int_reg; + typedef v_uint32x4 u_reg; + static v_uint32x4 zero() { return v_setzero_u32(); } + static v_uint32x4 all(unsigned val) { return v_setall_u32(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_int32x4 reg; + typedef v_int64x2 w_reg; + typedef v_uint32x4 u_reg; + static v_int32x4 zero() { return v_setzero_s32(); } + static v_int32x4 all(int val) { return v_setall_s32(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_uint64x2 reg; + static v_uint64x2 zero() { return v_setzero_u64(); } + static v_uint64x2 all(uint64 val) { return v_setall_u64(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_int64x2 reg; + static v_int64x2 zero() { return v_setzero_s64(); } + static v_int64x2 all(int64 val) { return v_setall_s64(val); } +}; + +template <> struct V_RegTrait128 { + typedef v_float32x4 reg; + typedef v_int32x4 int_reg; + typedef v_float32x4 u_reg; + static v_float32x4 zero() { return v_setzero_f32(); } + static v_float32x4 all(float val) { return v_setall_f32(val); } +}; + +#if CV_SIMD128_64F +template <> struct V_RegTrait128 { + typedef v_float64x2 reg; + typedef v_int32x4 int_reg; + typedef v_float64x2 u_reg; + static v_float64x2 zero() { return v_setzero_f64(); } + static v_float64x2 all(double val) { return v_setall_f64(val); } +}; +#endif + +} // cv:: + +//! @endcond + #endif diff --git a/modules/core/perf/perf_math.cpp b/modules/core/perf/perf_math.cpp index 267cc9c409..eb3fbb0b24 100644 --- a/modules/core/perf/perf_math.cpp +++ b/modules/core/perf/perf_math.cpp @@ -25,6 +25,20 @@ PERF_TEST_P(VectorLength, phase32f, testing::Values(128, 1000, 128*1024, 512*102 SANITY_CHECK(angle, 5e-5); } +PERF_TEST_P(VectorLength, phase64f, testing::Values(128, 1000, 128*1024, 512*1024, 1024*1024)) +{ + size_t length = GetParam(); + vector X(length); + vector Y(length); + vector angle(length); + + declare.in(X, Y, WARMUP_RNG).out(angle); + + TEST_CYCLE_N(200) cv::phase(X, Y, angle, true); + + SANITY_CHECK(angle, 5e-5); +} + PERF_TEST_P( MaxDim_MaxPoints, kmeans, testing::Combine( testing::Values( 16, 32, 64 ), testing::Values( 300, 400, 500) ) ) diff --git a/modules/core/src/hal_replacement.hpp b/modules/core/src/hal_replacement.hpp index 93476c4594..b3766dca45 100644 --- a/modules/core/src/hal_replacement.hpp +++ b/modules/core/src/hal_replacement.hpp @@ -376,6 +376,110 @@ inline int hal_ni_merge64s(const int64 **src_data, int64 *dst_data, int len, int #define cv_hal_merge64s hal_ni_merge64s //! @endcond + +/** +@param y,x source Y and X arrays +@param dst destination array +@param len length of arrays +@param angleInDegrees if set to true return angles in degrees, otherwise in radians + */ +//! @addtogroup core_hal_interface_fastAtan Atan calculation +//! @{ +inline int hal_ni_fastAtan32f(const float* y, const float* x, float* dst, int len, bool angleInDegrees) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_fastAtan64f(const double* y, const double* x, double* dst, int len, bool angleInDegrees) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_fastAtan32f hal_ni_fastAtan32f +#define cv_hal_fastAtan64f hal_ni_fastAtan64f +//! @endcond + + +/** +@param x,y source X and Y arrays +@param dst destination array +@param len length of arrays + */ +//! @addtogroup core_hal_interface_magnitude Magnitude calculation +//! @{ +inline int hal_ni_magnitude32f(const float *x, const float *y, float *dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_magnitude64f(const double *x, const double *y, double *dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_magnitude32f hal_ni_magnitude32f +#define cv_hal_magnitude64f hal_ni_magnitude64f +//! @endcond + + +/** +@param src source array +@param dst destination array +@param len length of arrays + */ +//! @addtogroup core_hal_interface_invSqrt Inverse square root calculation +//! @{ +inline int hal_ni_invSqrt32f(const float* src, float* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_invSqrt64f(const double* src, double* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_invSqrt32f hal_ni_invSqrt32f +#define cv_hal_invSqrt64f hal_ni_invSqrt64f +//! @endcond + + +/** +@param src source array +@param dst destination array +@param len length of arrays + */ +//! @addtogroup core_hal_interface_sqrt Square root calculation +//! @{ +inline int hal_ni_sqrt32f(const float* src, float* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_sqrt64f(const double* src, double* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_sqrt32f hal_ni_sqrt32f +#define cv_hal_sqrt64f hal_ni_sqrt64f +//! @endcond + + +/** +@param src source array +@param dst destination array +@param len length of arrays + */ +//! @addtogroup core_hal_interface_log Natural logarithm calculation +//! @{ +inline int hal_ni_log32f(const float* src, float* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_log64f(const double* src, double* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_log32f hal_ni_log32f +#define cv_hal_log64f hal_ni_log64f +//! @endcond + + +/** +@param src source array +@param dst destination array +@param len length of arrays + */ +//! @addtogroup core_hal_interface_exp Exponent calculation +//! @{ +inline int hal_ni_exp32f(const float* src, float* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +inline int hal_ni_exp64f(const double* src, double* dst, int len) { return CV_HAL_ERROR_NOT_IMPLEMENTED; } +//! @} + +//! @cond IGNORED +#define cv_hal_exp32f hal_ni_exp32f +#define cv_hal_exp64f hal_ni_exp64f +//! @endcond + + /** @brief Dummy structure storing DFT/DCT context diff --git a/modules/core/src/mathfuncs.cpp b/modules/core/src/mathfuncs.cpp index 495711f8dd..e974776c85 100644 --- a/modules/core/src/mathfuncs.cpp +++ b/modules/core/src/mathfuncs.cpp @@ -51,11 +51,6 @@ namespace cv typedef void (*MathFunc)(const void* src, void* dst, int len); -static const float atan2_p1 = 0.9997878412794807f*(float)(180/CV_PI); -static const float atan2_p3 = -0.3258083974640975f*(float)(180/CV_PI); -static const float atan2_p5 = 0.1555786518463281f*(float)(180/CV_PI); -static const float atan2_p7 = -0.04432655554792128f*(float)(180/CV_PI); - #ifdef HAVE_OPENCL enum { OCL_OP_LOG=0, OCL_OP_EXP=1, OCL_OP_MAG=2, OCL_OP_PHASE_DEGREES=3, OCL_OP_PHASE_RADIANS=4 }; @@ -100,29 +95,6 @@ static bool ocl_math_op(InputArray _src1, InputArray _src2, OutputArray _dst, in #endif -float fastAtan2( float y, float x ) -{ - float ax = std::abs(x), ay = std::abs(y); - float a, c, c2; - if( ax >= ay ) - { - c = ay/(ax + (float)DBL_EPSILON); - c2 = c*c; - a = (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; - } - else - { - c = ax/(ay + (float)DBL_EPSILON); - c2 = c*c; - a = 90.f - (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; - } - if( x < 0 ) - a = 180.f - a; - if( y < 0 ) - a = 360.f - a; - return a; -} - /* ************************************************************************** *\ Fast cube root by Ken Turkowski (http://www.worldserver.com/turk/computergraphics/papers.html) @@ -202,7 +174,6 @@ void magnitude( InputArray src1, InputArray src2, OutputArray dst ) } } - void phase( InputArray src1, InputArray src2, OutputArray dst, bool angleInDegrees ) { int type = src1.type(), depth = src1.depth(), cn = src1.channels(); @@ -218,19 +189,8 @@ void phase( InputArray src1, InputArray src2, OutputArray dst, bool angleInDegre const Mat* arrays[] = {&X, &Y, &Angle, 0}; uchar* ptrs[3]; NAryMatIterator it(arrays, ptrs); - cv::AutoBuffer _buf; - float* buf[2] = {0, 0}; - int j, k, total = (int)(it.size*cn), blockSize = total; + int j, total = (int)(it.size*cn), blockSize = total; size_t esz1 = X.elemSize1(); - - if( depth == CV_64F ) - { - blockSize = std::min(blockSize, ((BLOCK_SIZE+cn-1)/cn)*cn); - _buf.allocate(blockSize*2); - buf[0] = _buf; - buf[1] = buf[0] + blockSize; - } - for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( j = 0; j < total; j += blockSize ) @@ -240,53 +200,13 @@ void phase( InputArray src1, InputArray src2, OutputArray dst, bool angleInDegre { const float *x = (const float*)ptrs[0], *y = (const float*)ptrs[1]; float *angle = (float*)ptrs[2]; - hal::fastAtan2( y, x, angle, len, angleInDegrees ); + hal::fastAtan32f( y, x, angle, len, angleInDegrees ); } else { const double *x = (const double*)ptrs[0], *y = (const double*)ptrs[1]; double *angle = (double*)ptrs[2]; - k = 0; - -#if CV_SSE2 - if (USE_SSE2) - { - for ( ; k <= len - 4; k += 4) - { - __m128 v_dst0 = _mm_movelh_ps(_mm_cvtpd_ps(_mm_loadu_pd(x + k)), - _mm_cvtpd_ps(_mm_loadu_pd(x + k + 2))); - __m128 v_dst1 = _mm_movelh_ps(_mm_cvtpd_ps(_mm_loadu_pd(y + k)), - _mm_cvtpd_ps(_mm_loadu_pd(y + k + 2))); - - _mm_storeu_ps(buf[0] + k, v_dst0); - _mm_storeu_ps(buf[1] + k, v_dst1); - } - } -#endif - - for( ; k < len; k++ ) - { - buf[0][k] = (float)x[k]; - buf[1][k] = (float)y[k]; - } - - hal::fastAtan2( buf[1], buf[0], buf[0], len, angleInDegrees ); - k = 0; - -#if CV_SSE2 - if (USE_SSE2) - { - for ( ; k <= len - 4; k += 4) - { - __m128 v_src = _mm_loadu_ps(buf[0] + k); - _mm_storeu_pd(angle + k, _mm_cvtps_pd(v_src)); - _mm_storeu_pd(angle + k + 2, _mm_cvtps_pd(_mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(v_src), 8)))); - } - } -#endif - - for( ; k < len; k++ ) - angle[k] = buf[0][k]; + hal::fastAtan64f(y, x, angle, len, angleInDegrees); } ptrs[0] += len*esz1; ptrs[1] += len*esz1; @@ -353,18 +273,9 @@ void cartToPolar( InputArray src1, InputArray src2, const Mat* arrays[] = {&X, &Y, &Mag, &Angle, 0}; uchar* ptrs[4]; NAryMatIterator it(arrays, ptrs); - cv::AutoBuffer _buf; - float* buf[2] = {0, 0}; - int j, k, total = (int)(it.size*cn), blockSize = std::min(total, ((BLOCK_SIZE+cn-1)/cn)*cn); + int j, total = (int)(it.size*cn), blockSize = std::min(total, ((BLOCK_SIZE+cn-1)/cn)*cn); size_t esz1 = X.elemSize1(); - if( depth == CV_64F ) - { - _buf.allocate(blockSize*2); - buf[0] = _buf; - buf[1] = buf[0] + blockSize; - } - for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( j = 0; j < total; j += blockSize ) @@ -375,55 +286,14 @@ void cartToPolar( InputArray src1, InputArray src2, const float *x = (const float*)ptrs[0], *y = (const float*)ptrs[1]; float *mag = (float*)ptrs[2], *angle = (float*)ptrs[3]; hal::magnitude32f( x, y, mag, len ); - hal::fastAtan2( y, x, angle, len, angleInDegrees ); + hal::fastAtan32f( y, x, angle, len, angleInDegrees ); } else { const double *x = (const double*)ptrs[0], *y = (const double*)ptrs[1]; double *angle = (double*)ptrs[3]; - hal::magnitude64f(x, y, (double*)ptrs[2], len); - k = 0; - -#if CV_SSE2 - if (USE_SSE2) - { - for ( ; k <= len - 4; k += 4) - { - __m128 v_dst0 = _mm_movelh_ps(_mm_cvtpd_ps(_mm_loadu_pd(x + k)), - _mm_cvtpd_ps(_mm_loadu_pd(x + k + 2))); - __m128 v_dst1 = _mm_movelh_ps(_mm_cvtpd_ps(_mm_loadu_pd(y + k)), - _mm_cvtpd_ps(_mm_loadu_pd(y + k + 2))); - - _mm_storeu_ps(buf[0] + k, v_dst0); - _mm_storeu_ps(buf[1] + k, v_dst1); - } - } -#endif - - for( ; k < len; k++ ) - { - buf[0][k] = (float)x[k]; - buf[1][k] = (float)y[k]; - } - - hal::fastAtan2( buf[1], buf[0], buf[0], len, angleInDegrees ); - k = 0; - -#if CV_SSE2 - if (USE_SSE2) - { - for ( ; k <= len - 4; k += 4) - { - __m128 v_src = _mm_loadu_ps(buf[0] + k); - _mm_storeu_pd(angle + k, _mm_cvtps_pd(v_src)); - _mm_storeu_pd(angle + k + 2, _mm_cvtps_pd(_mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(v_src), 8)))); - } - } -#endif - - for( ; k < len; k++ ) - angle[k] = buf[0][k]; + hal::fastAtan64f(y, x, angle, len, angleInDegrees); } ptrs[0] += len*esz1; ptrs[1] += len*esz1; diff --git a/modules/core/src/mathfuncs_core.cpp b/modules/core/src/mathfuncs_core.cpp index 7b3ec319c9..de292fae94 100644 --- a/modules/core/src/mathfuncs_core.cpp +++ b/modules/core/src/mathfuncs_core.cpp @@ -42,116 +42,188 @@ #include "precomp.hpp" +using namespace std; + #undef HAVE_IPP -namespace cv { namespace hal { +namespace { -///////////////////////////////////// ATAN2 //////////////////////////////////// static const float atan2_p1 = 0.9997878412794807f*(float)(180/CV_PI); static const float atan2_p3 = -0.3258083974640975f*(float)(180/CV_PI); static const float atan2_p5 = 0.1555786518463281f*(float)(180/CV_PI); static const float atan2_p7 = -0.04432655554792128f*(float)(180/CV_PI); -void fastAtan2(const float *Y, const float *X, float *angle, int len, bool angleInDegrees ) -{ - int i = 0; - float scale = angleInDegrees ? 1 : (float)(CV_PI/180); +using namespace cv; -#ifdef HAVE_TEGRA_OPTIMIZATION - if (tegra::useTegra() && tegra::FastAtan2_32f(Y, X, angle, len, scale)) - return; +#if CV_SIMD128 + +template +struct v_atan +{ + typedef V_RegTrait128 Trait; + typedef typename Trait::reg VT; // vector type + enum { WorkWidth = VT::nlanes * 2 }; + + v_atan(const T & scale) + : s(Trait::all(scale)) + { + eps = Trait::all(DBL_EPSILON); + z = Trait::zero(); + p7 = Trait::all(atan2_p7); + p5 = Trait::all(atan2_p5); + p3 = Trait::all(atan2_p3); + p1 = Trait::all(atan2_p1); + val90 = Trait::all(90.f); + val180 = Trait::all(180.f); + val360 = Trait::all(360.f); + } + + inline int operator()(int len, const T * Y, const T * X, T * angle) + { + int i = 0; + const int c = VT::nlanes; + for ( ; i <= len - c * 2; i += c * 2) + { + VT x1 = v_load(X + i); + VT x2 = v_load(X + i + c); + VT y1 = v_load(Y + i); + VT y2 = v_load(Y + i + c); + v_store(&angle[i], s * one(x1, y1)); + v_store(&angle[i + c], s * one(x2, y2)); + } + return i; + } + +private: + inline VT one(VT & x, VT & y) + { + VT ax = v_abs(x); + VT ay = v_abs(y); + VT c = v_min(ax, ay) / (v_max(ax, ay) + eps); + VT cc = c * c; + VT a = (((p7 * cc + p5) * cc + p3) * cc + p1) * c; + a = v_select(ax >= ay, a, val90 - a); + a = v_select(x < z, val180 - a, a); + a = v_select(y < z, val360 - a, a); + return a; + } + +private: + VT eps; + VT z; + VT p7; + VT p5; + VT p3; + VT p1; + VT val90; + VT val180; + VT val360; + VT s; +}; + +#if !CV_SIMD128_64F + +// emulation +template <> +struct v_atan +{ + v_atan(double scale) : impl(static_cast(scale)) {} + inline int operator()(int len, const double * Y, const double * X, double * angle) + { + int i = 0; + const int c = v_atan::WorkWidth; + float bufY[c]; + float bufX[c]; + float bufA[c]; + for ( ; i <= len - c ; i += c) + { + for (int j = 0; j < c; ++j) + { + bufY[j] = static_cast(Y[i + j]); + bufX[j] = static_cast(X[i + j]); + } + impl(c, bufY, bufX, bufA); + for (int j = 0; j < c; ++j) + { + angle[i + j] = bufA[j]; + } + } + return i; + } +private: + v_atan impl; +}; #endif -#if CV_SSE2 - Cv32suf iabsmask; iabsmask.i = 0x7fffffff; - __m128 eps = _mm_set1_ps((float)DBL_EPSILON), absmask = _mm_set1_ps(iabsmask.f); - __m128 _90 = _mm_set1_ps(90.f), _180 = _mm_set1_ps(180.f), _360 = _mm_set1_ps(360.f); - __m128 z = _mm_setzero_ps(), scale4 = _mm_set1_ps(scale); - __m128 p1 = _mm_set1_ps(atan2_p1), p3 = _mm_set1_ps(atan2_p3); - __m128 p5 = _mm_set1_ps(atan2_p5), p7 = _mm_set1_ps(atan2_p7); +#endif - for( ; i <= len - 4; i += 4 ) +template +static inline T atanImpl(T y, T x) +{ + T ax = std::abs(x), ay = std::abs(y); + T a, c, c2; + if( ax >= ay ) { - __m128 x = _mm_loadu_ps(X + i), y = _mm_loadu_ps(Y + i); - __m128 ax = _mm_and_ps(x, absmask), ay = _mm_and_ps(y, absmask); - __m128 mask = _mm_cmplt_ps(ax, ay); - __m128 tmin = _mm_min_ps(ax, ay), tmax = _mm_max_ps(ax, ay); - __m128 c = _mm_div_ps(tmin, _mm_add_ps(tmax, eps)); - __m128 c2 = _mm_mul_ps(c, c); - __m128 a = _mm_mul_ps(c2, p7); - a = _mm_mul_ps(_mm_add_ps(a, p5), c2); - a = _mm_mul_ps(_mm_add_ps(a, p3), c2); - a = _mm_mul_ps(_mm_add_ps(a, p1), c); - - __m128 b = _mm_sub_ps(_90, a); - a = _mm_xor_ps(a, _mm_and_ps(_mm_xor_ps(a, b), mask)); - - b = _mm_sub_ps(_180, a); - mask = _mm_cmplt_ps(x, z); - a = _mm_xor_ps(a, _mm_and_ps(_mm_xor_ps(a, b), mask)); - - b = _mm_sub_ps(_360, a); - mask = _mm_cmplt_ps(y, z); - a = _mm_xor_ps(a, _mm_and_ps(_mm_xor_ps(a, b), mask)); - - a = _mm_mul_ps(a, scale4); - _mm_storeu_ps(angle + i, a); + c = ay/(ax + static_cast(DBL_EPSILON)); + c2 = c*c; + a = (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; } -#elif CV_NEON - float32x4_t eps = vdupq_n_f32((float)DBL_EPSILON); - float32x4_t _90 = vdupq_n_f32(90.f), _180 = vdupq_n_f32(180.f), _360 = vdupq_n_f32(360.f); - float32x4_t z = vdupq_n_f32(0.0f), scale4 = vdupq_n_f32(scale); - float32x4_t p1 = vdupq_n_f32(atan2_p1), p3 = vdupq_n_f32(atan2_p3); - float32x4_t p5 = vdupq_n_f32(atan2_p5), p7 = vdupq_n_f32(atan2_p7); - - for( ; i <= len - 4; i += 4 ) + else { - float32x4_t x = vld1q_f32(X + i), y = vld1q_f32(Y + i); - float32x4_t ax = vabsq_f32(x), ay = vabsq_f32(y); - float32x4_t tmin = vminq_f32(ax, ay), tmax = vmaxq_f32(ax, ay); - float32x4_t c = vmulq_f32(tmin, cv_vrecpq_f32(vaddq_f32(tmax, eps))); - float32x4_t c2 = vmulq_f32(c, c); - float32x4_t a = vmulq_f32(c2, p7); - a = vmulq_f32(vaddq_f32(a, p5), c2); - a = vmulq_f32(vaddq_f32(a, p3), c2); - a = vmulq_f32(vaddq_f32(a, p1), c); - - a = vbslq_f32(vcgeq_f32(ax, ay), a, vsubq_f32(_90, a)); - a = vbslq_f32(vcltq_f32(x, z), vsubq_f32(_180, a), a); - a = vbslq_f32(vcltq_f32(y, z), vsubq_f32(_360, a), a); - - vst1q_f32(angle + i, vmulq_f32(a, scale4)); + c = ax/(ay + static_cast(DBL_EPSILON)); + c2 = c*c; + a = 90.f - (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; } + if( x < 0 ) + a = 180.f - a; + if( y < 0 ) + a = 360.f - a; + return a; +} + +template +static inline void atanImpl(const T *Y, const T *X, T *angle, int len, bool angleInDegrees) +{ + int i = 0; + T scale = angleInDegrees ? 1 : static_cast(CV_PI/180); + +#if CV_SIMD128 + i = v_atan(scale)(len, Y, X, angle); #endif for( ; i < len; i++ ) { - float x = X[i], y = Y[i]; - float ax = std::abs(x), ay = std::abs(y); - float a, c, c2; - if( ax >= ay ) - { - c = ay/(ax + (float)DBL_EPSILON); - c2 = c*c; - a = (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; - } - else - { - c = ax/(ay + (float)DBL_EPSILON); - c2 = c*c; - a = 90.f - (((atan2_p7*c2 + atan2_p5)*c2 + atan2_p3)*c2 + atan2_p1)*c; - } - if( x < 0 ) - a = 180.f - a; - if( y < 0 ) - a = 360.f - a; - angle[i] = (float)(a*scale); + angle[i] = atanImpl(Y[i], X[i]) * scale; } } +} // anonymous:: + +namespace cv { namespace hal { + +///////////////////////////////////// ATAN2 //////////////////////////////////// + +void fastAtan32f(const float *Y, const float *X, float *angle, int len, bool angleInDegrees ) +{ + CALL_HAL(fastAtan32f, cv_hal_fastAtan32f, Y, X, angle, len, angleInDegrees); + atanImpl(Y, X, angle, len, angleInDegrees); +} + +void fastAtan64f(const double *Y, const double *X, double *angle, int len, bool angleInDegrees) +{ + CALL_HAL(fastAtan64f, cv_hal_fastAtan64f, Y, X, angle, len, angleInDegrees); + atanImpl(Y, X, angle, len, angleInDegrees); +} + +// deprecated +void fastAtan2(const float *Y, const float *X, float *angle, int len, bool angleInDegrees ) +{ + fastAtan32f(Y, X, angle, len, angleInDegrees); +} void magnitude32f(const float* x, const float* y, float* mag, int len) { + CALL_HAL(magnitude32f, cv_hal_magnitude32f, x, y, mag, len); #if defined HAVE_IPP CV_IPP_CHECK() { @@ -188,6 +260,7 @@ void magnitude32f(const float* x, const float* y, float* mag, int len) void magnitude64f(const double* x, const double* y, double* mag, int len) { + CALL_HAL(magnitude64f, cv_hal_magnitude64f, x, y, mag, len); #if defined(HAVE_IPP) CV_IPP_CHECK() { @@ -225,6 +298,7 @@ void magnitude64f(const double* x, const double* y, double* mag, int len) void invSqrt32f(const float* src, float* dst, int len) { + CALL_HAL(invSqrt32f, cv_hal_invSqrt32f, src, dst, len); #if defined(HAVE_IPP) CV_IPP_CHECK() { @@ -256,6 +330,7 @@ void invSqrt32f(const float* src, float* dst, int len) void invSqrt64f(const double* src, double* dst, int len) { + CALL_HAL(invSqrt64f, cv_hal_invSqrt64f, src, dst, len); int i = 0; #if CV_SSE2 @@ -271,6 +346,7 @@ void invSqrt64f(const double* src, double* dst, int len) void sqrt32f(const float* src, float* dst, int len) { + CALL_HAL(sqrt32f, cv_hal_sqrt32f, src, dst, len); #if defined(HAVE_IPP) CV_IPP_CHECK() { @@ -302,6 +378,7 @@ void sqrt32f(const float* src, float* dst, int len) void sqrt64f(const double* src, double* dst, int len) { + CALL_HAL(sqrt64f, cv_hal_sqrt64f, src, dst, len); #if defined(HAVE_IPP) CV_IPP_CHECK() { @@ -433,6 +510,7 @@ static const double exp_max_val = 3000.*(1 << EXPTAB_SCALE); // log10(DBL_MAX) < void exp32f( const float *_x, float *y, int n ) { + CALL_HAL(exp32f, cv_hal_exp32f, _x, y, n); static const float A4 = (float)(1.000000000000002438532970795181890933776 / EXPPOLY_32F_A0), A3 = (float)(.6931471805521448196800669615864773144641 / EXPPOLY_32F_A0), @@ -632,6 +710,7 @@ void exp32f( const float *_x, float *y, int n ) void exp64f( const double *_x, double *y, int n ) { + CALL_HAL(exp64f, cv_hal_exp64f, _x, y, n); static const double A5 = .99999999999999999998285227504999 / EXPPOLY_32F_A0, A4 = .69314718055994546743029643825322 / EXPPOLY_32F_A0, @@ -1076,6 +1155,7 @@ static const double ln_2 = 0.69314718055994530941723212145818; void log32f( const float *_x, float *y, int n ) { + CALL_HAL(log32f, cv_hal_log32f, _x, y, n); static const float shift[] = { 0, -1.f/512 }; static const float A0 = 0.3333333333333333333333333f, @@ -1220,6 +1300,7 @@ void log32f( const float *_x, float *y, int n ) void log64f( const double *x, double *y, int n ) { + CALL_HAL(log64f, cv_hal_log64f, x, y, n); static const double shift[] = { 0, -1./512 }; static const double A7 = 1.0, @@ -1457,4 +1538,10 @@ void invSqrt(const double* src, double* dst, int len) } -}} // cv::hal:: +} // cv::hal:: +} // cv:: + +float cv::fastAtan2( float y, float x ) +{ + return atanImpl(y, x); +} diff --git a/modules/core/test/test_intrin.cpp b/modules/core/test/test_intrin.cpp index 42b0cfcfd9..ca9d3dc7b7 100644 --- a/modules/core/test/test_intrin.cpp +++ b/modules/core/test/test_intrin.cpp @@ -69,8 +69,8 @@ template struct TheTest EXPECT_EQ(d, res); // zero, all - Data resZ = RegTrait::zero(); - Data resV = RegTrait::all(8); + Data resZ = V_RegTrait128::zero(); + Data resV = V_RegTrait128::all(8); for (int i = 0; i < R::nlanes; ++i) { EXPECT_EQ((LaneType)0, resZ[i]); @@ -135,7 +135,7 @@ template struct TheTest // v_expand and v_load_expand TheTest & test_expand() { - typedef typename RegTrait::w_reg Rx2; + typedef typename V_RegTrait128::w_reg Rx2; Data dataA; R a = dataA; @@ -158,7 +158,7 @@ template struct TheTest TheTest & test_expand_q() { - typedef typename RegTrait::q_reg Rx4; + typedef typename V_RegTrait128::q_reg Rx4; Data data; Data out = v_load_expand_q(data.d); const int n = Rx4::nlanes; @@ -232,7 +232,7 @@ template struct TheTest TheTest & test_mul_expand() { - typedef typename RegTrait::w_reg Rx2; + typedef typename V_RegTrait128::w_reg Rx2; Data dataA, dataB(2); R a = dataA, b = dataB; Rx2 c, d; @@ -295,7 +295,7 @@ template struct TheTest TheTest & test_dot_prod() { - typedef typename RegTrait::w_reg Rx2; + typedef typename V_RegTrait128::w_reg Rx2; Data dataA, dataB(2); R a = dataA, b = dataB; @@ -361,7 +361,7 @@ template struct TheTest TheTest & test_absdiff() { - typedef typename RegTrait::u_reg Ru; + typedef typename V_RegTrait128::u_reg Ru; typedef typename Ru::lane_type u_type; Data dataA(std::numeric_limits::max()), dataB(std::numeric_limits::min()); @@ -445,7 +445,7 @@ template struct TheTest template TheTest & test_pack() { - typedef typename RegTrait::w_reg Rx2; + typedef typename V_RegTrait128::w_reg Rx2; typedef typename Rx2::lane_type w_type; Data dataA, dataB; dataA += std::numeric_limits::is_signed ? -10 : 10; @@ -480,8 +480,8 @@ template struct TheTest template TheTest & test_pack_u() { - typedef typename RegTrait::w_reg Rx2; - typedef typename RegTrait::int_reg Ri2; + typedef typename V_TypeTraits::w_type LaneType_w; + typedef typename V_RegTrait128::int_reg Ri2; typedef typename Ri2::lane_type w_type; Data dataA, dataB; @@ -572,7 +572,7 @@ template struct TheTest TheTest & test_float_math() { - typedef typename RegTrait::int_reg Ri; + typedef typename V_RegTrait128::int_reg Ri; Data data1, data2, data3; data1 *= 1.1; data2 += 10; diff --git a/modules/core/test/test_intrin_utils.hpp b/modules/core/test/test_intrin_utils.hpp index a0eab56a53..1f8a78d98d 100644 --- a/modules/core/test/test_intrin_utils.hpp +++ b/modules/core/test/test_intrin_utils.hpp @@ -155,80 +155,4 @@ template std::ostream & operator<<(std::ostream & out, const Data struct RegTrait; - -template <> struct RegTrait { - typedef cv::v_uint16x8 w_reg; - typedef cv::v_uint32x4 q_reg; - typedef cv::v_uint8x16 u_reg; - static cv::v_uint8x16 zero() { return cv::v_setzero_u8(); } - static cv::v_uint8x16 all(uchar val) { return cv::v_setall_u8(val); } -}; -template <> struct RegTrait { - typedef cv::v_int16x8 w_reg; - typedef cv::v_int32x4 q_reg; - typedef cv::v_uint8x16 u_reg; - static cv::v_int8x16 zero() { return cv::v_setzero_s8(); } - static cv::v_int8x16 all(schar val) { return cv::v_setall_s8(val); } -}; - -template <> struct RegTrait { - typedef cv::v_uint32x4 w_reg; - typedef cv::v_int16x8 int_reg; - typedef cv::v_uint16x8 u_reg; - static cv::v_uint16x8 zero() { return cv::v_setzero_u16(); } - static cv::v_uint16x8 all(ushort val) { return cv::v_setall_u16(val); } -}; - -template <> struct RegTrait { - typedef cv::v_int32x4 w_reg; - typedef cv::v_uint16x8 u_reg; - static cv::v_int16x8 zero() { return cv::v_setzero_s16(); } - static cv::v_int16x8 all(short val) { return cv::v_setall_s16(val); } -}; - -template <> struct RegTrait { - typedef cv::v_uint64x2 w_reg; - typedef cv::v_int32x4 int_reg; - typedef cv::v_uint32x4 u_reg; - static cv::v_uint32x4 zero() { return cv::v_setzero_u32(); } - static cv::v_uint32x4 all(unsigned val) { return cv::v_setall_u32(val); } -}; - -template <> struct RegTrait { - typedef cv::v_int64x2 w_reg; - typedef cv::v_uint32x4 u_reg; - static cv::v_int32x4 zero() { return cv::v_setzero_s32(); } - static cv::v_int32x4 all(int val) { return cv::v_setall_s32(val); } -}; - -template <> struct RegTrait { - static cv::v_uint64x2 zero() { return cv::v_setzero_u64(); } - static cv::v_uint64x2 all(uint64 val) { return cv::v_setall_u64(val); } -}; - -template <> struct RegTrait { - static cv::v_int64x2 zero() { return cv::v_setzero_s64(); } - static cv::v_int64x2 all(int64 val) { return cv::v_setall_s64(val); } -}; - -template <> struct RegTrait { - typedef cv::v_int32x4 int_reg; - typedef cv::v_float32x4 u_reg; - static cv::v_float32x4 zero() { return cv::v_setzero_f32(); } - static cv::v_float32x4 all(float val) { return cv::v_setall_f32(val); } -}; - -#if CV_SIMD128_64F -template <> struct RegTrait { - typedef cv::v_int32x4 int_reg; - typedef cv::v_float64x2 u_reg; - static cv::v_float64x2 zero() { return cv::v_setzero_f64(); } - static cv::v_float64x2 all(double val) { return cv::v_setall_f64(val); } -}; - -#endif - #endif diff --git a/modules/core/test/test_math.cpp b/modules/core/test/test_math.cpp index 65e3861ed8..288c0c1f48 100644 --- a/modules/core/test/test_math.cpp +++ b/modules/core/test/test_math.cpp @@ -2411,8 +2411,9 @@ TEST(Core_SolvePoly, regression_5599) class Core_PhaseTest : public cvtest::BaseTest { + int t; public: - Core_PhaseTest() {} + Core_PhaseTest(int t_) : t(t_) {} ~Core_PhaseTest() {} protected: virtual void run(int) @@ -2421,9 +2422,9 @@ protected: const int axisCount = 8; const int dim = theRNG().uniform(1,10); const float scale = theRNG().uniform(1.f, 100.f); - Mat x(axisCount + 1, dim, CV_32FC1), - y(axisCount + 1, dim, CV_32FC1); - Mat anglesInDegrees(axisCount + 1, dim, CV_32FC1); + Mat x(axisCount + 1, dim, t), + y(axisCount + 1, dim, t); + Mat anglesInDegrees(axisCount + 1, dim, t); // fill the data x.row(0).setTo(Scalar(0)); @@ -2696,8 +2697,8 @@ TEST(Core_SVD, accuracy) { Core_SVDTest test; test.safe_run(); } TEST(Core_SVBkSb, accuracy) { Core_SVBkSbTest test; test.safe_run(); } TEST(Core_Trace, accuracy) { Core_TraceTest test; test.safe_run(); } TEST(Core_SolvePoly, accuracy) { Core_SolvePolyTest test; test.safe_run(); } -TEST(Core_Phase, accuracy) { Core_PhaseTest test; test.safe_run(); } - +TEST(Core_Phase, accuracy32f) { Core_PhaseTest test(CV_32FC1); test.safe_run(); } +TEST(Core_Phase, accuracy64f) { Core_PhaseTest test(CV_64FC1); test.safe_run(); } TEST(Core_SVD, flt) { diff --git a/modules/features2d/src/kaze/AKAZEFeatures.cpp b/modules/features2d/src/kaze/AKAZEFeatures.cpp index 6f1b610ccf..d5a0299440 100644 --- a/modules/features2d/src/kaze/AKAZEFeatures.cpp +++ b/modules/features2d/src/kaze/AKAZEFeatures.cpp @@ -812,7 +812,7 @@ void AKAZEFeatures::Compute_Main_Orientation(KeyPoint& kpt, const std::vector(float)(2.0*CV_PI) ? ang1 - (float)(5.0*CV_PI / 3.0) : ang1 + (float)(CV_PI / 3.0)); From c03d778ec7c9e84eaae0dfccf7e7fdbaeaf1181e Mon Sep 17 00:00:00 2001 From: Louis Letourneau Date: Thu, 19 May 2016 09:29:28 -0400 Subject: [PATCH 14/95] This fixes the seeking in h264 B-Frame enabled video issue. #4890 --- modules/videoio/src/cap_ffmpeg_impl.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/videoio/src/cap_ffmpeg_impl.hpp b/modules/videoio/src/cap_ffmpeg_impl.hpp index 8ac33d749d..4a725bc20b 100644 --- a/modules/videoio/src/cap_ffmpeg_impl.hpp +++ b/modules/videoio/src/cap_ffmpeg_impl.hpp @@ -971,7 +971,8 @@ bool CvCapture_FFMPEG::grabFrame() { //picture_pts = picture->best_effort_timestamp; if( picture_pts == AV_NOPTS_VALUE_ ) - picture_pts = packet.pts != AV_NOPTS_VALUE_ && packet.pts != 0 ? packet.pts : packet.dts; + picture_pts = picture->pkt_pts != AV_NOPTS_VALUE_ && picture->pkt_pts != 0 ? picture->pkt_pts : picture->pkt_dts; + frame_number++; valid = true; } From 7c5b981c17d0308e84e8a5fe86d87c1ac43b1e2b Mon Sep 17 00:00:00 2001 From: Suleyman TURKMEN Date: Sun, 5 Jun 2016 01:06:55 +0300 Subject: [PATCH 15/95] Update drawing.cpp --- modules/imgproc/src/drawing.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/imgproc/src/drawing.cpp b/modules/imgproc/src/drawing.cpp index 4396e0a5ab..a73a30f9dc 100644 --- a/modules/imgproc/src/drawing.cpp +++ b/modules/imgproc/src/drawing.cpp @@ -1813,7 +1813,7 @@ void circle( InputOutputArray _img, Point center, int radius, double buf[4]; scalarToRawData(color, buf, img.type(), 0); - if( thickness > 1 || line_type >= CV_AA || shift > 0 ) + if( thickness > 1 || line_type != LINE_8 || shift > 0 ) { center.x <<= XY_SHIFT - shift; center.y <<= XY_SHIFT - shift; From 43d5988df6731f7753ecc58b64fa6ce498c3b05e Mon Sep 17 00:00:00 2001 From: k-shinotsuka Date: Sat, 4 Jun 2016 15:20:22 +0900 Subject: [PATCH 16/95] improve to calculate norm --- modules/imgproc/src/canny.cpp | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/modules/imgproc/src/canny.cpp b/modules/imgproc/src/canny.cpp index 18cdbd73ee..53fb66bbbe 100644 --- a/modules/imgproc/src/canny.cpp +++ b/modules/imgproc/src/canny.cpp @@ -408,14 +408,12 @@ public: __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j)); __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j)); - __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx); - __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy); - - __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh)); - _mm_storeu_si128((__m128i *)(_norm + j), v_norm); - - v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh)); - _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm); + __m128i v_dx_dy_ml = _mm_unpacklo_epi16(v_dx, v_dy); + __m128i v_dx_dy_mh = _mm_unpackhi_epi16(v_dx, v_dy); + __m128i v_norm_ml = _mm_madd_epi16(v_dx_dy_ml, v_dx_dy_ml); + __m128i v_norm_mh = _mm_madd_epi16(v_dx_dy_mh, v_dx_dy_mh); + _mm_storeu_si128((__m128i *)(_norm + j), v_norm_ml); + _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm_mh); } } #elif CV_NEON @@ -799,14 +797,12 @@ while (borderPeaks.try_pop(m)) __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j)); __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j)); - __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx); - __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy); - - __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh)); - _mm_storeu_si128((__m128i *)(_norm + j), v_norm); - - v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh)); - _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm); + __m128i v_dx_dy_ml = _mm_unpacklo_epi16(v_dx, v_dy); + __m128i v_dx_dy_mh = _mm_unpackhi_epi16(v_dx, v_dy); + __m128i v_norm_ml = _mm_madd_epi16(v_dx_dy_ml, v_dx_dy_ml); + __m128i v_norm_mh = _mm_madd_epi16(v_dx_dy_mh, v_dx_dy_mh); + _mm_storeu_si128((__m128i *)(_norm + j), v_norm_ml); + _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm_mh); } } #elif CV_NEON From ecd827fc8ea248ed3ebbb6e7e48f1b75e11fbd05 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sat, 18 Jun 2016 21:40:29 +0800 Subject: [PATCH 17/95] Add Base64 support for FileStorage [GSoC] FileStorage: Add base64 support for reading and writting XML\YML file. The two new functions: ``` void cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int len, const char* dt); void cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv::Mat const & mat); ``` --- .../core/include/opencv2/core/persistence.hpp | 7 +- modules/core/src/persistence.cpp | 1354 ++++++++++++++++- modules/core/test/test_io.cpp | 121 ++ 3 files changed, 1472 insertions(+), 10 deletions(-) diff --git a/modules/core/include/opencv2/core/persistence.hpp b/modules/core/include/opencv2/core/persistence.hpp index 15454165ad..23714868bd 100644 --- a/modules/core/include/opencv2/core/persistence.hpp +++ b/modules/core/include/opencv2/core/persistence.hpp @@ -1238,6 +1238,11 @@ inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, * //! @endcond + +CV_EXPORTS void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt); + +CV_EXPORTS void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat); + } // cv -#endif // __OPENCV_CORE_PERSISTENCE_HPP__ +#endif // __OPENCV_CORE_PERSISTENCE_HPP__ \ No newline at end of file diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 8f9a42abe6..4f323984bf 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -44,6 +44,8 @@ #include #include +#include +#include #include #define USE_ZLIB 1 @@ -242,6 +244,87 @@ typedef struct CvFileStorage } CvFileStorage; +namespace base64 +{ + static const size_t HEADER_SIZE = 24U; + static const size_t ENCODED_HEADER_SIZE = 32U; + + /* base64 */ + + typedef uchar uint8_t; + + extern uint8_t const base64_padding; + extern uint8_t const base64_mapping[65]; + extern uint8_t const base64_demapping[127]; + + size_t base64_encode(uint8_t const * src, uint8_t * dst, size_t off, size_t cnt); + size_t base64_encode( char const * src, char * dst, size_t off = 0U, size_t cnt = 0U); + + size_t base64_decode(uint8_t const * src, uint8_t * dst, size_t off, size_t cnt); + size_t base64_decode( char const * src, char * dst, size_t off = 0U, size_t cnt = 0U); + + bool base64_valid (uint8_t const * src, size_t off, size_t cnt); + bool base64_valid ( char const * src, size_t off = 0U, size_t cnt = 0U); + + size_t base64_encode_buffer_size(size_t cnt); + + size_t base64_decode_buffer_size(size_t cnt); + + /* binary */ + + template inline size_t to_binary(_uint_t val, uchar * cur); + template<> inline size_t to_binary(double val, uchar * cur); + template<> inline size_t to_binary(float val, uchar * cur); + template inline size_t to_binary(uchar const * val, uchar * cur); + + template inline size_t binary_to(uchar const * cur, _uint_t & val); + template<> inline size_t binary_to(uchar const * cur, double & val); + template<> inline size_t binary_to(uchar const * cur, float & val); + template inline size_t binary_to(uchar const * cur, uchar * val); + + class MatToBinaryConvertor; + class RawDataToBinaryConvertor; + + class BinaryToCvSeqConvertor; + + /* class */ + + class Base64ContextParser + { + public: + explicit Base64ContextParser(uchar * buffer, size_t size); + ~Base64ContextParser(); + Base64ContextParser & read(const uchar * beg, const uchar * end); + bool flush(); + private: + static const size_t BUFFER_LEN = 120U; + uchar * dst_cur; + uchar * dst_end; + uchar * dst_beg; + std::vector base64_buffer; + uchar * src_beg; + uchar * src_end; + uchar * src_cur; + std::vector binary_buffer; + }; + + class Base64ContextEmitter; + + /* other */ + + std::string make_base64_header(int byte_size, const char * dt); + + bool read_base64_header(std::string const & header, int & byte_size, std::string & dt); + + void make_seq(void * binary_data, int elem_cnt, const char * dt, CvSeq & seq); + + /* sample */ + + void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt); + void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat); +} + + static void icvPuts( CvFileStorage* fs, const char* str ) { if( fs->outbuf ) @@ -995,6 +1078,95 @@ icvYMLSkipSpaces( CvFileStorage* fs, char* ptr, int min_indent, int max_comment_ } +static void icvYMLGetMultilineStringContent(CvFileStorage* fs, + char* ptr, int indent, char* &beg, char* &end) +{ + ptr = icvYMLSkipSpaces(fs, ptr, 0, INT_MAX); + beg = ptr; + end = ptr; + if (fs->dummy_eof) + return ; /* end of file */ + + if (ptr - fs->buffer_start != indent) + return ; /* end of string */ + + /* find end */ + while(cv_isprint(*ptr)) /* no check for base64 string */ + ++ ptr; + if (*ptr == '\0') + CV_PARSE_ERROR("Unexpected end of line"); + + end = ptr; +} + +static int icvCalcStructSize( const char* dt, int initial_size ); + +static char* icvYMLParseBase64(CvFileStorage* fs, char* ptr, int indent, CvFileNode * node) +{ + char * beg = 0; + char * end = 0; + + icvYMLGetMultilineStringContent(fs, ptr, indent, beg, end); + if (beg >= end) + return end; // CV_PARSE_ERROR("Empty Binary Data"); + + /* calc (decoded) total_byte_size from header */ + std::string dt; + int total_byte_size = -1; + { + if (end - beg < base64::ENCODED_HEADER_SIZE) + CV_PARSE_ERROR("Unrecognized Base64 header"); + + std::vector header(base64::HEADER_SIZE + 1, ' '); + base64::base64_decode(beg, header.data(), 0U, base64::ENCODED_HEADER_SIZE); + std::istringstream iss(header.data()); + + if (!(iss >> total_byte_size) || total_byte_size < 0) + CV_PARSE_ERROR("Cannot parse size in Base64 header"); + if (!(iss >> dt) || dt.empty()) + CV_PARSE_ERROR("Cannot parse dt in Base64 header"); + + beg += base64::ENCODED_HEADER_SIZE; + } + + /* buffer for decoded data(exclude header) */ + std::vector buffer(total_byte_size + 4); + { + base64::Base64ContextParser parser(buffer.data(), total_byte_size + 4); + + /* decoding */ + while(beg < end) + { + /* save this part [beg, end) */ + parser.read((const uchar *)beg, (const uchar *)end); + + beg = end; + + /* find next part */ + icvYMLGetMultilineStringContent(fs, beg, indent, beg, end); + } + } + /* save as CvSeq */ + int elem_size = ::icvCalcStructSize(dt.c_str(), 0); + if (total_byte_size % elem_size != 0) + CV_PARSE_ERROR("Byte size not match elememt size"); + int elem_cnt = total_byte_size / elem_size; + + node->tag = CV_NODE_NONE; + int struct_flags = CV_NODE_FLOW + CV_NODE_SEQ; /* after icvFSCreateCollection, node->tag == struct_flags */ + icvFSCreateCollection(fs, struct_flags, node); + base64::make_seq(buffer.data(), elem_cnt, dt.c_str(), *node->data.seq); + + if (fs->dummy_eof) { + /* end of file */ + return fs->buffer_start; + } else { + /* end of line */ + return end; + } +} + + static char* icvYMLParseKey( CvFileStorage* fs, char* ptr, CvFileNode* map_node, CvFileNode** value_placeholder ) @@ -1038,6 +1210,7 @@ icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, int is_parent_flow = CV_NODE_IS_FLOW(parent_flags); int value_type = CV_NODE_NONE; int len; + bool is_binary_string = false; memset( node, 0, sizeof(*node) ); @@ -1074,6 +1247,27 @@ icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, if( memcmp( ptr, "float", 5 ) == 0 ) value_type = CV_NODE_REAL; } + else if (len == 6 && CV_NODE_IS_USER(value_type)) + { + if( memcmp( ptr, "binary", 6 ) == 0 ) { + value_type = CV_NODE_SEQ; + is_binary_string = true; + + /* for ignore '|' */ + + /**** operation with endptr ****/ + *endptr = d; + + do { + d = *++endptr; + if (d == '|') + break; + } while (d == ' '); + + d = *++endptr; + *endptr = '\0'; + } + } else if( CV_NODE_IS_USER(value_type) ) { node->info = cvFindType( ptr ); @@ -1088,7 +1282,7 @@ icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, if( !CV_NODE_IS_USER(value_type) ) { - if( value_type == CV_NODE_STRING && c != '\'' && c != '\"' ) + if (value_type == CV_NODE_STRING && c != '\'' && c != '\"') goto force_string; if( value_type == CV_NODE_INT ) goto force_int; @@ -1097,7 +1291,13 @@ icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, } } - if( cv_isdigit(c) || + if (is_binary_string) + { + /* for base64 string */ + int indent = ptr - fs->buffer_start; + ptr = icvYMLParseBase64(fs, ptr, indent, node); + } + else if( cv_isdigit(c) || ((c == '-' || c == '+') && (cv_isdigit(d) || d == '.')) || (c == '.' && cv_isalnum(d))) // a number { @@ -1355,8 +1555,9 @@ icvYMLParse( CvFileStorage* fs ) if( *ptr == '%' ) { - if( memcmp( ptr, "%YAML:", 6 ) == 0 && - memcmp( ptr, "%YAML:1.", 8 ) != 0 ) + if( memcmp( ptr, "%YAML", 5 ) == 0 && + memcmp( ptr, "%YAML:1.", 8 ) != 0 && + memcmp( ptr, "%YAML 1.", 8 ) != 0) CV_PARSE_ERROR( "Unsupported YAML version (it must be 1.x)" ); *ptr = '\0'; } @@ -1521,7 +1722,14 @@ icvYMLStartWriteStruct( CvFileStorage* fs, const char* key, int struct_flags, CV_Error( CV_StsBadArg, "Some collection type - CV_NODE_SEQ or CV_NODE_MAP, must be specified" ); - if( CV_NODE_IS_FLOW(struct_flags) ) + if (type_name && memcmp(type_name, "binary", 6) == 0) + { + /* reset struct flag. in order not to print ']' */ + struct_flags = CV_NODE_SEQ; + sprintf(buf, "!!binary |"); + data = buf; + } + else if( CV_NODE_IS_FLOW(struct_flags)) { char c = CV_NODE_IS_MAP(struct_flags) ? '{' : '['; struct_flags |= CV_NODE_FLOW; @@ -1813,6 +2021,92 @@ icvXMLSkipSpaces( CvFileStorage* fs, char* ptr, int mode ) } +static void icvXMLGetMultilineStringContent(CvFileStorage* fs, + char* ptr, char* &beg, char* &end) +{ + ptr = icvXMLSkipSpaces(fs, ptr, CV_XML_INSIDE_TAG); + beg = ptr; + end = ptr; + if (fs->dummy_eof) + return ; /* end of file */ + + if (*beg == '<') + return; /* end of string */ + + /* find end */ + while(cv_isprint(*ptr)) /* no check for base64 string */ + ++ ptr; + if (*ptr == '\0') + CV_PARSE_ERROR("Unexpected end of line"); + + end = ptr; +} + + +static char* icvXMLParseBase64(CvFileStorage* fs, char* ptr, CvFileNode * node) +{ + char * beg = 0; + char * end = 0; + + icvXMLGetMultilineStringContent(fs, ptr, beg, end); + if (beg >= end) + return end; // CV_PARSE_ERROR("Empty Binary Data"); + + /* calc (decoded) total_byte_size from header */ + std::string dt; + int total_byte_size = -1; + { + if (end - beg < base64::ENCODED_HEADER_SIZE) + CV_PARSE_ERROR("Unrecognized Base64 header"); + + std::vector header(base64::HEADER_SIZE + 1, ' '); + base64::base64_decode(beg, header.data(), 0U, base64::ENCODED_HEADER_SIZE); + std::istringstream iss(header.data()); + if (!(iss >> total_byte_size) || total_byte_size < 0) + CV_PARSE_ERROR("Cannot parse size in Base64 header"); + if (!(iss >> dt) || dt.empty()) + CV_PARSE_ERROR("Cannot parse dt in Base64 header"); + + beg += base64::ENCODED_HEADER_SIZE; + } + + /* alloc buffer for all decoded data(include header) */ + std::vector buffer(total_byte_size + 4); + { + base64::Base64ContextParser parser(buffer.data(), total_byte_size + 4); + + /* decoding */ + while(beg < end) + { + /* save this part [beg, end) */ + parser.read((const uchar *)beg, (const uchar *)end); + beg = end; + /* find next part */ + icvXMLGetMultilineStringContent(fs, beg, beg, end); + } + } + + /* save as CvSeq */ + int elem_size = ::icvCalcStructSize(dt.c_str(), 0); + if (total_byte_size % elem_size != 0) + CV_PARSE_ERROR("Byte size not match elememt size"); + int elem_cnt = total_byte_size / elem_size; + + node->tag = CV_NODE_NONE; + int struct_flags = CV_NODE_SEQ; /* after icvFSCreateCollection, node->tag == struct_flags */ + icvFSCreateCollection(fs, struct_flags, node); + base64::make_seq(buffer.data(), elem_cnt, dt.c_str(), *node->data.seq); + + if (fs->dummy_eof) { + /* end of file */ + return fs->buffer_start; + } else { + /* end of line */ + return end; + } +} + + static char* icvXMLParseTag( CvFileStorage* fs, char* ptr, CvStringHashNode** _tag, CvAttrList** _list, int* _tag_type ); @@ -1864,6 +2158,9 @@ icvXMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, assert( tag_type == CV_XML_OPENING_TAG ); + /* for base64 string */ + bool is_binary_string = false; + type_name = list ? cvAttrValue( list, "type_id" ) : 0; if( type_name ) { @@ -1873,6 +2170,11 @@ icvXMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, elem_type = CV_NODE_MAP; else if( strcmp( type_name, "seq" ) == 0 ) elem_type = CV_NODE_SEQ; + else if (strcmp(type_name, "binary") == 0) + { + elem_type = CV_NODE_NONE; + is_binary_string = true; + } else { info = cvFindType( type_name ); @@ -1895,7 +2197,14 @@ icvXMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, else elem = cvGetFileNode( fs, node, key, 1 ); - ptr = icvXMLParseValue( fs, ptr, elem, elem_type); + if (!is_binary_string) + ptr = icvXMLParseValue( fs, ptr, elem, elem_type); + else { + /* for base64 string */ + ptr = icvXMLParseBase64( fs, ptr, elem); + ptr = icvXMLSkipSpaces( fs, ptr, 0 ); + } + if( !is_noname ) elem->tag |= CV_NODE_NAMED; is_simple &= !CV_NODE_IS_COLLECTION(elem->tag); @@ -2832,7 +3141,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co else { if( !append ) - icvPuts( fs, "%YAML:1.0\n" ); + icvPuts( fs, "%YAML 1.0\n---\n" ); else icvPuts( fs, "...\n---\n" ); fs->start_write_struct = icvYMLStartWriteStruct; @@ -2853,7 +3162,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co } size_t buf_size = 1 << 20; - const char* yaml_signature = "%YAML:"; + const char* yaml_signature = "%YAML"; char buf[16]; icvGets( fs, buf, sizeof(buf)-2 ); fs->fmt = strncmp( buf, yaml_signature, strlen(yaml_signature) ) == 0 ? @@ -3074,6 +3383,29 @@ icvCalcElemSize( const char* dt, int initial_size ) } +static int +icvCalcStructSize( const char* dt, int initial_size ) +{ + int size = icvCalcElemSize( dt, initial_size ); + int elem_max_size = 0; + for ( const char * type = dt; *type != '\0'; type++ ) { + switch ( *type ) + { + case 'u': { if (elem_max_size < sizeof(uchar)) elem_max_size = sizeof(uchar); break; } + case 'c': { if (elem_max_size < sizeof(schar)) elem_max_size = sizeof(schar); break; } + case 'w': { if (elem_max_size < sizeof(ushort)) elem_max_size = sizeof(ushort); break; } + case 's': { if (elem_max_size < sizeof(short)) elem_max_size = sizeof(short); break; } + case 'i': { if (elem_max_size < sizeof(int)) elem_max_size = sizeof(int); break; } + case 'f': { if (elem_max_size < sizeof(float)) elem_max_size = sizeof(float); break; } + case 'd': { if (elem_max_size < sizeof(double)) elem_max_size = sizeof(double); break; } + default: break; + } + } + size = cvAlign( size, elem_max_size ); + return size; +} + + static int icvDecodeSimpleFormat( const char* dt ) { @@ -3534,7 +3866,7 @@ static int icvFileNodeSeqLen( CvFileNode* node ) { return CV_NODE_IS_COLLECTION(node->tag) ? node->data.seq->total : - CV_NODE_TYPE(node->tag) != CV_NODE_NONE; + CV_NODE_TYPE(node->tag) != CV_NODE_NONE; } @@ -5680,4 +6012,1008 @@ void read(const FileNode& node, String& value, const String& default_value) } + + + + + + + + +/**************************************************************************** + * Newly added for Base64 + * + * + ***************************************************************************/ + + +/**************************************************************************** + * constant + ***************************************************************************/ + +#if CHAR_BIT != 8 +#error "`char` should be 8 bit." +#endif + +uint8_t const base64::base64_mapping[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +uint8_t const base64::base64_padding = '='; + +uint8_t const base64::base64_demapping[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, + 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 0, 0, 0, 0, +}; + +/* `base64_demapping` above is generated in this way: + * ````````````````````````````````````````````````````````````````````` + * std::string mapping((const char *)base64_mapping); + * for (auto ch = 0; ch < 127; ch++) { + * auto i = mapping.find(ch); + * printf("%3u, ", (i != std::string::npos ? i : 0)); + * } + * putchar('\n'); + * ````````````````````````````````````````````````````````````````````` + */ + +/**************************************************************************** + * function + ***************************************************************************/ + +size_t base64::base64_encode(uint8_t const * src, uint8_t * dst, size_t off, size_t cnt) +{ + if (!src || !dst || !cnt) + return 0; + + /* initialize beginning and end */ + uint8_t * dst_beg = dst; + uint8_t * dst_cur = dst_beg; + + uint8_t const * src_beg = src + off; + uint8_t const * src_cur = src_beg; + uint8_t const * src_end = src_cur + cnt / 3U * 3U; + + /* integer multiples part */ + while (src_cur < src_end) { + uint8_t _2 = *src_cur++; + uint8_t _1 = *src_cur++; + uint8_t _0 = *src_cur++; + *dst_cur++ = base64_mapping[ _2 >> 2U]; + *dst_cur++ = base64_mapping[(_1 & 0xF0U) >> 4U | (_2 & 0x03U) << 4U]; + *dst_cur++ = base64_mapping[(_0 & 0xC0U) >> 6U | (_1 & 0x0FU) << 2U]; + *dst_cur++ = base64_mapping[ _0 & 0x3FU]; + } + + /* remainder part */ + size_t rst = src_beg + cnt - src_cur; + if (rst == 1U) { + uint8_t _2 = *src_cur++; + *dst_cur++ = base64_mapping[ _2 >> 2U]; + *dst_cur++ = base64_mapping[(_2 & 0x03U) << 4U]; + } else if (rst == 2U) { + uint8_t _2 = *src_cur++; + uint8_t _1 = *src_cur++; + *dst_cur++ = base64_mapping[ _2 >> 2U]; + *dst_cur++ = base64_mapping[(_2 & 0x03U) << 4U | (_1 & 0xF0U) >> 4U]; + *dst_cur++ = base64_mapping[(_1 & 0x0FU) << 2U]; + } + + /* padding */ + switch (rst) + { + case 1U: *dst_cur++ = base64_padding; + case 2U: *dst_cur++ = base64_padding; + default: *dst_cur = 0; + break; + } + + return static_cast(dst_cur - dst_beg); +} + +size_t base64::base64_encode(char const * src, char * dst, size_t off, size_t cnt) +{ + if (cnt == 0U) + cnt = std::strlen(src); + + return base64_encode + ( + reinterpret_cast(src), + reinterpret_cast(dst), + off, + cnt + ); +} + +size_t base64::base64_decode(uint8_t const * src, uint8_t * dst, size_t off, size_t cnt) +{ + /* check parameters */ + if (!src || !dst || !cnt) + return 0U; + if (cnt & 0x3U) + return 0U; + + /* initialize beginning and end */ + uint8_t * dst_beg = dst; + uint8_t * dst_cur = dst_beg; + + uint8_t const * src_beg = src + off; + uint8_t const * src_cur = src_beg; + uint8_t const * src_end = src_cur + cnt; + + /* start decoding */ + while (src_cur < src_end) { + uint8_t d50 = base64_demapping[*src_cur++]; + uint8_t c50 = base64_demapping[*src_cur++]; + uint8_t b50 = base64_demapping[*src_cur++]; + uint8_t a50 = base64_demapping[*src_cur++]; + + uint8_t b10 = b50 & 0x03U; + uint8_t b52 = b50 & 0x3CU; + uint8_t c30 = c50 & 0x0FU; + uint8_t c54 = c50 & 0x30U; + + *dst_cur++ = (d50 << 2U) | (c54 >> 4U); + *dst_cur++ = (c30 << 4U) | (b52 >> 2U); + *dst_cur++ = (b10 << 6U) | (a50 >> 0U); + } + + *dst_cur = 0; + return size_t(dst_cur - dst_beg); +} + +size_t base64::base64_decode(char const * src, char * dst, size_t off, size_t cnt) +{ + if (cnt == 0U) + cnt = std::strlen(src); + + return base64_decode + ( + reinterpret_cast(src), + reinterpret_cast(dst), + off, + cnt + ); +} + +bool base64::base64_valid(uint8_t const * src, size_t off, size_t cnt) +{ + /* check parameters */ + if (src == nullptr || src + off == nullptr) + return false; + if (cnt == 0U) + cnt = std::strlen(reinterpret_cast(src)); + if (cnt & 0x3U) + return false; + + /* initialize beginning and end */ + uint8_t const * beg = src + off; + uint8_t const * end = beg + cnt; + + /* skip padding */ + if (*(end - 1U) == base64_padding) { + end--; + if (*(end - 1U) == base64_padding) + end--; + } + + /* find illegal characters */ + for (uint8_t const * iter = beg; iter < end; iter++) + if (*iter < 0 || (!base64_demapping[(uint8_t)*iter] && *iter != base64_mapping[0])) + return false; + + return true; +} + +bool base64::base64_valid(char const * src, size_t off, size_t cnt) +{ + if (cnt == 0U) + cnt = std::strlen(src); + + return base64_valid(reinterpret_cast(src), off, cnt); +} + +size_t base64::base64_encode_buffer_size(size_t cnt) +{ + return size_t((cnt + 2U) / 3U * 4U + 1U); +} + +size_t base64::base64_decode_buffer_size(size_t cnt) +{ + return size_t(cnt / 4U * 3U + 1U); +} + +/**************************************************************************** + * to_binary && binary_to + ***************************************************************************/ + +template inline size_t base64:: +to_binary(_uint_t val, uchar * cur) +{ + size_t cnt = sizeof(_uint_t); + while (cnt --> static_cast(0U)) { + *cur++ = static_cast(val); + val >>= CHAR_BIT; + } + return sizeof(_uint_t); +} + +template<> inline size_t base64::to_binary(double val, uchar * cur) +{ + Cv64suf bit64; + bit64.f = val; + return to_binary(bit64.u, cur); +} + +template<> inline size_t base64::to_binary(float val, uchar * cur) +{ + Cv32suf bit32; + bit32.f = val; + return to_binary(bit32.u, cur); +} + +template inline size_t base64:: +to_binary(uchar const * val, uchar * cur) +{ + return to_binary<_primitive_t>(*reinterpret_cast<_primitive_t const *>(val), cur); +} + + +template inline size_t base64:: +binary_to(uchar const * cur, _uint_t & val) +{ + val = static_cast<_uint_t>(0); + for (size_t i = static_cast(0U); i < sizeof(_uint_t); i++) + val |= (static_cast<_uint_t>(*cur++) << (i * CHAR_BIT)); + return sizeof(_uint_t); +} + +template<> inline size_t base64::binary_to(uchar const * cur, double & val) +{ + Cv64suf bit64; + binary_to(cur, bit64.u); + val = bit64.f; + return sizeof(val); +} + +template<> inline size_t base64::binary_to(uchar const * cur, float & val) +{ + Cv32suf bit32; + binary_to(cur, bit32.u); + val = bit32.f; + return sizeof(val); +} + +template inline size_t base64:: +binary_to(uchar const * cur, uchar * val) +{ + return binary_to<_primitive_t>(cur, *reinterpret_cast<_primitive_t *>(val)); +} + +/**************************************************************************** + * others + ***************************************************************************/ + +std::string base64::make_base64_header(int byte_size, const char * dt) +{ + int size = byte_size; + + std::ostringstream oss; + oss << size << ' ' + << dt << ' '; + std::string buffer(oss.str()); + if (buffer.size() > HEADER_SIZE) + CV_Assert(0); // error! header is too long + + buffer.reserve(HEADER_SIZE); + while (buffer.size() < HEADER_SIZE) + buffer += ' '; + + return buffer; +} + +bool base64::read_base64_header(std::string const & header, int & byte_size, std::string & dt) +{ + std::istringstream iss(header); + return static_cast(iss >> byte_size >> dt); +} + +/**************************************************************************** + * Parser + ***************************************************************************/ + +base64::Base64ContextParser::Base64ContextParser(uchar * buffer, size_t size) + : dst_beg(buffer) + , dst_cur(buffer) + , dst_end(buffer + size) + , base64_buffer(BUFFER_LEN) + , src_beg(0) + , src_end(0) + , src_cur(0) + , binary_buffer(base64_encode_buffer_size(BUFFER_LEN)) +{ + src_beg = binary_buffer.data(); + src_cur = src_beg; + src_end = src_beg + BUFFER_LEN; +} + +base64::Base64ContextParser::~Base64ContextParser() +{ + if (src_cur != src_beg) { + /* encode the rest binary data to base64 buffer */ + flush(); + } +} + +base64::Base64ContextParser & base64::Base64ContextParser:: +read(const uchar * beg, const uchar * end) +{ + if (beg >= end) + return *this; + + while (beg < end) { + /* collect binary data and copy to binary buffer */ + size_t len = std::min(end - beg, src_end - src_cur); + std::memcpy(src_cur, beg, len); + beg += len; + src_cur += len; + + if (src_cur >= src_end) { + /* binary buffer is full. */ + /* decode it send result to dst */ + + CV_Assert(flush()); /* check for base64_valid */ + } + } + + return *this; +} + +bool base64::Base64ContextParser::flush() +{ + if (!base64_valid(src_beg, 0U, src_cur - src_beg)) + return false; + + uchar * buffer = binary_buffer.data(); + size_t len = base64_decode(src_beg, buffer, 0U, src_cur - src_beg); + src_cur = src_beg; + + /* unexpected error */ + CV_Assert(len != 0); + + /* buffer is full */ + CV_Assert(dst_cur + len < dst_end); + + if (dst_cur + len < dst_end) { + /* send data to dst */ + std::memcpy(dst_cur, buffer, len); + dst_cur += len; + } + + return true; +} + +/**************************************************************************** + * Emitter + ***************************************************************************/ + +/* A decorator for CvFileStorage + * - no copyable + * - not safe for now + * - move constructor may be needed if C++11 + */ +class base64::Base64ContextEmitter +{ +public: + explicit Base64ContextEmitter(CvFileStorage * fs) + : file_storage(fs) + , binary_buffer(BUFFER_LEN) + , base64_buffer(base64_encode_buffer_size(BUFFER_LEN)) + , src_beg(0) + , src_end(0) + , src_cur(0) + { + src_beg = binary_buffer.data(); + src_end = src_beg + BUFFER_LEN; + src_cur = src_beg; + + // TODO: check if fs.state is valid. + + ::icvFSFlush(file_storage); + } + + ~Base64ContextEmitter() + { + /* cleaning */ + if (src_cur != src_beg) + flush(); /* encode the rest binary data to base64 buffer */ + } + + Base64ContextEmitter & write(const uchar * beg, const uchar * end) + { + if (beg >= end) + return *this; + + while (beg < end) { + /* collect binary data and copy to binary buffer */ + size_t len = std::min(end - beg, src_end - src_cur); + std::copy_n(beg, len, src_cur); + beg += len; + src_cur += len; + + if (src_cur >= src_end) { + /* binary buffer is full. */ + /* encode it to base64 and send result to fs */ + flush(); + } + } + + return *this; + } + + /* + * a convertor must provide : + * - `operator >> (uchar * & dst)` for writting current binary data to `dst` and moving to next data. + * - `operator bool` for checking if current loaction is valid and not the end. + */ + template inline + Base64ContextEmitter & write(_to_binary_convertor_t & convertor) + { + static const size_t BUFFER_MAX_LEN = 1024U; + + std::vector buffer(BUFFER_MAX_LEN); + uchar * beg = buffer.data(); + uchar * end = beg; + + while (convertor) { + convertor >> end; + write(beg, end); + end = beg; + } + + return *this; + } + + bool flush() + { + /* controll line width, so on. */ + size_t len = base64_encode(src_beg, base64_buffer.data(), 0U, src_cur - src_beg); + if (len == 0U) + return false; + + src_cur = src_beg; + { + // TODO: better solutions. + const char newline[] = "\n"; + char space[80]; + + int ident = file_storage->struct_indent; + memset(space, ' ', ident); + space[ident] = '\0'; + + ::icvPuts(file_storage, space); + ::icvPuts(file_storage, (const char*)base64_buffer.data()); + ::icvPuts(file_storage, newline); + ::icvFSFlush(file_storage); + } + + return true; + } + +private: + /* because of Base64, we must keep its length a multiple of 3 */ + static const size_t BUFFER_LEN = 51U; + // static_assert(BUFFER_LEN % 3 == 0, "BUFFER_LEN is invalid"); + +private: + CvFileStorage * file_storage; + + std::vector binary_buffer; + std::vector base64_buffer; + uchar * src_beg; + uchar * src_end; + uchar * src_cur; +}; + +class base64::MatToBinaryConvertor +{ +public: + + explicit MatToBinaryConvertor(const cv::Mat & src) + : y (0) + , y_max(0) + , x(0) + , x_max(0) + { + /* make sure each mat `mat.dims == 2` */ + if (src.dims > 2) { + const cv::Mat * arrays[] = { &src, 0 }; + cv::Mat plane; + cv::NAryMatIterator it(arrays, &plane, 1); + + CV_Assert(it.nplanes > 0U); /* make sure mats not empty */ + mats.reserve(it.nplanes); + for (size_t i = 0U; i < it.nplanes; ++i, ++it) + mats.push_back(*it.planes); + } else { + mats.push_back(src); + } + + /* set all to beginning */ + mat_iter = mats.begin(); + y_max = (mat_iter)->rows; + x_max = (mat_iter)->cols * (mat_iter)->elemSize(); + row_begin = (mat_iter)->ptr(0); + step = (mat_iter)->elemSize1(); + + /* choose a function */ + switch ((mat_iter)->depth()) + { + case CV_8U : + case CV_8S : { to_binary_func = to_binary ; break; } + case CV_16U: + case CV_16S: { to_binary_func = to_binary; break; } + case CV_32S: { to_binary_func = to_binary ; break; } + case CV_32F: { to_binary_func = to_binary ; break; } + case CV_64F: { to_binary_func = to_binary; break; } + case CV_USRTYPE1: + default: { CV_Assert(0); break; } + }; + + /* check if empty */ + if (mats.empty() || mats.front().empty() || mats.front().data == 0) { + mat_iter = mats.end(); + CV_Assert(!(*this)); + } + + } + + inline MatToBinaryConvertor & operator >> (uchar * & dst) + { + CV_DbgAssert(*this); + + /* copy to dst */ + dst += to_binary_func(row_begin + x, dst); + + /* move to next */ + x += step; + if (x >= x_max) { + /* when x arrive end, reset it and increase y */ + x = 0U; + ++ y; + if (y >= y_max) { + /* when y arrive end, reset it and increase iter */ + y = 0U; + ++ mat_iter; + if (mat_iter == mats.end()) { + ;/* when iter arrive end, all done */ + } else { + /* usually x_max and y_max won't change */ + y_max = (mat_iter)->rows; + x_max = (mat_iter)->cols * (mat_iter)->elemSize(); + row_begin = (mat_iter)->ptr(y); + } + } else + row_begin = (mat_iter)->ptr(y); + } + + return *this; + } + + inline explicit operator bool() const + { + return mat_iter != mats.end(); + } + +private: + + size_t x; + size_t x_max; + size_t y; + size_t y_max; + std::vector::iterator mat_iter; + std::vector mats; + + size_t step; + const uchar * row_begin; + + typedef size_t(*to_binary_t)(const uchar *, uchar *); + to_binary_t to_binary_func; +}; + +class base64::RawDataToBinaryConvertor +{ +public: + + RawDataToBinaryConvertor(const void* src, int len, const char* dt) + : beg(reinterpret_cast(src)) + , cur(0) + , end(0) + { + CV_Assert(src); + CV_Assert(dt); + CV_Assert(len > 0); + + /* calc step and to_binary_funcs */ + make_to_binary_funcs(dt); + + end = beg; + cur = beg; + + step = ::icvCalcStructSize(dt, 0); + end = beg + step * static_cast(len); + } + + inline RawDataToBinaryConvertor & operator >>(uchar * & dst) + { + CV_DbgAssert(*this); + + for (size_t i = 0U, n = to_binary_funcs.size(); i < n; i++) { + elem_to_binary_t & pack = to_binary_funcs[i]; + pack.func(cur + pack.offset, dst + pack.offset); + } + cur += step; + dst += step; + + return *this; + } + + inline explicit operator bool() const + { + return cur < end; + } + +private: + typedef size_t(*to_binary_t)(const uchar *, uchar *); + struct elem_to_binary_t + { + size_t offset; + to_binary_t func; + }; + +private: + void make_to_binary_funcs(const char* dt) + { + size_t cnt = 0; + size_t offset = 0; + char type = '\0'; + + std::istringstream iss(dt); + while (!iss.eof()) { + if (!(iss >> cnt)) { + iss.clear(); + cnt = 1; + } + CV_Assert(cnt > 0U); + if (!(iss >> type)) + break; + + while (cnt-- > 0) + { + to_binary_funcs.emplace_back(); + elem_to_binary_t & pack = to_binary_funcs.back(); + + size_t size = 0; + switch (type) + { + case 'u': + case 'c': + size = sizeof(uchar); + pack.func = to_binary; + break; + case 'w': + case 's': + size = sizeof(ushort); + pack.func = to_binary; + break; + case 'i': + size = sizeof(uint); + pack.func = to_binary; + break; + case 'f': + size = sizeof(float); + pack.func = to_binary; + break; + case 'd': + size = sizeof(double); + pack.func = to_binary; + break; + case 'r': + default: { CV_Assert(0); break; } + }; + + offset = static_cast(cvAlign(offset, size)); + pack.offset = offset; + offset += size; + } + } + + CV_Assert(iss.eof()); + } + +private: + const uchar * cur; + const uchar * beg; + const uchar * end; + + size_t step; + std::vector to_binary_funcs; +}; + +class base64::BinaryToCvSeqConvertor +{ +public: + BinaryToCvSeqConvertor(const void* src, int len, const char* dt) + : cur(reinterpret_cast(src)) + , beg(reinterpret_cast(src)) + , end(reinterpret_cast(src)) + { + CV_Assert(src); + CV_Assert(dt); + CV_Assert(len >= 0); + + /* calc binary_to_funcs */ + make_funcs(dt); + functor_iter = binary_to_funcs.begin(); + + step = ::icvCalcStructSize(dt, 0); + end = beg + step * static_cast(len); + } + + inline BinaryToCvSeqConvertor & operator >> (CvFileNode & dst) + { + CV_DbgAssert(*this); + + /* get current data */ + uchar buffer[sizeof(double)] = {0}; + functor_iter->func(cur + functor_iter->offset, buffer); + + /* set node::data */ + switch (functor_iter->cv_type) + { + case CV_8U : { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} + case CV_8S : { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} + case CV_16U: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} + case CV_16S: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} + case CV_32S: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} + case CV_32F: { dst.data.f = cv::saturate_cast(*reinterpret_cast(buffer)); break;} + case CV_64F: { dst.data.f = cv::saturate_cast(*reinterpret_cast(buffer)); break;} + default: break; + } + + /* set node::tag */ + switch (functor_iter->cv_type) + { + case CV_8U : + case CV_8S : + case CV_16U: + case CV_16S: + case CV_32S: { dst.tag = CV_NODE_INT; /*std::printf("%i,", dst.data.i);*/ break; } + case CV_32F: + case CV_64F: { dst.tag = CV_NODE_REAL; /*std::printf("%.1f,", dst.data.f);*/ break; } + default: break; + } + + /* check if end */ + if (++functor_iter == binary_to_funcs.end()) { + functor_iter = binary_to_funcs.begin(); + cur += step; + } + + return *this; + } + + inline explicit operator bool() const + { + return cur < end; + } + +private: + typedef size_t(*binary_to_t)(uchar const *, uchar *); + struct binary_to_filenode_t + { + size_t cv_type; + size_t offset; + binary_to_t func; + }; + +private: + void make_funcs(const char* dt) + { + size_t cnt = 0; + char type = '\0'; + int offset = 0; + + std::istringstream iss(dt); + while (!iss.eof()) { + if (!(iss >> cnt)) { + iss.clear(); + cnt = 1; + } + CV_Assert(cnt > 0U); + if (!(iss >> type)) + break; + + while (cnt-- > 0) + { + binary_to_funcs.emplace_back(); + binary_to_filenode_t & pack = binary_to_funcs.back(); + + /* set func and offset */ + size_t size = 0; + switch (type) + { + case 'u': + case 'c': + size = sizeof(uchar); + pack.func = binary_to; + break; + case 'w': + case 's': + size = sizeof(ushort); + pack.func = binary_to; + break; + case 'i': + size = sizeof(uint); + pack.func = binary_to; + break; + case 'f': + size = sizeof(float); + pack.func = binary_to; + break; + case 'd': + size = sizeof(double); + pack.func = binary_to; + break; + case 'r': + default: { CV_Assert(0); break; } + }; + + offset = static_cast(cvAlign(offset, size)); + pack.offset = offset; + offset += size; + + /* set type */ + switch (type) + { + case 'u': { pack.cv_type = CV_8U ; break; } + case 'c': { pack.cv_type = CV_8S ; break; } + case 'w': { pack.cv_type = CV_16U; break; } + case 's': { pack.cv_type = CV_16S; break; } + case 'i': { pack.cv_type = CV_32S; break; } + case 'f': { pack.cv_type = CV_32F; break; } + case 'd': { pack.cv_type = CV_64F; break; } + case 'r': + default: { CV_Assert(0); break; } + } + } + } + + CV_Assert(iss.eof()); + CV_Assert(binary_to_funcs.size()); + } + +private: + + const uchar * cur; + const uchar * beg; + const uchar * end; + + size_t step; + std::vector binary_to_funcs; + std::vector::iterator functor_iter; +}; + + + +/**************************************************************************** + * Wapper + ***************************************************************************/ + +void base64::make_seq(void * binary, int elem_cnt, const char * dt, CvSeq & seq) +{ + CvFileNode node; + node.info = 0; + BinaryToCvSeqConvertor convertor(binary, elem_cnt, dt); + while (convertor) { + convertor >> node; + cvSeqPush(&seq, &node); + } +} + +void base64::cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int len, const char* dt) +{ + cvStartWriteStruct(*fs, fs.elname.c_str(), CV_NODE_SEQ, "binary"); + { + Base64ContextEmitter emitter(*fs); + { /* header */ + /* total byte size(before encode) */ + int size = len * ::icvCalcStructSize(dt, 0); + std::string buffer = make_base64_header(size, dt); + const uchar * beg = reinterpret_cast(buffer.data()); + const uchar * end = beg + buffer.size(); + + emitter.write(beg, end); + } + { /* body */ + RawDataToBinaryConvertor convert(_data, len, dt); + emitter.write(convert); + } + } + cvEndWriteStruct(*fs); +} + +void base64::cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv::Mat const & mat) +{ + char dt[4]; + ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt); + + { /* [1]output other attr */ + + if (mat.dims <= 2) { + cvStartWriteStruct(*fs, name.c_str(), CV_NODE_MAP, CV_TYPE_NAME_MAT); + + cvWriteInt(*fs, "rows", mat.rows ); + cvWriteInt(*fs, "cols", mat.cols ); + } else { + cvStartWriteStruct(*fs, name.c_str(), CV_NODE_MAP, CV_TYPE_NAME_MATND); + + cvStartWriteStruct(*fs, "sizes", CV_NODE_SEQ | CV_NODE_FLOW); + cvWriteRawData(*fs, mat.size.p, mat.dims, "i"); + cvEndWriteStruct(*fs); + } + cvWriteString(*fs, "dt", ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt ), 0 ); + } + + cvStartWriteStruct(*fs, "data", CV_NODE_SEQ, "binary"); + { /* [2]deal with matrix's data */ + Base64ContextEmitter emitter(*fs); + + { /* [2][1]define base64 header */ + /* total byte size */ + int size = mat.total() * mat.elemSize(); + std::string buffer = make_base64_header(size, dt); + const uchar * beg = reinterpret_cast(buffer.data()); + const uchar * end = beg + buffer.size(); + + emitter.write(beg, end); + } + + { /* [2][2]base64 body */ + MatToBinaryConvertor convertor(mat); + + emitter.write(convertor); + } + } + cvEndWriteStruct(*fs); + + { /* [3]output end */ + cvEndWriteStruct(*fs); + } +} + +/**************************************************************************** + * Interface + ***************************************************************************/ + +namespace cv +{ + void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt) + { + ::base64::cvWriteRawData_Base64(fs, _data, len, dt); + } + + void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat) + { + ::base64::cvWriteMat_Base64(fs, name, mat); + } +} + + /* End of file. */ diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index b53c43c83b..3e1cf6d1f9 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -577,3 +577,124 @@ TEST(Core_InputOutput, FileStorageKey) const std::string expected = "%YAML:1.0\nkey1: value1\n_key2: value2\nkey_3: value3\n"; ASSERT_STREQ(f.releaseAndGetString().c_str(), expected.c_str()); } + +TEST(Core_InputOutput, filestorage_yml_compatibility) +{ + //EXPECT_ANY_THROW(); +} + +TEST(Core_InputOutput, filestorage_yml_base64) +{ + cv::Mat _em_out, _em_in; + cv::Mat _2d_out, _2d_in; + cv::Mat _nd_out, _nd_in; + + { /* init */ + + /* normal mat */ + _2d_out = cv::Mat(1000, 1000, CV_8UC3, cvScalar(1U, 2U, 3U)); + for (int i = 0; i < _2d_out.rows; ++i) + for (int j = 0; j < _2d_out.cols; ++j) + _2d_out.at(i, j)[1] = i % 256; + + /* 4d mat */ + const int Size[] = {4, 4, 4, 4}; + cv::Mat _4d(4, Size, CV_32FC4); + const cv::Range ranges[] = { {0, 2}, {0, 2}, {1, 2}, {0, 2} }; + _nd_out = _4d(ranges); + } + + { /* write */ + cv::FileStorage fs("test.yml", cv::FileStorage::WRITE); + cv::cvWriteMat_Base64(fs, "normal_2d_mat", _2d_out); + cv::cvWriteMat_Base64(fs, "normal_nd_mat", _nd_out); + cv::cvWriteMat_Base64(fs, "empty_2d_mat", _em_out); + fs.release(); + } + + { /* read */ + cv::FileStorage fs("test.yml", cv::FileStorage::READ); + fs["empty_2d_mat"] >> _em_in; + fs["normal_2d_mat"] >> _2d_in; + fs["normal_nd_mat"] >> _nd_in; + fs.release(); + } + + EXPECT_EQ(_em_in.rows , _em_out.rows); + EXPECT_EQ(_em_in.cols , _em_out.cols); + EXPECT_EQ(_em_in.dims , _em_out.dims); + EXPECT_EQ(_em_in.depth(), _em_out.depth()); + EXPECT_TRUE(_em_in.empty()); + + EXPECT_EQ(_2d_in.rows , _2d_in.rows); + EXPECT_EQ(_2d_in.cols , _2d_in.cols); + EXPECT_EQ(_2d_in.dims , _2d_in.dims); + EXPECT_EQ(_2d_in.depth(), _2d_in.depth()); + for(int i = 0; i < _2d_in.rows; ++i) + for (int j = 0; j < _2d_in.cols; ++j) + EXPECT_EQ(_2d_in.at(i, j), _2d_out.at(i, j)); + + EXPECT_EQ(_nd_in.rows , _nd_in.rows); + EXPECT_EQ(_nd_in.cols , _nd_in.cols); + EXPECT_EQ(_nd_in.dims , _nd_in.dims); + EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); + EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0); +} + +TEST(Core_InputOutput, filestorage_xml_base64) +{ + cv::Mat _em_out, _em_in; + cv::Mat _2d_out, _2d_in; + cv::Mat _nd_out, _nd_in; + + { /* init */ + + /* normal mat */ + _2d_out = cv::Mat(1000, 1000, CV_8UC3, cvScalar(1U, 2U, 3U)); + for (int i = 0; i < _2d_out.rows; ++i) + for (int j = 0; j < _2d_out.cols; ++j) + _2d_out.at(i, j)[1] = i % 256; + + /* 4d mat */ + const int Size[] = {4, 4, 4, 4}; + cv::Mat _4d(4, Size, CV_32FC4); + const cv::Range ranges[] = { {0, 2}, {0, 2}, {1, 2}, {0, 2} }; + _nd_out = _4d(ranges); + } + + { /* write */ + cv::FileStorage fs("test.xml", cv::FileStorage::WRITE); + cv::cvWriteMat_Base64(fs, "normal_2d_mat", _2d_out); + cv::cvWriteMat_Base64(fs, "normal_nd_mat", _nd_out); + cv::cvWriteMat_Base64(fs, "empty_2d_mat", _em_out); + fs.release(); + } + + { /* read */ + cv::FileStorage fs("test.xml", cv::FileStorage::READ); + fs["empty_2d_mat"] >> _em_in; + fs["normal_2d_mat"] >> _2d_in; + fs["normal_nd_mat"] >> _nd_in; + fs.release(); + } + + EXPECT_EQ(_em_in.rows , _em_out.rows); + EXPECT_EQ(_em_in.cols , _em_out.cols); + EXPECT_EQ(_em_in.dims , _em_out.dims); + EXPECT_EQ(_em_in.depth(), _em_out.depth()); + EXPECT_TRUE(_em_in.empty()); + + EXPECT_EQ(_2d_in.rows , _2d_in.rows); + EXPECT_EQ(_2d_in.cols , _2d_in.cols); + EXPECT_EQ(_2d_in.dims , _2d_in.dims); + EXPECT_EQ(_2d_in.depth(), _2d_in.depth()); + for(int i = 0; i < _2d_in.rows; ++i) + for (int j = 0; j < _2d_in.cols; ++j) + EXPECT_EQ(_2d_in.at(i, j), _2d_out.at(i, j)); + + EXPECT_EQ(_nd_in.rows , _nd_in.rows); + EXPECT_EQ(_nd_in.cols , _nd_in.cols); + EXPECT_EQ(_nd_in.dims , _nd_in.dims); + EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); + EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0); +} From 7b1f7c8d8ede055df30e1d819e8de3b73dff8b7a Mon Sep 17 00:00:00 2001 From: MYLS Date: Sat, 18 Jun 2016 22:13:49 +0800 Subject: [PATCH 18/95] Add Base64 support for FileStorage 1. Add Base64 support for reading and writing XML\YML file. The two new functions for writing: ```cpp void cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int len, const char* dt); void cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv::Mat const & mat); ``` 2. Change YML file header form `YAML:1.0` to `YAML 1.0`. (standard format) 3. Add test for Base64 part. --- modules/core/test/test_io.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 3e1cf6d1f9..a36b212cdf 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -574,7 +574,7 @@ TEST(Core_InputOutput, FileStorageKey) EXPECT_NO_THROW(f << "key1" << "value1"); EXPECT_NO_THROW(f << "_key2" << "value2"); EXPECT_NO_THROW(f << "key_3" << "value3"); - const std::string expected = "%YAML:1.0\nkey1: value1\n_key2: value2\nkey_3: value3\n"; + const std::string expected = "%YAML 1.0\n---\nkey1: value1\n_key2: value2\nkey_3: value3\n"; ASSERT_STREQ(f.releaseAndGetString().c_str(), expected.c_str()); } From d1b097f409bf4bb3366953ddc36f967760083e83 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sat, 18 Jun 2016 23:28:12 +0800 Subject: [PATCH 19/95] fix most coding style warnings and errors --- modules/core/src/persistence.cpp | 64 ++++++++++++++++---------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 4f323984bf..9c44e0c46a 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -298,9 +298,9 @@ namespace base64 bool flush(); private: static const size_t BUFFER_LEN = 120U; + uchar * dst_beg; uchar * dst_cur; uchar * dst_end; - uchar * dst_beg; std::vector base64_buffer; uchar * src_beg; uchar * src_end; @@ -1114,7 +1114,7 @@ static char* icvYMLParseBase64(CvFileStorage* fs, char* ptr, int indent, CvFileN std::string dt; int total_byte_size = -1; { - if (end - beg < base64::ENCODED_HEADER_SIZE) + if (end - beg < static_cast(base64::ENCODED_HEADER_SIZE)) CV_PARSE_ERROR("Unrecognized Base64 header"); std::vector header(base64::HEADER_SIZE + 1, ' '); @@ -1294,7 +1294,7 @@ icvYMLParseValue( CvFileStorage* fs, char* ptr, CvFileNode* node, if (is_binary_string) { /* for base64 string */ - int indent = ptr - fs->buffer_start; + int indent = static_cast(ptr - fs->buffer_start); ptr = icvYMLParseBase64(fs, ptr, indent, node); } else if( cv_isdigit(c) || @@ -2056,7 +2056,7 @@ static char* icvXMLParseBase64(CvFileStorage* fs, char* ptr, CvFileNode * node) std::string dt; int total_byte_size = -1; { - if (end - beg < base64::ENCODED_HEADER_SIZE) + if (end - beg < static_cast(base64::ENCODED_HEADER_SIZE)) CV_PARSE_ERROR("Unrecognized Base64 header"); std::vector header(base64::HEADER_SIZE + 1, ' '); @@ -3387,7 +3387,7 @@ static int icvCalcStructSize( const char* dt, int initial_size ) { int size = icvCalcElemSize( dt, initial_size ); - int elem_max_size = 0; + size_t elem_max_size = 0; for ( const char * type = dt; *type != '\0'; type++ ) { switch ( *type ) { @@ -3401,7 +3401,7 @@ icvCalcStructSize( const char* dt, int initial_size ) default: break; } } - size = cvAlign( size, elem_max_size ); + size = cvAlign( size, static_cast(elem_max_size) ); return size; } @@ -6035,14 +6035,14 @@ void read(const FileNode& node, String& value, const String& default_value) #error "`char` should be 8 bit." #endif -uint8_t const base64::base64_mapping[] = +base64::uint8_t const base64::base64_mapping[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; -uint8_t const base64::base64_padding = '='; +base64::uint8_t const base64::base64_padding = '='; -uint8_t const base64::base64_demapping[] = { +base64::uint8_t const base64::base64_demapping[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, @@ -6185,7 +6185,7 @@ size_t base64::base64_decode(char const * src, char * dst, size_t off, size_t cn bool base64::base64_valid(uint8_t const * src, size_t off, size_t cnt) { /* check parameters */ - if (src == nullptr || src + off == nullptr) + if (src == 0 || src + off == 0) return false; if (cnt == 0U) cnt = std::strlen(reinterpret_cast(src)); @@ -6205,7 +6205,7 @@ bool base64::base64_valid(uint8_t const * src, size_t off, size_t cnt) /* find illegal characters */ for (uint8_t const * iter = beg; iter < end; iter++) - if (*iter < 0 || (!base64_demapping[(uint8_t)*iter] && *iter != base64_mapping[0])) + if (*iter > 126U || (!base64_demapping[(uint8_t)*iter] && *iter != base64_mapping[0])) return false; return true; @@ -6308,8 +6308,8 @@ std::string base64::make_base64_header(int byte_size, const char * dt) oss << size << ' ' << dt << ' '; std::string buffer(oss.str()); - if (buffer.size() > HEADER_SIZE) - CV_Assert(0); // error! header is too long + if (buffer.size() > HEADER_SIZE) { + CV_Assert(0); } buffer.reserve(HEADER_SIZE); while (buffer.size() < HEADER_SIZE) @@ -6334,8 +6334,8 @@ base64::Base64ContextParser::Base64ContextParser(uchar * buffer, size_t size) , dst_end(buffer + size) , base64_buffer(BUFFER_LEN) , src_beg(0) - , src_end(0) , src_cur(0) + , src_end(0) , binary_buffer(base64_encode_buffer_size(BUFFER_LEN)) { src_beg = binary_buffer.data(); @@ -6443,7 +6443,7 @@ public: while (beg < end) { /* collect binary data and copy to binary buffer */ size_t len = std::min(end - beg, src_end - src_cur); - std::copy_n(beg, len, src_cur); + std::memcpy(src_cur, beg, len); beg += len; src_cur += len; @@ -6597,26 +6597,26 @@ public: /* usually x_max and y_max won't change */ y_max = (mat_iter)->rows; x_max = (mat_iter)->cols * (mat_iter)->elemSize(); - row_begin = (mat_iter)->ptr(y); + row_begin = (mat_iter)->ptr(static_cast(y)); } } else - row_begin = (mat_iter)->ptr(y); + row_begin = (mat_iter)->ptr(static_cast(y)); } return *this; } - inline explicit operator bool() const + inline operator bool() const { return mat_iter != mats.end(); } private: - size_t x; - size_t x_max; size_t y; size_t y_max; + size_t x; + size_t x_max; std::vector::iterator mat_iter; std::vector mats; @@ -6664,7 +6664,7 @@ public: return *this; } - inline explicit operator bool() const + inline operator bool() const { return cur < end; } @@ -6696,8 +6696,7 @@ private: while (cnt-- > 0) { - to_binary_funcs.emplace_back(); - elem_to_binary_t & pack = to_binary_funcs.back(); + elem_to_binary_t pack; size_t size = 0; switch (type) @@ -6728,9 +6727,11 @@ private: default: { CV_Assert(0); break; } }; - offset = static_cast(cvAlign(offset, size)); + offset = static_cast(cvAlign(static_cast(offset), static_cast(size))); pack.offset = offset; offset += size; + + to_binary_funcs.push_back(pack); } } @@ -6738,8 +6739,8 @@ private: } private: - const uchar * cur; const uchar * beg; + const uchar * cur; const uchar * end; size_t step; @@ -6809,7 +6810,7 @@ public: return *this; } - inline explicit operator bool() const + inline operator bool() const { return cur < end; } @@ -6842,8 +6843,7 @@ private: while (cnt-- > 0) { - binary_to_funcs.emplace_back(); - binary_to_filenode_t & pack = binary_to_funcs.back(); + binary_to_filenode_t pack; /* set func and offset */ size_t size = 0; @@ -6875,9 +6875,9 @@ private: default: { CV_Assert(0); break; } }; - offset = static_cast(cvAlign(offset, size)); + offset = static_cast(cvAlign(static_cast(offset), static_cast(size))); pack.offset = offset; - offset += size; + offset += static_cast(size); /* set type */ switch (type) @@ -6892,6 +6892,8 @@ private: case 'r': default: { CV_Assert(0); break; } } + + binary_to_funcs.push_back(pack); } } @@ -6977,7 +6979,7 @@ void base64::cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv { /* [2][1]define base64 header */ /* total byte size */ - int size = mat.total() * mat.elemSize(); + int size = static_cast(mat.total() * mat.elemSize()); std::string buffer = make_base64_header(size, dt); const uchar * beg = reinterpret_cast(buffer.data()); const uchar * end = beg + buffer.size(); From 882e4221e722c92d419d86b2b94ad8c5fc1fd574 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sun, 19 Jun 2016 00:45:51 +0800 Subject: [PATCH 20/95] fix errors from test. Two other test are still needed. 1. Verify the Base64 data. 2. Read an old YML file for compatibility test. --- modules/core/src/persistence.cpp | 55 +++++++++++++++++++------------- modules/core/test/test_io.cpp | 12 +++++-- 2 files changed, 43 insertions(+), 24 deletions(-) diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 9c44e0c46a..d1514ec308 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -303,8 +303,8 @@ namespace base64 uchar * dst_end; std::vector base64_buffer; uchar * src_beg; - uchar * src_end; uchar * src_cur; + uchar * src_end; std::vector binary_buffer; }; @@ -3498,7 +3498,7 @@ cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt ) data += sizeof(size_t); break; default: - assert(0); + CV_Assert(!"elem_type is not support."); return; } @@ -3620,7 +3620,7 @@ cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, data += sizeof(size_t); break; default: - assert(0); + CV_Assert(0); return; } } @@ -3670,7 +3670,7 @@ cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, data += sizeof(size_t); break; default: - assert(0); + CV_Assert(0); return; } } @@ -6236,10 +6236,11 @@ size_t base64::base64_decode_buffer_size(size_t cnt) template inline size_t base64:: to_binary(_uint_t val, uchar * cur) { + size_t delta = CHAR_BIT; size_t cnt = sizeof(_uint_t); while (cnt --> static_cast(0U)) { *cur++ = static_cast(val); - val >>= CHAR_BIT; + val >>= delta; } return sizeof(_uint_t); } @@ -6308,8 +6309,7 @@ std::string base64::make_base64_header(int byte_size, const char * dt) oss << size << ' ' << dt << ' '; std::string buffer(oss.str()); - if (buffer.size() > HEADER_SIZE) { - CV_Assert(0); } + CV_Assert(buffer.size() < HEADER_SIZE); buffer.reserve(HEADER_SIZE); while (buffer.size() < HEADER_SIZE) @@ -6563,7 +6563,7 @@ public: case CV_32F: { to_binary_func = to_binary ; break; } case CV_64F: { to_binary_func = to_binary; break; } case CV_USRTYPE1: - default: { CV_Assert(0); break; } + default: { CV_Assert(!"mat type is invalid"); break; } }; /* check if empty */ @@ -6724,7 +6724,7 @@ private: pack.func = to_binary; break; case 'r': - default: { CV_Assert(0); break; } + default: { CV_Assert(!"type not support"); break; } }; offset = static_cast(cvAlign(static_cast(offset), static_cast(size))); @@ -6772,19 +6772,30 @@ public: CV_DbgAssert(*this); /* get current data */ - uchar buffer[sizeof(double)] = {0}; - functor_iter->func(cur + functor_iter->offset, buffer); + union + { + uchar mem[sizeof(double)]; + uchar u; + char b; + ushort w; + short s; + int i; + float f; + double d; + } buffer; /* for GCC -Wstrict-aliasing */ + std::memset(buffer.mem, 0, sizeof(buffer)); + functor_iter->func(cur + functor_iter->offset, buffer.mem); /* set node::data */ switch (functor_iter->cv_type) { - case CV_8U : { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} - case CV_8S : { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} - case CV_16U: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} - case CV_16S: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} - case CV_32S: { dst.data.i = cv::saturate_cast (*reinterpret_cast(buffer)); break;} - case CV_32F: { dst.data.f = cv::saturate_cast(*reinterpret_cast(buffer)); break;} - case CV_64F: { dst.data.f = cv::saturate_cast(*reinterpret_cast(buffer)); break;} + case CV_8U : { dst.data.i = cv::saturate_cast (buffer.u); break;} + case CV_8S : { dst.data.i = cv::saturate_cast (buffer.b); break;} + case CV_16U: { dst.data.i = cv::saturate_cast (buffer.w); break;} + case CV_16S: { dst.data.i = cv::saturate_cast (buffer.s); break;} + case CV_32S: { dst.data.i = cv::saturate_cast (buffer.i); break;} + case CV_32F: { dst.data.f = cv::saturate_cast(buffer.f); break;} + case CV_64F: { dst.data.f = cv::saturate_cast(buffer.d); break;} default: break; } @@ -6872,8 +6883,8 @@ private: pack.func = binary_to; break; case 'r': - default: { CV_Assert(0); break; } - }; + default: { CV_Assert(!"type not support"); break; } + }; // need a better way for outputting error. offset = static_cast(cvAlign(static_cast(offset), static_cast(size))); pack.offset = offset; @@ -6890,8 +6901,8 @@ private: case 'f': { pack.cv_type = CV_32F; break; } case 'd': { pack.cv_type = CV_64F; break; } case 'r': - default: { CV_Assert(0); break; } - } + default: { CV_Assert(!"type is not support"); break; } + } // need a better way for outputting error. binary_to_funcs.push_back(pack); } diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index a36b212cdf..8ef91a8b2e 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -600,7 +600,11 @@ TEST(Core_InputOutput, filestorage_yml_base64) /* 4d mat */ const int Size[] = {4, 4, 4, 4}; cv::Mat _4d(4, Size, CV_32FC4); - const cv::Range ranges[] = { {0, 2}, {0, 2}, {1, 2}, {0, 2} }; + const cv::Range ranges[] = { + cv::Range(0, 2), + cv::Range(0, 2), + cv::Range(1, 2), + cv::Range(0, 2) }; _nd_out = _4d(ranges); } @@ -658,7 +662,11 @@ TEST(Core_InputOutput, filestorage_xml_base64) /* 4d mat */ const int Size[] = {4, 4, 4, 4}; cv::Mat _4d(4, Size, CV_32FC4); - const cv::Range ranges[] = { {0, 2}, {0, 2}, {1, 2}, {0, 2} }; + const cv::Range ranges[] = { + cv::Range(0, 2), + cv::Range(0, 2), + cv::Range(1, 2), + cv::Range(0, 2) }; _nd_out = _4d(ranges); } From 958263d24556c5ce59d3b50df41b81276e657c14 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sun, 19 Jun 2016 02:00:32 +0800 Subject: [PATCH 21/95] Solve warnings, and adjusted the test case. --- modules/core/src/persistence.cpp | 6 +++--- modules/core/test/test_io.cpp | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index d1514ec308..278ac6f0c9 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -3498,7 +3498,7 @@ cvWriteRawData( CvFileStorage* fs, const void* _data, int len, const char* dt ) data += sizeof(size_t); break; default: - CV_Assert(!"elem_type is not support."); + CV_Error( CV_StsUnsupportedFormat, "Unsupported type" ); return; } @@ -3620,7 +3620,7 @@ cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, data += sizeof(size_t); break; default: - CV_Assert(0); + CV_Error( CV_StsUnsupportedFormat, "Unsupported type" ); return; } } @@ -3670,7 +3670,7 @@ cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, data += sizeof(size_t); break; default: - CV_Assert(0); + CV_Error( CV_StsUnsupportedFormat, "Unsupported type" ); return; } } diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 8ef91a8b2e..1410b26d29 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -592,14 +592,14 @@ TEST(Core_InputOutput, filestorage_yml_base64) { /* init */ /* normal mat */ - _2d_out = cv::Mat(1000, 1000, CV_8UC3, cvScalar(1U, 2U, 3U)); + _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); for (int i = 0; i < _2d_out.rows; ++i) for (int j = 0; j < _2d_out.cols; ++j) _2d_out.at(i, j)[1] = i % 256; /* 4d mat */ const int Size[] = {4, 4, 4, 4}; - cv::Mat _4d(4, Size, CV_32FC4); + cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444)); const cv::Range ranges[] = { cv::Range(0, 2), cv::Range(0, 2), @@ -654,14 +654,14 @@ TEST(Core_InputOutput, filestorage_xml_base64) { /* init */ /* normal mat */ - _2d_out = cv::Mat(1000, 1000, CV_8UC3, cvScalar(1U, 2U, 3U)); + _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); for (int i = 0; i < _2d_out.rows; ++i) for (int j = 0; j < _2d_out.cols; ++j) _2d_out.at(i, j)[1] = i % 256; /* 4d mat */ const int Size[] = {4, 4, 4, 4}; - cv::Mat _4d(4, Size, CV_32FC4); + cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444)); const cv::Range ranges[] = { cv::Range(0, 2), cv::Range(0, 2), @@ -704,5 +704,5 @@ TEST(Core_InputOutput, filestorage_xml_base64) EXPECT_EQ(_nd_in.cols , _nd_in.cols); EXPECT_EQ(_nd_in.dims , _nd_in.dims); EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); - EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0); + EXPECT_EQ(cv::countNonZero(cv::sum(_nd_in != _nd_out)), 0); } From 9faa2a7fd01fc8856dbedb4f133757e8aea194ec Mon Sep 17 00:00:00 2001 From: MYLS Date: Sun, 19 Jun 2016 02:44:39 +0800 Subject: [PATCH 22/95] solve warning for IOS Two test are still needed: 1. Verify the Base64 data. 2. Read an old YML file for compatibility test. --- modules/core/src/persistence.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index 278ac6f0c9..ad8f9eaab1 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -298,7 +298,6 @@ namespace base64 bool flush(); private: static const size_t BUFFER_LEN = 120U; - uchar * dst_beg; uchar * dst_cur; uchar * dst_end; std::vector base64_buffer; @@ -6329,8 +6328,7 @@ bool base64::read_base64_header(std::string const & header, int & byte_size, std ***************************************************************************/ base64::Base64ContextParser::Base64ContextParser(uchar * buffer, size_t size) - : dst_beg(buffer) - , dst_cur(buffer) + : dst_cur(buffer) , dst_end(buffer + size) , base64_buffer(BUFFER_LEN) , src_beg(0) @@ -6840,7 +6838,7 @@ private: { size_t cnt = 0; char type = '\0'; - int offset = 0; + size_t offset = 0; std::istringstream iss(dt); while (!iss.eof()) { @@ -6888,7 +6886,7 @@ private: offset = static_cast(cvAlign(static_cast(offset), static_cast(size))); pack.offset = offset; - offset += static_cast(size); + offset += size; /* set type */ switch (type) From 29921d055df344b44fd5fbd92b80f58b93216886 Mon Sep 17 00:00:00 2001 From: MYLS Date: Mon, 20 Jun 2016 16:59:58 +0800 Subject: [PATCH 23/95] change the parameter to `CvMat` and `CvMatND` ```cpp cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat) ``` becomes: ```cpp CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat); CV_EXPORTS void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat); ``` --- .../core/include/opencv2/core/persistence.hpp | 8 +++- modules/core/src/persistence.cpp | 39 +++++++++++-------- modules/core/test/test_io.cpp | 18 ++++++--- 3 files changed, 41 insertions(+), 24 deletions(-) diff --git a/modules/core/include/opencv2/core/persistence.hpp b/modules/core/include/opencv2/core/persistence.hpp index 23714868bd..6ceeca438b 100644 --- a/modules/core/include/opencv2/core/persistence.hpp +++ b/modules/core/include/opencv2/core/persistence.hpp @@ -89,6 +89,8 @@ the extension of the opened file, ".xml" for XML files and ".yml" or ".yaml" for */ typedef struct CvFileStorage CvFileStorage; typedef struct CvFileNode CvFileNode; +typedef struct CvMat CvMat; +typedef struct CvMatND CvMatND; //! @} core_c @@ -1239,9 +1241,11 @@ inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, * //! @endcond -CV_EXPORTS void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt); +CV_EXPORTS void cvWriteRawData_Base64(FileStorage & fs, const void* _data, int len, const char* dt); -CV_EXPORTS void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat); +CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat); + +CV_EXPORTS void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat); } // cv diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index ad8f9eaab1..fade7a71a4 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -320,7 +320,7 @@ namespace base64 /* sample */ void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt); - void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat); + void cvWriteMat_Base64(CvFileStorage * fs, const char * name, ::cv::Mat const & mat); } @@ -6960,7 +6960,7 @@ void base64::cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int cvEndWriteStruct(*fs); } -void base64::cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv::Mat const & mat) +void base64::cvWriteMat_Base64(CvFileStorage * fs, const char * name, cv::Mat const & mat) { char dt[4]; ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt); @@ -6968,23 +6968,23 @@ void base64::cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv { /* [1]output other attr */ if (mat.dims <= 2) { - cvStartWriteStruct(*fs, name.c_str(), CV_NODE_MAP, CV_TYPE_NAME_MAT); + cvStartWriteStruct(fs, name, CV_NODE_MAP, CV_TYPE_NAME_MAT); - cvWriteInt(*fs, "rows", mat.rows ); - cvWriteInt(*fs, "cols", mat.cols ); + cvWriteInt(fs, "rows", mat.rows ); + cvWriteInt(fs, "cols", mat.cols ); } else { - cvStartWriteStruct(*fs, name.c_str(), CV_NODE_MAP, CV_TYPE_NAME_MATND); + cvStartWriteStruct(fs, name, CV_NODE_MAP, CV_TYPE_NAME_MATND); - cvStartWriteStruct(*fs, "sizes", CV_NODE_SEQ | CV_NODE_FLOW); - cvWriteRawData(*fs, mat.size.p, mat.dims, "i"); - cvEndWriteStruct(*fs); + cvStartWriteStruct(fs, "sizes", CV_NODE_SEQ | CV_NODE_FLOW); + cvWriteRawData(fs, mat.size.p, mat.dims, "i"); + cvEndWriteStruct(fs); } - cvWriteString(*fs, "dt", ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt ), 0 ); + cvWriteString(fs, "dt", ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt ), 0 ); } - cvStartWriteStruct(*fs, "data", CV_NODE_SEQ, "binary"); + cvStartWriteStruct(fs, "data", CV_NODE_SEQ, "binary"); { /* [2]deal with matrix's data */ - Base64ContextEmitter emitter(*fs); + Base64ContextEmitter emitter(fs); { /* [2][1]define base64 header */ /* total byte size */ @@ -7002,10 +7002,10 @@ void base64::cvWriteMat_Base64(cv::FileStorage & fs, cv::String const & name, cv emitter.write(convertor); } } - cvEndWriteStruct(*fs); + cvEndWriteStruct(fs); { /* [3]output end */ - cvEndWriteStruct(*fs); + cvEndWriteStruct(fs); } } @@ -7020,9 +7020,16 @@ namespace cv ::base64::cvWriteRawData_Base64(fs, _data, len, dt); } - void cvWriteMat_Base64(::cv::FileStorage & fs, ::cv::String const & name, ::cv::Mat const & mat) + void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat) { - ::base64::cvWriteMat_Base64(fs, name, mat); + ::cv::Mat holder = ::cv::cvarrToMat(mat); + ::base64::cvWriteMat_Base64(fs, name, holder); + } + + void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat) + { + ::cv::Mat holder = ::cv::cvarrToMat(mat); + ::base64::cvWriteMat_Base64(fs, name, holder); } } diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 1410b26d29..99646e43f0 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -610,9 +610,12 @@ TEST(Core_InputOutput, filestorage_yml_base64) { /* write */ cv::FileStorage fs("test.yml", cv::FileStorage::WRITE); - cv::cvWriteMat_Base64(fs, "normal_2d_mat", _2d_out); - cv::cvWriteMat_Base64(fs, "normal_nd_mat", _nd_out); - cv::cvWriteMat_Base64(fs, "empty_2d_mat", _em_out); + CvMat holder = _2d_out; + cv::cvWriteMat_Base64(*fs, "normal_2d_mat", &holder); + CvMatND holder_nd = _nd_out; + cv::cvWriteMatND_Base64(*fs, "normal_nd_mat", &holder_nd); + holder = _em_out; + cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); fs.release(); } @@ -672,9 +675,12 @@ TEST(Core_InputOutput, filestorage_xml_base64) { /* write */ cv::FileStorage fs("test.xml", cv::FileStorage::WRITE); - cv::cvWriteMat_Base64(fs, "normal_2d_mat", _2d_out); - cv::cvWriteMat_Base64(fs, "normal_nd_mat", _nd_out); - cv::cvWriteMat_Base64(fs, "empty_2d_mat", _em_out); + CvMat holder = _2d_out; + cv::cvWriteMat_Base64(*fs, "normal_2d_mat", &holder); + CvMatND holder_nd = _nd_out; + cv::cvWriteMatND_Base64(*fs, "normal_nd_mat", &holder_nd); + holder = _em_out; + cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); fs.release(); } From 7188e6e2acdc4c581d42096cc4e5a1ea03f51cbe Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Mon, 18 Jan 2016 14:11:02 +0300 Subject: [PATCH 24/95] android: update build scripts --- platforms/android/build-tests/test_cmake_build.py | 5 +++++ platforms/android/build_sdk.py | 14 ++------------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/platforms/android/build-tests/test_cmake_build.py b/platforms/android/build-tests/test_cmake_build.py index 0e84928f0a..f02915c611 100644 --- a/platforms/android/build-tests/test_cmake_build.py +++ b/platforms/android/build-tests/test_cmake_build.py @@ -2,6 +2,9 @@ import unittest import os, sys, subprocess, argparse, shutil, re +import logging as log + +log.basicConfig(format='%(message)s', level=log.DEBUG) CMAKE_TEMPLATE='''\ CMAKE_MINIMUM_REQUIRED(VERSION 2.8) @@ -83,10 +86,12 @@ class TestCmakeBuild(unittest.TestCase): "-DANDROID_TOOLCHAIN_NAME=%s" % self.toolchain, self.srcdir ] + log.info("Executing: %s" % cmd) retcode = subprocess.call(cmd) self.assertEqual(retcode, 0, "cmake failed") cmd = ["ninja"] + log.info("Executing: %s" % cmd) retcode = subprocess.call(cmd) self.assertEqual(retcode, 0, "make failed") diff --git a/platforms/android/build_sdk.py b/platforms/android/build_sdk.py index 812b465e7b..61c9f7d34f 100755 --- a/platforms/android/build_sdk.py +++ b/platforms/android/build_sdk.py @@ -73,8 +73,7 @@ class ABI: def __str__(self): return "%s (%s)" % (self.name, self.toolchain) def haveIPP(self): - return False - # return self.name == "x86" or self.name == "x86_64" + return self.name == "x86" or self.name == "x86_64" ABIs = [ ABI("2", "armeabi-v7a", "arm-linux-androideabi-4.8", cmake_name="armeabi-v7a with NEON"), @@ -143,7 +142,7 @@ class Builder: cmd.append(self.opencvdir) if self.use_ccache == True: - cmd.extend(["-DNDK_CCACHE=ccache", "-DENABLE_PRECOMPILED_HEADERS=OFF"]) + cmd.append("-DNDK_CCACHE=ccache") if do_install: cmd.extend(["-DBUILD_TESTS=ON", "-DINSTALL_TESTS=ON"]) execute(cmd) @@ -238,15 +237,6 @@ class Builder: log.info("Copy docs: %s", self.docdest) shutil.copytree(self.docdest, os.path.join(self.resultdest, "sdk", "java", "javadoc")) - # Patch cmake config - with open(os.path.join(self.resultdest, "sdk", "native", "jni", "OpenCVConfig.cmake"), "r+t") as f: - contents = f.read() - contents, count = re.subn(r'OpenCV_ANDROID_NATIVE_API_LEVEL \d+', "OpenCV_ANDROID_NATIVE_API_LEVEL 8", contents) - f.seek(0) - f.write(contents) - f.truncate() - log.info("Patch cmake config: %s (%d changes)", f.name, count) - # Clean samples path = os.path.join(self.resultdest, "samples") for item in os.listdir(path): From c6c651212cc60a13b46996b62e24df5bd3e2c38d Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Mon, 11 Jan 2016 17:54:14 +0300 Subject: [PATCH 25/95] cmake: refactoring of OpenCVConfig - removed OpenCV_LIB_DIR* vars (they are broken and not required anymore) - OpenCVConfig.cmake doesn't contain ANDROID/CUDA code if there is no such support - removed OpenCV2_INCLUDE_DIRS_CONFIGCMAKE, merged into OpenCV_INCLUDE_DIRS_CONFIGCMAKE - fix hard-coded relative paths for OpenCV_INSTALL_PATH - removed OpenCV_TBB_ARCH - switch OpenCVConfig.cmake into 2-level mode for Android SDK --- CMakeLists.txt | 128 +++++---- cmake/OpenCVFindIPP.cmake | 2 +- cmake/OpenCVGenConfig.cmake | 146 ++++------ cmake/OpenCVUtils.cmake | 28 +- cmake/templates/OpenCVConfig-ANDROID.cmake.in | 13 + cmake/templates/OpenCVConfig-CUDA.cmake.in | 53 ++++ cmake/templates/OpenCVConfig-IPPICV.cmake.in | 7 + cmake/templates/OpenCVConfig.cmake.in | 268 +++--------------- .../OpenCVConfig.root-ANDROID.cmake.in | 50 ++++ .../OpenCVConfig.root-WIN32.cmake.in} | 50 +--- 10 files changed, 323 insertions(+), 422 deletions(-) create mode 100644 cmake/templates/OpenCVConfig-ANDROID.cmake.in create mode 100644 cmake/templates/OpenCVConfig-CUDA.cmake.in create mode 100644 cmake/templates/OpenCVConfig-IPPICV.cmake.in create mode 100644 cmake/templates/OpenCVConfig.root-ANDROID.cmake.in rename cmake/{OpenCVConfig.cmake => templates/OpenCVConfig.root-WIN32.cmake.in} (72%) diff --git a/CMakeLists.txt b/CMakeLists.txt index f043acd614..18887f4712 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -86,8 +86,10 @@ if (POLICY CMP0042) cmake_policy(SET CMP0042 OLD) endif() +include(cmake/OpenCVUtils.cmake) + # must go before the project command -set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE) +ocv_update(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE) if(DEFINED CMAKE_BUILD_TYPE) set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} ) endif() @@ -100,8 +102,6 @@ if(MSVC) set(CMAKE_USE_RELATIVE_PATHS ON CACHE INTERNAL "" FORCE) endif() -include(cmake/OpenCVUtils.cmake) - ocv_cmake_eval(DEBUG_PRE ONCE) ocv_clear_vars(OpenCVModules_TARGETS) @@ -304,50 +304,50 @@ include(cmake/OpenCVVersion.cmake) # ---------------------------------------------------------------------------- # Save libs and executables in the same place -set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin" CACHE PATH "Output directory for applications" ) +set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin" CACHE PATH "Output directory for applications") -if (ANDROID) - if (ANDROID_ABI MATCHES "NEON") +if(ANDROID) + if(ANDROID_ABI MATCHES "NEON") set(ENABLE_NEON ON) endif() - if (ANDROID_ABI MATCHES "VFPV3") + if(ANDROID_ABI MATCHES "VFPV3") set(ENABLE_VFPV3 ON) endif() endif() if(ANDROID OR WIN32) - set(OPENCV_DOC_INSTALL_PATH doc) + ocv_update(OPENCV_DOC_INSTALL_PATH doc) else() - set(OPENCV_DOC_INSTALL_PATH share/OpenCV/doc) + ocv_update(OPENCV_DOC_INSTALL_PATH share/OpenCV/doc) endif() if(WIN32 AND CMAKE_HOST_SYSTEM_NAME MATCHES Windows) if(DEFINED OpenCV_RUNTIME AND DEFINED OpenCV_ARCH) - set(OpenCV_INSTALL_BINARIES_PREFIX "${OpenCV_ARCH}/${OpenCV_RUNTIME}/") + ocv_update(OpenCV_INSTALL_BINARIES_PREFIX "${OpenCV_ARCH}/${OpenCV_RUNTIME}/") else() message(STATUS "Can't detect runtime and/or arch") - set(OpenCV_INSTALL_BINARIES_PREFIX "") + ocv_update(OpenCV_INSTALL_BINARIES_PREFIX "") endif() elseif(ANDROID) - set(OpenCV_INSTALL_BINARIES_PREFIX "sdk/native/") + ocv_update(OpenCV_INSTALL_BINARIES_PREFIX "sdk/native/") else() - set(OpenCV_INSTALL_BINARIES_PREFIX "") + ocv_update(OpenCV_INSTALL_BINARIES_PREFIX "") endif() if(ANDROID) - set(OPENCV_SAMPLES_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}samples/${ANDROID_NDK_ABI_NAME}") + ocv_update(OPENCV_SAMPLES_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}samples/${ANDROID_NDK_ABI_NAME}") else() - set(OPENCV_SAMPLES_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}samples") + ocv_update(OPENCV_SAMPLES_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}samples") endif() if(ANDROID) - set(OPENCV_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}bin/${ANDROID_NDK_ABI_NAME}") + ocv_update(OPENCV_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}bin/${ANDROID_NDK_ABI_NAME}") else() - set(OPENCV_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}bin") + ocv_update(OPENCV_BIN_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}bin") endif() if(NOT OPENCV_TEST_INSTALL_PATH) - set(OPENCV_TEST_INSTALL_PATH "${OPENCV_BIN_INSTALL_PATH}") + ocv_update(OPENCV_TEST_INSTALL_PATH "${OPENCV_BIN_INSTALL_PATH}") endif() if (OPENCV_TEST_DATA_PATH) @@ -356,66 +356,74 @@ endif() if(OPENCV_TEST_DATA_PATH AND NOT OPENCV_TEST_DATA_INSTALL_PATH) if(ANDROID) - set(OPENCV_TEST_DATA_INSTALL_PATH "sdk/etc/testdata") + ocv_update(OPENCV_TEST_DATA_INSTALL_PATH "sdk/etc/testdata") elseif(WIN32) - set(OPENCV_TEST_DATA_INSTALL_PATH "testdata") + ocv_update(OPENCV_TEST_DATA_INSTALL_PATH "testdata") else() - set(OPENCV_TEST_DATA_INSTALL_PATH "share/OpenCV/testdata") + ocv_update(OPENCV_TEST_DATA_INSTALL_PATH "share/OpenCV/testdata") endif() endif() if(ANDROID) - set(LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/lib/${ANDROID_NDK_ABI_NAME}") - set(3P_LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/3rdparty/lib/${ANDROID_NDK_ABI_NAME}") - set(OPENCV_LIB_INSTALL_PATH sdk/native/libs/${ANDROID_NDK_ABI_NAME}) - set(OPENCV_3P_LIB_INSTALL_PATH sdk/native/3rdparty/libs/${ANDROID_NDK_ABI_NAME}) - set(OPENCV_CONFIG_INSTALL_PATH sdk/native/jni) - set(OPENCV_INCLUDE_INSTALL_PATH sdk/native/jni/include) - set(OPENCV_SAMPLES_SRC_INSTALL_PATH samples/native) - set(OPENCV_OTHER_INSTALL_PATH sdk/etc) + set(LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/lib/${ANDROID_NDK_ABI_NAME}") + ocv_update(3P_LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/3rdparty/lib/${ANDROID_NDK_ABI_NAME}") + ocv_update(OPENCV_LIB_INSTALL_PATH sdk/native/libs/${ANDROID_NDK_ABI_NAME}) + ocv_update(OPENCV_3P_LIB_INSTALL_PATH sdk/native/3rdparty/libs/${ANDROID_NDK_ABI_NAME}) + ocv_update(OPENCV_CONFIG_INSTALL_PATH sdk/native/jni) + ocv_update(OPENCV_INCLUDE_INSTALL_PATH sdk/native/jni/include) + ocv_update(OPENCV_SAMPLES_SRC_INSTALL_PATH samples/native) + ocv_update(OPENCV_OTHER_INSTALL_PATH sdk/etc) else() - set(LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/lib") - set(3P_LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/3rdparty/lib${LIB_SUFFIX}") + set(LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/lib") + ocv_update(3P_LIBRARY_OUTPUT_PATH "${OpenCV_BINARY_DIR}/3rdparty/lib${LIB_SUFFIX}") if(WIN32 AND CMAKE_HOST_SYSTEM_NAME MATCHES Windows) if(OpenCV_STATIC) - set(OPENCV_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib${LIB_SUFFIX}") + ocv_update(OPENCV_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib${LIB_SUFFIX}") else() - set(OPENCV_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}lib${LIB_SUFFIX}") + ocv_update(OPENCV_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}lib${LIB_SUFFIX}") endif() - set(OPENCV_3P_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib${LIB_SUFFIX}") - set(OPENCV_SAMPLES_SRC_INSTALL_PATH samples/native) - set(OPENCV_JAR_INSTALL_PATH java) - set(OPENCV_OTHER_INSTALL_PATH etc) + ocv_update(OPENCV_3P_LIB_INSTALL_PATH "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib${LIB_SUFFIX}") + ocv_update(OPENCV_SAMPLES_SRC_INSTALL_PATH samples/native) + ocv_update(OPENCV_JAR_INSTALL_PATH java) + ocv_update(OPENCV_OTHER_INSTALL_PATH etc) + ocv_update(OPENCV_CONFIG_INSTALL_PATH "") else() - set(OPENCV_LIB_INSTALL_PATH lib${LIB_SUFFIX}) - set(OPENCV_3P_LIB_INSTALL_PATH share/OpenCV/3rdparty/${OPENCV_LIB_INSTALL_PATH}) - set(OPENCV_SAMPLES_SRC_INSTALL_PATH share/OpenCV/samples) - set(OPENCV_JAR_INSTALL_PATH share/OpenCV/java) - set(OPENCV_OTHER_INSTALL_PATH share/OpenCV) - endif() - set(OPENCV_INCLUDE_INSTALL_PATH "include") + ocv_update(OPENCV_LIB_INSTALL_PATH lib${LIB_SUFFIX}) + ocv_update(OPENCV_3P_LIB_INSTALL_PATH share/OpenCV/3rdparty/${OPENCV_LIB_INSTALL_PATH}) + ocv_update(OPENCV_SAMPLES_SRC_INSTALL_PATH share/OpenCV/samples) + ocv_update(OPENCV_JAR_INSTALL_PATH share/OpenCV/java) + ocv_update(OPENCV_OTHER_INSTALL_PATH share/OpenCV) - math(EXPR SIZEOF_VOID_P_BITS "8 * ${CMAKE_SIZEOF_VOID_P}") - if(LIB_SUFFIX AND NOT SIZEOF_VOID_P_BITS EQUAL LIB_SUFFIX) - set(OPENCV_CONFIG_INSTALL_PATH lib${LIB_SUFFIX}/cmake/opencv) - else() - set(OPENCV_CONFIG_INSTALL_PATH share/OpenCV) + if(NOT DEFINED OPENCV_CONFIG_INSTALL_PATH) + math(EXPR SIZEOF_VOID_P_BITS "8 * ${CMAKE_SIZEOF_VOID_P}") + if(LIB_SUFFIX AND NOT SIZEOF_VOID_P_BITS EQUAL LIB_SUFFIX) + ocv_update(OPENCV_CONFIG_INSTALL_PATH lib${LIB_SUFFIX}/cmake/opencv) + else() + ocv_update(OPENCV_CONFIG_INSTALL_PATH share/OpenCV) + endif() + endif() endif() + ocv_update(OPENCV_INCLUDE_INSTALL_PATH "include") endif() -set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${OPENCV_LIB_INSTALL_PATH}") +ocv_update(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${OPENCV_LIB_INSTALL_PATH}") set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) if(INSTALL_TO_MANGLED_PATHS) set(OPENCV_INCLUDE_INSTALL_PATH ${OPENCV_INCLUDE_INSTALL_PATH}/opencv-${OPENCV_VERSION}) - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_3P_LIB_INSTALL_PATH "${OPENCV_3P_LIB_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_SAMPLES_SRC_INSTALL_PATH "${OPENCV_SAMPLES_SRC_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_CONFIG_INSTALL_PATH "${OPENCV_CONFIG_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_DOC_INSTALL_PATH "${OPENCV_DOC_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_JAR_INSTALL_PATH "${OPENCV_JAR_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_TEST_DATA_INSTALL_PATH "${OPENCV_TEST_DATA_INSTALL_PATH}") - string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" OPENCV_OTHER_INSTALL_PATH "${OPENCV_OTHER_INSTALL_PATH}") + foreach(v + OPENCV_3P_LIB_INSTALL_PATH + OPENCV_SAMPLES_SRC_INSTALL_PATH + OPENCV_CONFIG_INSTALL_PATH + OPENCV_DOC_INSTALL_PATH + OPENCV_JAR_INSTALL_PATH + OPENCV_TEST_DATA_INSTALL_PATH + OPENCV_OTHER_INSTALL_PATH + ) + string(REPLACE "OpenCV" "OpenCV-${OPENCV_VERSION}" ${v} "${${v}}") + string(REPLACE "opencv" "opencv-${OPENCV_VERSION}" ${v} "${${v}}") + endforeach() endif() @@ -440,7 +448,7 @@ endif() # ---------------------------------------------------------------------------- # Path for build/platform -specific headers # ---------------------------------------------------------------------------- -set(OPENCV_CONFIG_FILE_INCLUDE_DIR "${CMAKE_BINARY_DIR}/" CACHE PATH "Where to create the platform-dependant cvconfig.h") +ocv_update(OPENCV_CONFIG_FILE_INCLUDE_DIR "${CMAKE_BINARY_DIR}/" CACHE PATH "Where to create the platform-dependant cvconfig.h") ocv_include_directories(${OPENCV_CONFIG_FILE_INCLUDE_DIR}) # ---------------------------------------------------------------------------- @@ -453,7 +461,7 @@ set(OPENCV_EXTRA_MODULES_PATH "" CACHE PATH "Where to look for additional OpenCV # ---------------------------------------------------------------------------- find_host_package(Git QUIET) -if(GIT_FOUND) +if(NOT DEFINED OPENCV_VCSVERSION AND GIT_FOUND) execute_process(COMMAND "${GIT_EXECUTABLE}" describe --tags --always --dirty --match "[0-9].[0-9].[0-9]*" WORKING_DIRECTORY "${OpenCV_SOURCE_DIR}" OUTPUT_VARIABLE OPENCV_VCSVERSION @@ -464,7 +472,7 @@ if(GIT_FOUND) if(NOT GIT_RESULT EQUAL 0) set(OPENCV_VCSVERSION "unknown") endif() -else() +elseif(NOT DEFINED OPENCV_VCSVERSION) # We don't have git: set(OPENCV_VCSVERSION "unknown") endif() diff --git a/cmake/OpenCVFindIPP.cmake b/cmake/OpenCVFindIPP.cmake index 3bff766930..43172112f1 100644 --- a/cmake/OpenCVFindIPP.cmake +++ b/cmake/OpenCVFindIPP.cmake @@ -146,7 +146,7 @@ macro(ipp_detect_version) IMPORTED_LOCATION ${IPP_LIBRARY_DIR}/${IPP_LIB_PREFIX}${IPP_PREFIX}${name}${IPP_SUFFIX}${IPP_LIB_SUFFIX} ) list(APPEND IPP_LIBRARIES ipp${name}) - if (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB) + if (NOT BUILD_SHARED_LIBS) # CMake doesn't support "install(TARGETS ${IPP_PREFIX}${name} " command with imported targets install(FILES ${IPP_LIBRARY_DIR}/${IPP_LIB_PREFIX}${IPP_PREFIX}${name}${IPP_SUFFIX}${IPP_LIB_SUFFIX} DESTINATION ${OPENCV_3P_LIB_INSTALL_PATH} COMPONENT dev) diff --git a/cmake/OpenCVGenConfig.cmake b/cmake/OpenCVGenConfig.cmake index 3770d05b4a..29517cdb12 100644 --- a/cmake/OpenCVGenConfig.cmake +++ b/cmake/OpenCVGenConfig.cmake @@ -11,47 +11,20 @@ else() set(OpenCV_USE_MANGLED_PATHS_CONFIGCMAKE FALSE) endif() -if(NOT OpenCV_CUDA_CC) - set(OpenCV_CUDA_CC_CONFIGCMAKE "\"\"") - set(OpenCV_CUDA_VERSION "") -else() - set(OpenCV_CUDA_CC_CONFIGCMAKE "${OpenCV_CUDA_CC}") - set(OpenCV_CUDA_VERSION ${CUDA_VERSION_STRING}) +if(HAVE_CUDA) + ocv_cmake_configure("${CMAKE_CURRENT_LIST_DIR}/templates/OpenCVConfig-CUDA.cmake.in" CUDA_CONFIGCMAKE @ONLY) endif() -if(NOT ANDROID_NATIVE_API_LEVEL) - set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE 0) -else() - set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE "${ANDROID_NATIVE_API_LEVEL}") -endif() - -if(CMAKE_GENERATOR MATCHES "Visual" OR CMAKE_GENERATOR MATCHES "Xcode") - set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE TRUE) -else() - set(OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE FALSE) -endif() - - - -if(WIN32) - if(MINGW) - set(OPENCV_LINK_LIBRARY_SUFFIX ".dll.a") +if(ANDROID) + if(NOT ANDROID_NATIVE_API_LEVEL) + set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE 0) else() - set(OPENCV_LINK_LIBRARY_SUFFIX ".lib") + set(OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE "${ANDROID_NATIVE_API_LEVEL}") endif() + ocv_cmake_configure("${CMAKE_CURRENT_LIST_DIR}/templates/OpenCVConfig-ANDROID.cmake.in" ANDROID_CONFIGCMAKE @ONLY) endif() -#build list of modules available for the OpenCV user -set(OpenCV_LIB_COMPONENTS "") -foreach(m ${OPENCV_MODULES_PUBLIC}) - list(INSERT OpenCV_LIB_COMPONENTS 0 ${${m}_MODULE_DEPS_OPT} ${m}) -endforeach() -ocv_list_unique(OpenCV_LIB_COMPONENTS) -set(OPENCV_MODULES_CONFIGCMAKE ${OpenCV_LIB_COMPONENTS}) -ocv_list_filterout(OpenCV_LIB_COMPONENTS "^opencv_") -if(OpenCV_LIB_COMPONENTS) - list(REMOVE_ITEM OPENCV_MODULES_CONFIGCMAKE ${OpenCV_LIB_COMPONENTS}) -endif() +set(OPENCV_MODULES_CONFIGCMAKE ${OPENCV_MODULES_PUBLIC}) if(BUILD_FAT_JAVA_LIB AND HAVE_opencv_java) list(APPEND OPENCV_MODULES_CONFIGCMAKE opencv_java) @@ -62,33 +35,20 @@ endif() # ------------------------------------------------------------------------------------------- set(OpenCV_INCLUDE_DIRS_CONFIGCMAKE "\"${OPENCV_CONFIG_FILE_INCLUDE_DIR}\" \"${OpenCV_SOURCE_DIR}/include\" \"${OpenCV_SOURCE_DIR}/include/opencv\"") -set(OpenCV2_INCLUDE_DIRS_CONFIGCMAKE "") foreach(m ${OPENCV_MODULES_BUILD}) if(EXISTS "${OPENCV_MODULE_${m}_LOCATION}/include") - list(APPEND OpenCV2_INCLUDE_DIRS_CONFIGCMAKE "${OPENCV_MODULE_${m}_LOCATION}/include") + set(OpenCV_INCLUDE_DIRS_CONFIGCMAKE "${OpenCV_INCLUDE_DIRS_CONFIGCMAKE} \"${OPENCV_MODULE_${m}_LOCATION}/include\"") endif() endforeach() -if(ANDROID AND NOT BUILD_SHARED_LIBS AND HAVE_TBB) - #export TBB headers location because static linkage of TBB might be troublesome if application wants to use TBB itself - list(APPEND OpenCV2_INCLUDE_DIRS_CONFIGCMAKE ${TBB_INCLUDE_DIRS}) -endif() +export(TARGETS ${OpenCVModules_TARGETS} FILE "${CMAKE_BINARY_DIR}/OpenCVModules.cmake") -set(modules_file_suffix "") -if(ANDROID) - # the REPLACE here is needed, because OpenCVModules_armeabi.cmake includes - # OpenCVModules_armeabi-*.cmake, which would match OpenCVModules_armeabi-v7a*.cmake. - string(REPLACE - _ modules_file_suffix "_${ANDROID_NDK_ABI_NAME}") -endif() - -export(TARGETS ${OpenCVModules_TARGETS} FILE "${CMAKE_BINARY_DIR}/OpenCVModules${modules_file_suffix}.cmake") - -if(TARGET ippicv AND (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)) +if(TARGET ippicv AND NOT BUILD_SHARED_LIBS) set(USE_IPPICV TRUE) - file(RELATIVE_PATH INSTALL_PATH_RELATIVE_IPPICV ${CMAKE_BINARY_DIR} ${IPPICV_LOCATION_PATH}) + file(RELATIVE_PATH IPPICV_INSTALL_PATH_RELATIVE_CONFIGCMAKE ${CMAKE_BINARY_DIR} ${IPPICV_LOCATION_PATH}) + ocv_cmake_configure("${CMAKE_CURRENT_LIST_DIR}/templates/OpenCVConfig-IPPICV.cmake.in" IPPICV_CONFIGCMAKE @ONLY) else() set(USE_IPPICV FALSE) - set(INSTALL_PATH_RELATIVE_IPPICV "non-existed-path") endif() configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig.cmake.in" "${CMAKE_BINARY_DIR}/OpenCVConfig.cmake" @ONLY) @@ -98,58 +58,60 @@ configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig-version.cmake. # -------------------------------------------------------------------------------------------- # Part 2/3: ${BIN_DIR}/unix-install/OpenCVConfig.cmake -> For use *with* "make install" # ------------------------------------------------------------------------------------------- -set(OpenCV_INCLUDE_DIRS_CONFIGCMAKE "\"\${OpenCV_INSTALL_PATH}/${OPENCV_INCLUDE_INSTALL_PATH}/opencv" "\${OpenCV_INSTALL_PATH}/${OPENCV_INCLUDE_INSTALL_PATH}\"") +file(RELATIVE_PATH OpenCV_INSTALL_PATH_RELATIVE_CONFIGCMAKE "${CMAKE_INSTALL_PREFIX}/${OPENCV_CONFIG_INSTALL_PATH}/" ${CMAKE_INSTALL_PREFIX}) +set(OpenCV_INCLUDE_DIRS_CONFIGCMAKE "\"\${OpenCV_INSTALL_PATH}/${OPENCV_INCLUDE_INSTALL_PATH}\" \"\${OpenCV_INSTALL_PATH}/${OPENCV_INCLUDE_INSTALL_PATH}/opencv\"") -set(OpenCV2_INCLUDE_DIRS_CONFIGCMAKE "\"\"") -set(OpenCV_3RDPARTY_LIB_DIRS_CONFIGCMAKE "\"\${OpenCV_INSTALL_PATH}/${OPENCV_3P_LIB_INSTALL_PATH}\"") +if(USE_IPPICV) + file(RELATIVE_PATH IPPICV_INSTALL_PATH_RELATIVE_CONFIGCMAKE "${CMAKE_INSTALL_PREFIX}" ${IPPICV_INSTALL_PATH}) + ocv_cmake_configure("${CMAKE_CURRENT_LIST_DIR}/templates/OpenCVConfig-IPPICV.cmake.in" IPPICV_CONFIGCMAKE @ONLY) +endif() -if(UNIX) # ANDROID configuration is created here also - #http://www.vtk.org/Wiki/CMake/Tutorials/Packaging reference - # For a command "find_package( [major[.minor]] [EXACT] [REQUIRED|QUIET])" - # cmake will look in the following dir on unix: - # /(share|lib)/cmake/*/ (U) - # /(share|lib)/*/ (U) - # /(share|lib)/*/(cmake|CMake)/ (U) - if(USE_IPPICV) - file(RELATIVE_PATH INSTALL_PATH_RELATIVE_IPPICV "${CMAKE_INSTALL_PREFIX}/${OPENCV_CONFIG_INSTALL_PATH}/" ${IPPICV_INSTALL_PATH}) +function(ocv_gen_config TMP_DIR NESTED_PATH ROOT_NAME) + ocv_path_join(__install_nested "${OPENCV_CONFIG_INSTALL_PATH}" "${NESTED_PATH}") + ocv_path_join(__tmp_nested "${TMP_DIR}" "${NESTED_PATH}") + + file(RELATIVE_PATH OpenCV_INSTALL_PATH_RELATIVE_CONFIGCMAKE "${CMAKE_INSTALL_PREFIX}/${__install_nested}" "${CMAKE_INSTALL_PREFIX}/") + + configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig-version.cmake.in" "${TMP_DIR}/OpenCVConfig-version.cmake" @ONLY) + + configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig.cmake.in" "${__tmp_nested}/OpenCVConfig.cmake" @ONLY) + install(EXPORT OpenCVModules DESTINATION "${__install_nested}" FILE OpenCVModules.cmake COMPONENT dev) + install(FILES + "${TMP_DIR}/OpenCVConfig-version.cmake" + "${__tmp_nested}/OpenCVConfig.cmake" + DESTINATION "${CMAKE_INSTALL_PREFIX}/${__install_nested}" COMPONENT dev) + + if(ROOT_NAME) + # Root config file + configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/${ROOT_NAME}" "${TMP_DIR}/OpenCVConfig.cmake" @ONLY) + install(FILES + "${TMP_DIR}/OpenCVConfig-version.cmake" + "${TMP_DIR}/OpenCVConfig.cmake" + DESTINATION "${CMAKE_INSTALL_PREFIX}/${OPENCV_CONFIG_INSTALL_PATH}" COMPONENT dev) endif() - configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig.cmake.in" "${CMAKE_BINARY_DIR}/unix-install/OpenCVConfig.cmake" @ONLY) - configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig-version.cmake.in" "${CMAKE_BINARY_DIR}/unix-install/OpenCVConfig-version.cmake" @ONLY) - install(FILES "${CMAKE_BINARY_DIR}/unix-install/OpenCVConfig.cmake" DESTINATION ${OPENCV_CONFIG_INSTALL_PATH}/ COMPONENT dev) - install(FILES ${CMAKE_BINARY_DIR}/unix-install/OpenCVConfig-version.cmake DESTINATION ${OPENCV_CONFIG_INSTALL_PATH}/ COMPONENT dev) - install(EXPORT OpenCVModules DESTINATION ${OPENCV_CONFIG_INSTALL_PATH}/ FILE OpenCVModules${modules_file_suffix}.cmake COMPONENT dev) +endfunction() + +if(UNIX AND NOT ANDROID) + ocv_gen_config("${CMAKE_BINARY_DIR}/unix-install" "" "") endif() if(ANDROID) - install(FILES "${OpenCV_SOURCE_DIR}/platforms/android/android.toolchain.cmake" DESTINATION ${OPENCV_CONFIG_INSTALL_PATH}/ COMPONENT dev) + ocv_gen_config("${CMAKE_BINARY_DIR}/unix-install" "abi-${ANDROID_NDK_ABI_NAME}" "OpenCVConfig.root-ANDROID.cmake.in") + install(FILES "${OpenCV_SOURCE_DIR}/platforms/android/android.toolchain.cmake" DESTINATION "${OPENCV_CONFIG_INSTALL_PATH}" COMPONENT dev) endif() # -------------------------------------------------------------------------------------------- # Part 3/3: ${BIN_DIR}/win-install/OpenCVConfig.cmake -> For use within binary installers/packages # -------------------------------------------------------------------------------------------- if(WIN32) - set(OpenCV_INCLUDE_DIRS_CONFIGCMAKE "\"\${OpenCV_CONFIG_PATH}/include\" \"\${OpenCV_CONFIG_PATH}/include/opencv\"") - set(OpenCV2_INCLUDE_DIRS_CONFIGCMAKE "\"\"") - - exec_program(mkdir ARGS "-p \"${CMAKE_BINARY_DIR}/win-install/\"" OUTPUT_VARIABLE RET_VAL) - if(USE_IPPICV) - file(RELATIVE_PATH INSTALL_PATH_RELATIVE_IPPICV "${CMAKE_INSTALL_PREFIX}/${OpenCV_INSTALL_BINARIES_PREFIX}staticlib" ${IPPICV_INSTALL_PATH}) - endif() - configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig.cmake.in" "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig.cmake" @ONLY) - configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/OpenCVConfig-version.cmake.in" "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig-version.cmake" @ONLY) - if (CMAKE_HOST_SYSTEM_NAME MATCHES Windows) + if(CMAKE_HOST_SYSTEM_NAME MATCHES Windows) if(BUILD_SHARED_LIBS) - install(FILES "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig.cmake" DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}lib" COMPONENT dev) - install(EXPORT OpenCVModules DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}lib" FILE OpenCVModules${modules_file_suffix}.cmake COMPONENT dev) + set(_lib_suffix "lib") else() - install(FILES "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig.cmake" DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib" COMPONENT dev) - install(EXPORT OpenCVModules DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}staticlib" FILE OpenCVModules${modules_file_suffix}.cmake COMPONENT dev) + set(_lib_suffix "staticlib") endif() - install(FILES "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig-version.cmake" DESTINATION ./ COMPONENT dev) - install(FILES "${OpenCV_SOURCE_DIR}/cmake/OpenCVConfig.cmake" DESTINATION ./ COMPONENT dev) - else () - install(FILES "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig.cmake" DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}lib/cmake/opencv-${OPENCV_VERSION}" COMPONENT dev) - install(EXPORT OpenCVModules DESTINATION "${OpenCV_INSTALL_BINARIES_PREFIX}lib/cmake/opencv-${OPENCV_VERSION}" FILE OpenCVModules${modules_file_suffix}.cmake COMPONENT dev) - install(FILES "${CMAKE_BINARY_DIR}/win-install/OpenCVConfig-version.cmake" DESTINATION "lib/cmake/opencv-${OPENCV_VERSION}" COMPONENT dev) - endif () + ocv_gen_config("${CMAKE_BINARY_DIR}/win-install" "${OpenCV_INSTALL_BINARIES_PREFIX}${_lib_suffix}" "OpenCVConfig.root-WIN32.cmake.in") + else() + ocv_gen_config("${CMAKE_BINARY_DIR}/win-install" "" "") + endif() endif() diff --git a/cmake/OpenCVUtils.cmake b/cmake/OpenCVUtils.cmake index a17e255488..2816100872 100644 --- a/cmake/OpenCVUtils.cmake +++ b/cmake/OpenCVUtils.cmake @@ -30,6 +30,19 @@ function(ocv_cmake_eval var_name) endif() endfunction() +macro(ocv_cmake_configure file_name var_name) + configure_file(${file_name} "${CMAKE_BINARY_DIR}/CMakeConfig-${var_name}.cmake" ${ARGN}) + file(READ "${CMAKE_BINARY_DIR}/CMakeConfig-${var_name}.cmake" ${var_name}) +endmacro() + +macro(ocv_update VAR) + if(NOT DEFINED ${VAR}) + set(${VAR} ${ARGN}) + else() + #ocv_debug_message("Preserve old value for ${VAR}: ${${VAR}}") + endif() +endmacro() + # Search packages for host system instead of packages for target system # in case of cross compilation thess macro should be defined by toolchain file if(NOT COMMAND find_host_package) @@ -71,6 +84,19 @@ macro(ocv_check_environment_variables) endforeach() endmacro() +macro(ocv_path_join result_var P1 P2) + string(REGEX REPLACE "^[/]+" "" P2 "${P2}") + if("${P1}" STREQUAL "") + set(${result_var} "${P2}") + elseif("${P1}" STREQUAL "/") + set(${result_var} "/${P2}") + elseif("${P2}" STREQUAL "") + set(${result_var} "${P1}") + else() + set(${result_var} "${P1}/${P2}") + endif() +endmacro() + # rename modules target to world if needed macro(_ocv_fix_target target_var) if(BUILD_opencv_world) @@ -359,7 +385,7 @@ macro(CHECK_MODULE module_name define) endmacro() -set(OPENCV_BUILD_INFO_FILE "${OpenCV_BINARY_DIR}/version_string.tmp") +set(OPENCV_BUILD_INFO_FILE "${CMAKE_BINARY_DIR}/version_string.tmp") file(REMOVE "${OPENCV_BUILD_INFO_FILE}") function(ocv_output_status msg) message(STATUS "${msg}") diff --git a/cmake/templates/OpenCVConfig-ANDROID.cmake.in b/cmake/templates/OpenCVConfig-ANDROID.cmake.in new file mode 100644 index 0000000000..1787acab38 --- /dev/null +++ b/cmake/templates/OpenCVConfig-ANDROID.cmake.in @@ -0,0 +1,13 @@ +# Android API level from which OpenCV has been compiled is remembered +set(OpenCV_ANDROID_NATIVE_API_LEVEL "@OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE@") + +# ============================================================== +# Check OpenCV availability +# ============================================================== +if(OpenCV_ANDROID_NATIVE_API_LEVEL GREATER ANDROID_NATIVE_API_LEVEL) + if(NOT OpenCV_FIND_QUIETLY) + message(WARNING "Minimum required by OpenCV API level is android-${OpenCV_ANDROID_NATIVE_API_LEVEL}") + endif() + set(OpenCV_FOUND 0) + return() +endif() diff --git a/cmake/templates/OpenCVConfig-CUDA.cmake.in b/cmake/templates/OpenCVConfig-CUDA.cmake.in new file mode 100644 index 0000000000..0d261dd84b --- /dev/null +++ b/cmake/templates/OpenCVConfig-CUDA.cmake.in @@ -0,0 +1,53 @@ +# Version Compute Capability from which OpenCV has been compiled is remembered +set(OpenCV_COMPUTE_CAPABILITIES "@OpenCV_CUDA_CC@") + +set(OpenCV_CUDA_VERSION "@CUDA_VERSION_STRING@") +set(OpenCV_USE_CUBLAS "@HAVE_CUBLAS@") +set(OpenCV_USE_CUFFT "@HAVE_CUFFT@") +set(OpenCV_USE_NVCUVID "@HAVE_NVCUVID@") + +if(NOT CUDA_FOUND) + find_host_package(CUDA ${OpenCV_CUDA_VERSION} EXACT REQUIRED) +else() + if(NOT CUDA_VERSION_STRING VERSION_EQUAL OpenCV_CUDA_VERSION) + message(FATAL_ERROR "OpenCV static library was compiled with CUDA ${OpenCV_CUDA_VERSION} support. Please, use the same version or rebuild OpenCV with CUDA ${CUDA_VERSION_STRING}") + endif() +endif() + +set(OpenCV_CUDA_LIBS_ABSPATH ${CUDA_LIBRARIES}) + +if(${CUDA_VERSION} VERSION_LESS "5.5") + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_npp_LIBRARY}) +else() + find_cuda_helper_libs(nppc) + find_cuda_helper_libs(nppi) + find_cuda_helper_libs(npps) + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nppc_LIBRARY} ${CUDA_nppi_LIBRARY} ${CUDA_npps_LIBRARY}) +endif() + +if(OpenCV_USE_CUBLAS) + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_CUBLAS_LIBRARIES}) +endif() + +if(OpenCV_USE_CUFFT) + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_CUFFT_LIBRARIES}) +endif() + +if(OpenCV_USE_NVCUVID) + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nvcuvid_LIBRARIES}) +endif() + +if(WIN32) + list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nvcuvenc_LIBRARIES}) +endif() + +set(OpenCV_CUDA_LIBS_RELPATH "") +foreach(l ${OpenCV_CUDA_LIBS_ABSPATH}) + get_filename_component(_tmp ${l} PATH) + if(NOT ${_tmp} MATCHES "-Wl.*") + list(APPEND OpenCV_CUDA_LIBS_RELPATH ${_tmp}) + endif() +endforeach() + +list(REMOVE_DUPLICATES OpenCV_CUDA_LIBS_RELPATH) +link_directories(${OpenCV_CUDA_LIBS_RELPATH}) diff --git a/cmake/templates/OpenCVConfig-IPPICV.cmake.in b/cmake/templates/OpenCVConfig-IPPICV.cmake.in new file mode 100644 index 0000000000..33cf2d4374 --- /dev/null +++ b/cmake/templates/OpenCVConfig-IPPICV.cmake.in @@ -0,0 +1,7 @@ +if(NOT TARGET ippicv) + add_library(ippicv STATIC IMPORTED) + set_target_properties(ippicv PROPERTIES + IMPORTED_LINK_INTERFACE_LIBRARIES "" + IMPORTED_LOCATION "${OpenCV_INSTALL_PATH}/@IPPICV_INSTALL_PATH_RELATIVE_CONFIGCMAKE@" + ) +endif() diff --git a/cmake/templates/OpenCVConfig.cmake.in b/cmake/templates/OpenCVConfig.cmake.in index 468732b8b0..dfe9aeafe1 100644 --- a/cmake/templates/OpenCVConfig.cmake.in +++ b/cmake/templates/OpenCVConfig.cmake.in @@ -29,125 +29,15 @@ # # Advanced variables: # - OpenCV_SHARED : Use OpenCV as shared library -# - OpenCV_CONFIG_PATH : Path to this OpenCVConfig.cmake -# - OpenCV_INSTALL_PATH : OpenCV location (not set on Windows) +# - OpenCV_INSTALL_PATH : OpenCV location # - OpenCV_LIB_COMPONENTS : Present OpenCV modules list # - OpenCV_USE_MANGLED_PATHS : Mangled OpenCV path flag -# - OpenCV_MODULES_SUFFIX : The suffix for OpenCVModules-XXX.cmake file # # Deprecated variables: # - OpenCV_VERSION_TWEAK : Always "0" # # =================================================================================== -# Search packages for host system instead of packages for target system. -# in case of cross compilation thess macro should be defined by toolchain file - -if(NOT COMMAND find_host_package) - macro(find_host_package) - find_package(${ARGN}) - endmacro() -endif() - -if(NOT COMMAND find_host_program) - macro(find_host_program) - find_program(${ARGN}) - endmacro() -endif() - -if(NOT DEFINED OpenCV_MODULES_SUFFIX) - if(ANDROID) - string(REPLACE - _ OpenCV_MODULES_SUFFIX "_${ANDROID_NDK_ABI_NAME}") - else() - set(OpenCV_MODULES_SUFFIX "") - endif() -endif() - -if("@USE_IPPICV@" STREQUAL "TRUE") # value is defined by package builder (use STREQUAL to comply new CMake policy CMP0012) - if(NOT TARGET ippicv) - if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/@INSTALL_PATH_RELATIVE_IPPICV@") - add_library(ippicv STATIC IMPORTED) - set_target_properties(ippicv PROPERTIES - IMPORTED_LINK_INTERFACE_LIBRARIES "" - IMPORTED_LOCATION "${CMAKE_CURRENT_LIST_DIR}/@INSTALL_PATH_RELATIVE_IPPICV@" - ) - endif() - endif() -endif() - -if(NOT TARGET opencv_core) - # Extract directory name from full path of the file currently being processed. - # Note that CMake 2.8.3 introduced CMAKE_CURRENT_LIST_DIR. We reimplement it - # for older versions of CMake to support these as well. - if(CMAKE_VERSION VERSION_LESS "2.8.3") - get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) - endif() - - include(${CMAKE_CURRENT_LIST_DIR}/OpenCVModules${OpenCV_MODULES_SUFFIX}.cmake) -endif() - -# TODO All things below should be reviewed. What is about of moving this code into related modules (special vars/hooks/files) - -# Version Compute Capability from which OpenCV has been compiled is remembered -set(OpenCV_COMPUTE_CAPABILITIES @OpenCV_CUDA_CC_CONFIGCMAKE@) - -set(OpenCV_CUDA_VERSION @OpenCV_CUDA_VERSION@) -set(OpenCV_USE_CUBLAS @HAVE_CUBLAS@) -set(OpenCV_USE_CUFFT @HAVE_CUFFT@) -set(OpenCV_USE_NVCUVID @HAVE_NVCUVID@) - -# Android API level from which OpenCV has been compiled is remembered -if(ANDROID) - set(OpenCV_ANDROID_NATIVE_API_LEVEL @OpenCV_ANDROID_NATIVE_API_LEVEL_CONFIGCMAKE@) -else() - set(OpenCV_ANDROID_NATIVE_API_LEVEL 0) -endif() - -# Some additional settings are required if OpenCV is built as static libs -set(OpenCV_SHARED @BUILD_SHARED_LIBS@) - -# Enables mangled install paths, that help with side by side installs -set(OpenCV_USE_MANGLED_PATHS @OpenCV_USE_MANGLED_PATHS_CONFIGCMAKE@) - -# Extract the directory where *this* file has been installed (determined at cmake run-time) -if(CMAKE_VERSION VERSION_LESS "2.8.12") - get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" PATH CACHE) -else() - get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY CACHE) -endif() - -if(NOT WIN32 OR ANDROID) - if(ANDROID) - set(OpenCV_INSTALL_PATH "${OpenCV_CONFIG_PATH}/../../..") - else() - set(OpenCV_INSTALL_PATH "${OpenCV_CONFIG_PATH}/../..") - endif() - # Get the absolute path with no ../.. relative marks, to eliminate implicit linker warnings - if(${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} VERSION_LESS 2.8) - get_filename_component(OpenCV_INSTALL_PATH "${OpenCV_INSTALL_PATH}" ABSOLUTE) - else() - get_filename_component(OpenCV_INSTALL_PATH "${OpenCV_INSTALL_PATH}" REALPATH) - endif() -endif() - -# ====================================================== -# Include directories to add to the user project: -# ====================================================== - -# Provide the include directories to the caller -set(OpenCV_INCLUDE_DIRS @OpenCV_INCLUDE_DIRS_CONFIGCMAKE@) - -# ====================================================== -# Link directories to add to the user project: -# ====================================================== - -# Provide the libs directories to the caller -set(OpenCV_LIB_DIR_OPT @OpenCV_LIB_DIRS_CONFIGCMAKE@ CACHE PATH "Path where release OpenCV libraries are located") -set(OpenCV_LIB_DIR_DBG @OpenCV_LIB_DIRS_CONFIGCMAKE@ CACHE PATH "Path where debug OpenCV libraries are located") -set(OpenCV_3RDPARTY_LIB_DIR_OPT @OpenCV_3RDPARTY_LIB_DIRS_CONFIGCMAKE@ CACHE PATH "Path where release 3rdparty OpenCV dependencies are located") -set(OpenCV_3RDPARTY_LIB_DIR_DBG @OpenCV_3RDPARTY_LIB_DIRS_CONFIGCMAKE@ CACHE PATH "Path where debug 3rdparty OpenCV dependencies are located") -mark_as_advanced(FORCE OpenCV_LIB_DIR_OPT OpenCV_LIB_DIR_DBG OpenCV_3RDPARTY_LIB_DIR_OPT OpenCV_3RDPARTY_LIB_DIR_DBG OpenCV_CONFIG_PATH) - # ====================================================== # Version variables: # ====================================================== @@ -158,28 +48,48 @@ SET(OpenCV_VERSION_PATCH @OPENCV_VERSION_PATCH@) SET(OpenCV_VERSION_TWEAK 0) SET(OpenCV_VERSION_STATUS "@OPENCV_VERSION_STATUS@") -# ==================================================================== -# Link libraries: e.g. opencv_core;opencv_imgproc; etc... -# ==================================================================== +# Extract directory name from full path of the file currently being processed. +# Note that CMake 2.8.3 introduced CMAKE_CURRENT_LIST_DIR. We reimplement it +# for older versions of CMake to support these as well. +if(CMAKE_VERSION VERSION_LESS "2.8.3") + get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +endif() -SET(OpenCV_LIB_COMPONENTS @OPENCV_MODULES_CONFIGCMAKE@) -list(REMOVE_ITEM OpenCV_LIB_COMPONENTS opencv_hal) -SET(OpenCV_WORLD_COMPONENTS @OPENCV_WORLD_MODULES@) +# Extract the directory where *this* file has been installed (determined at cmake run-time) +# Get the absolute path with no ../.. relative marks, to eliminate implicit linker warnings +set(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_DIR}") +get_filename_component(OpenCV_INSTALL_PATH "${OpenCV_CONFIG_PATH}/@OpenCV_INSTALL_PATH_RELATIVE_CONFIGCMAKE@" REALPATH) -# ============================================================== -# Extra include directories, needed by OpenCV 2 new structure -# ============================================================== -SET(OpenCV2_INCLUDE_DIRS @OpenCV2_INCLUDE_DIRS_CONFIGCMAKE@) -if(OpenCV2_INCLUDE_DIRS) - list(APPEND OpenCV_INCLUDE_DIRS ${OpenCV2_INCLUDE_DIRS}) +# Search packages for host system instead of packages for target system. +# in case of cross compilation thess macro should be defined by toolchain file +if(NOT COMMAND find_host_package) + macro(find_host_package) + find_package(${ARGN}) + endmacro() +endif() +if(NOT COMMAND find_host_program) + macro(find_host_program) + find_program(${ARGN}) + endmacro() +endif() - set(OpenCV_ADD_DEBUG_RELEASE @OpenCV_ADD_DEBUG_RELEASE_CONFIGCMAKE@) - if(OpenCV_ADD_DEBUG_RELEASE) - set(OpenCV_LIB_DIR_OPT "${OpenCV_LIB_DIR_OPT}/Release") - set(OpenCV_LIB_DIR_DBG "${OpenCV_LIB_DIR_DBG}/Debug") - set(OpenCV_3RDPARTY_LIB_DIR_OPT "${OpenCV_3RDPARTY_LIB_DIR_OPT}/Release") - set(OpenCV_3RDPARTY_LIB_DIR_DBG "${OpenCV_3RDPARTY_LIB_DIR_DBG}/Debug") - endif() + +@CUDA_CONFIGCMAKE@ +@ANDROID_CONFIGCMAKE@ + +@IPPICV_CONFIGCMAKE@ + +# Some additional settings are required if OpenCV is built as static libs +set(OpenCV_SHARED @BUILD_SHARED_LIBS@) + +# Enables mangled install paths, that help with side by side installs +set(OpenCV_USE_MANGLED_PATHS @OpenCV_USE_MANGLED_PATHS_CONFIGCMAKE@) + +set(OpenCV_LIB_COMPONENTS @OPENCV_MODULES_CONFIGCMAKE@) +set(OpenCV_INCLUDE_DIRS @OpenCV_INCLUDE_DIRS_CONFIGCMAKE@) + +if(NOT TARGET opencv_core) + include(${CMAKE_CURRENT_LIST_DIR}/OpenCVModules${OpenCV_MODULES_SUFFIX}.cmake) endif() if(NOT CMAKE_VERSION VERSION_LESS "2.8.11") @@ -196,22 +106,6 @@ if(NOT CMAKE_VERSION VERSION_LESS "2.8.11") endforeach() endif() -# ============================================================== -# Check OpenCV availability -# ============================================================== -if(ANDROID AND OpenCV_ANDROID_NATIVE_API_LEVEL GREATER ANDROID_NATIVE_API_LEVEL) - message(FATAL_ERROR "Minimum required by OpenCV API level is android-${OpenCV_ANDROID_NATIVE_API_LEVEL}") - #always FATAL_ERROR because we can't say to the caller that OpenCV is not found - #http://www.mail-archive.com/cmake@cmake.org/msg37831.html - if(OpenCV_FIND_REQUIRED) - message(FATAL_ERROR "Minimum required by OpenCV API level is android-${OpenCV_ANDROID_NATIVE_API_LEVEL}") - elseif(NOT OpenCV_FIND_QUIETLY) - message(WARNING "Minimum required by OpenCV API level is android-${OpenCV_ANDROID_NATIVE_API_LEVEL}") - endif() - set(OpenCV_FOUND "OpenCV_FOUND-NOTFOUND") - return()#Android toolchain requires CMake > 2.6 -endif() - # ============================================================== # Form list of modules (components) to find # ============================================================== @@ -223,6 +117,8 @@ if(NOT OpenCV_FIND_COMPONENTS) endif() endif() +set(OpenCV_WORLD_COMPONENTS @OPENCV_WORLD_MODULES@) + # expand short module names and see if requested components exist set(OpenCV_FIND_COMPONENTS_ "") foreach(__cvcomponent ${OpenCV_FIND_COMPONENTS}) @@ -276,89 +172,11 @@ foreach(__cvcomponent ${OpenCV_FIND_COMPONENTS}) endforeach() set(OpenCV_FIND_COMPONENTS ${OpenCV_FIND_COMPONENTS_}) -# ============================================================== -# Resolve dependencies -# ============================================================== -if(OpenCV_USE_MANGLED_PATHS) - set(OpenCV_LIB_SUFFIX ".${OpenCV_VERSION_MAJOR}.${OpenCV_VERSION_MINOR}.${OpenCV_VERSION_PATCH}") -else() - set(OpenCV_LIB_SUFFIX "") -endif() - -foreach(__opttype OPT DBG) - SET(OpenCV_LIBS_${__opttype} "${OpenCV_LIBS}") - SET(OpenCV_EXTRA_LIBS_${__opttype} "") - - # CUDA - if(OpenCV_CUDA_VERSION) - if(NOT CUDA_FOUND) - find_host_package(CUDA ${OpenCV_CUDA_VERSION} EXACT REQUIRED) - else() - if(NOT CUDA_VERSION_STRING VERSION_EQUAL OpenCV_CUDA_VERSION) - message(FATAL_ERROR "OpenCV static library was compiled with CUDA ${OpenCV_CUDA_VERSION} support. Please, use the same version or rebuild OpenCV with CUDA ${CUDA_VERSION_STRING}") - endif() - endif() - - set(OpenCV_CUDA_LIBS_ABSPATH ${CUDA_LIBRARIES}) - - if(${CUDA_VERSION} VERSION_LESS "5.5") - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_npp_LIBRARY}) - else() - find_cuda_helper_libs(nppc) - find_cuda_helper_libs(nppi) - find_cuda_helper_libs(npps) - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nppc_LIBRARY} ${CUDA_nppi_LIBRARY} ${CUDA_npps_LIBRARY}) - endif() - - if(OpenCV_USE_CUBLAS) - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_CUBLAS_LIBRARIES}) - endif() - - if(OpenCV_USE_CUFFT) - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_CUFFT_LIBRARIES}) - endif() - - if(OpenCV_USE_NVCUVID) - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nvcuvid_LIBRARIES}) - endif() - - if(WIN32) - list(APPEND OpenCV_CUDA_LIBS_ABSPATH ${CUDA_nvcuvenc_LIBRARIES}) - endif() - - set(OpenCV_CUDA_LIBS_RELPATH "") - foreach(l ${OpenCV_CUDA_LIBS_ABSPATH}) - get_filename_component(_tmp ${l} PATH) - if(NOT ${_tmp} MATCHES "-Wl.*") - list(APPEND OpenCV_CUDA_LIBS_RELPATH ${_tmp}) - endif() - endforeach() - - list(REMOVE_DUPLICATES OpenCV_CUDA_LIBS_RELPATH) - link_directories(${OpenCV_CUDA_LIBS_RELPATH}) - endif() -endforeach() - # ============================================================== # Compatibility stuff # ============================================================== -if(CMAKE_BUILD_TYPE MATCHES "Debug") - SET(OpenCV_LIB_DIR ${OpenCV_LIB_DIR_DBG} ${OpenCV_3RDPARTY_LIB_DIR_DBG}) -else() - SET(OpenCV_LIB_DIR ${OpenCV_LIB_DIR_OPT} ${OpenCV_3RDPARTY_LIB_DIR_OPT}) -endif() set(OpenCV_LIBRARIES ${OpenCV_LIBS}) -if(CMAKE_CROSSCOMPILING AND OpenCV_SHARED AND (CMAKE_SYSTEM_NAME MATCHES "Linux")) - foreach(dir ${OpenCV_LIB_DIR}) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath-link,${dir}") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-rpath-link,${dir}") - set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-rpath-link,${dir}") - endforeach() -endif() - - - # # Some macroses for samples # @@ -376,7 +194,7 @@ endmacro() # adds include directories in such way that directories from the OpenCV source tree go first function(ocv_include_directories) set(__add_before "") - file(TO_CMAKE_PATH "${OpenCV_DIR}" __baseDir) + file(TO_CMAKE_PATH "${OpenCV_INSTALL_PATH}" __baseDir) foreach(dir ${ARGN}) get_filename_component(__abs_dir "${dir}" ABSOLUTE) if("${__abs_dir}" MATCHES "^${__baseDir}") diff --git a/cmake/templates/OpenCVConfig.root-ANDROID.cmake.in b/cmake/templates/OpenCVConfig.root-ANDROID.cmake.in new file mode 100644 index 0000000000..7ceeec4c7f --- /dev/null +++ b/cmake/templates/OpenCVConfig.root-ANDROID.cmake.in @@ -0,0 +1,50 @@ +# =================================================================================== +# The OpenCV CMake configuration file +# +# ** File generated automatically, do not modify ** +# +# Usage from an external project: +# In your CMakeLists.txt, add these lines: +# +# find_package(OpenCV REQUIRED) +# include_directories(${OpenCV_INCLUDE_DIRS}) # Not needed for CMake >= 2.8.11 +# target_link_libraries(MY_TARGET_NAME ${OpenCV_LIBS}) +# +# Or you can search for specific OpenCV modules: +# +# find_package(OpenCV REQUIRED core videoio) +# +# If the module is found then OPENCV__FOUND is set to TRUE. +# +# This file will define the following variables: +# - OpenCV_LIBS : The list of all imported targets for OpenCV modules. +# - OpenCV_INCLUDE_DIRS : The OpenCV include directories. +# - OpenCV_ANDROID_NATIVE_API_LEVEL : Minimum required level of Android API. +# - OpenCV_VERSION : The version of this OpenCV build: "@OPENCV_VERSION_PLAIN@" +# - OpenCV_VERSION_MAJOR : Major version part of OpenCV_VERSION: "@OPENCV_VERSION_MAJOR@" +# - OpenCV_VERSION_MINOR : Minor version part of OpenCV_VERSION: "@OPENCV_VERSION_MINOR@" +# - OpenCV_VERSION_PATCH : Patch version part of OpenCV_VERSION: "@OPENCV_VERSION_PATCH@" +# - OpenCV_VERSION_STATUS : Development status of this build: "@OPENCV_VERSION_STATUS@" +# +# =================================================================================== + +# Extract directory name from full path of the file currently being processed. +# Note that CMake 2.8.3 introduced CMAKE_CURRENT_LIST_DIR. We reimplement it +# for older versions of CMake to support these as well. +if(CMAKE_VERSION VERSION_LESS "2.8.3") + get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +endif() + +if(NOT DEFINED OpenCV_CONFIG_SUBDIR) + set(OpenCV_CONFIG_SUBDIR "/abi-${ANDROID_NDK_ABI_NAME}") +endif() + +set(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_DIR}${OpenCV_CONFIG_SUBDIR}") +if(EXISTS "${OpenCV_CONFIG_PATH}/OpenCVConfig.cmake") + include("${OpenCV_CONFIG_PATH}/OpenCVConfig.cmake") +else() + if(NOT OpenCV_FIND_QUIETLY) + message(WARNING "Found OpenCV Android Pack but it has no binaries compatible with your ABI (can't find: ${OpenCV_CONFIG_SUBDIR})") + endif() + set(OpenCV_FOUND FALSE) +endif() diff --git a/cmake/OpenCVConfig.cmake b/cmake/templates/OpenCVConfig.root-WIN32.cmake.in similarity index 72% rename from cmake/OpenCVConfig.cmake rename to cmake/templates/OpenCVConfig.root-WIN32.cmake.in index fdc371b19f..e40140fb75 100644 --- a/cmake/OpenCVConfig.cmake +++ b/cmake/templates/OpenCVConfig.root-WIN32.cmake.in @@ -17,20 +17,16 @@ # # This file will define the following variables: # - OpenCV_LIBS : The list of libraries to link against. -# - OpenCV_LIB_DIR : The directory(es) where lib files are. Calling LINK_DIRECTORIES -# with this path is NOT needed. # - OpenCV_INCLUDE_DIRS : The OpenCV include directories. # - OpenCV_COMPUTE_CAPABILITIES : The version of compute capability -# - OpenCV_ANDROID_NATIVE_API_LEVEL : Minimum required level of Android API -# - OpenCV_VERSION : The version of this OpenCV build. Example: "2.4.0" -# - OpenCV_VERSION_MAJOR : Major version part of OpenCV_VERSION. Example: "2" -# - OpenCV_VERSION_MINOR : Minor version part of OpenCV_VERSION. Example: "4" -# - OpenCV_VERSION_PATCH : Patch version part of OpenCV_VERSION. Example: "0" +# - OpenCV_VERSION : The version of this OpenCV build: "@OPENCV_VERSION_PLAIN@" +# - OpenCV_VERSION_MAJOR : Major version part of OpenCV_VERSION: "@OPENCV_VERSION_MAJOR@" +# - OpenCV_VERSION_MINOR : Minor version part of OpenCV_VERSION: "@OPENCV_VERSION_MINOR@" +# - OpenCV_VERSION_PATCH : Patch version part of OpenCV_VERSION: "@OPENCV_VERSION_PATCH@" +# - OpenCV_VERSION_STATUS : Development status of this build: "@OPENCV_VERSION_STATUS@" # # Advanced variables: # - OpenCV_SHARED -# - OpenCV_CONFIG_PATH -# - OpenCV_LIB_COMPONENTS # # =================================================================================== # @@ -64,13 +60,11 @@ endif() if(MSVC) if(CMAKE_CL_64) set(OpenCV_ARCH x64) - set(OpenCV_TBB_ARCH intel64) elseif((CMAKE_GENERATOR MATCHES "ARM") OR ("${arch_hint}" STREQUAL "ARM") OR (CMAKE_VS_EFFECTIVE_PLATFORMS MATCHES "ARM|arm")) # see Modules/CmakeGenericSystem.cmake set(OpenCV_ARCH ARM) else() set(OpenCV_ARCH x86) - set(OpenCV_TBB_ARCH ia32) endif() if(MSVC_VERSION EQUAL 1400) set(OpenCV_RUNTIME vc8) @@ -99,22 +93,13 @@ elseif(MINGW) endif() endif() -if(CMAKE_VERSION VERSION_GREATER 2.6.2) - unset(OpenCV_CONFIG_PATH CACHE) -endif() - if(NOT OpenCV_FIND_QUIETLY) message(STATUS "OpenCV ARCH: ${OpenCV_ARCH}") message(STATUS "OpenCV RUNTIME: ${OpenCV_RUNTIME}") message(STATUS "OpenCV STATIC: ${OpenCV_STATIC}") endif() -if(CMAKE_VERSION VERSION_LESS "2.8.12") - get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" PATH CACHE) -else() - get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY CACHE) -endif() - +get_filename_component(OpenCV_CONFIG_PATH "${CMAKE_CURRENT_LIST_FILE}" PATH) if(OpenCV_RUNTIME AND OpenCV_ARCH) if(OpenCV_STATIC AND EXISTS "${OpenCV_CONFIG_PATH}/${OpenCV_ARCH}/${OpenCV_RUNTIME}/staticlib/OpenCVConfig.cmake") if(OpenCV_CUDA AND EXISTS "${OpenCV_CONFIG_PATH}/gpu/${OpenCV_ARCH}/${OpenCV_RUNTIME}/staticlib/OpenCVConfig.cmake") @@ -132,28 +117,8 @@ if(OpenCV_RUNTIME AND OpenCV_ARCH) endif() if(OpenCV_LIB_PATH AND EXISTS "${OpenCV_LIB_PATH}/OpenCVConfig.cmake") - set(OpenCV_LIB_DIR_OPT "${OpenCV_LIB_PATH}" CACHE PATH "Path where release OpenCV libraries are located" FORCE) - set(OpenCV_LIB_DIR_DBG "${OpenCV_LIB_PATH}" CACHE PATH "Path where debug OpenCV libraries are located" FORCE) - set(OpenCV_3RDPARTY_LIB_DIR_OPT "${OpenCV_LIB_PATH}" CACHE PATH "Path where release 3rdparty OpenCV dependencies are located" FORCE) - set(OpenCV_3RDPARTY_LIB_DIR_DBG "${OpenCV_LIB_PATH}" CACHE PATH "Path where debug 3rdparty OpenCV dependencies are located" FORCE) - include("${OpenCV_LIB_PATH}/OpenCVConfig.cmake") - if(OpenCV_CUDA) - set(_OpenCV_LIBS "") - foreach(_lib ${OpenCV_LIBS}) - string(REPLACE "${OpenCV_CONFIG_PATH}/gpu/${OpenCV_ARCH}/${OpenCV_RUNTIME}" "${OpenCV_CONFIG_PATH}/${OpenCV_ARCH}/${OpenCV_RUNTIME}" _lib2 "${_lib}") - if(NOT EXISTS "${_lib}" AND EXISTS "${_lib2}") - list(APPEND _OpenCV_LIBS "${_lib2}") - else() - list(APPEND _OpenCV_LIBS "${_lib}") - endif() - endforeach() - set(OpenCV_LIBS ${_OpenCV_LIBS}) - endif() - set(OpenCV_FOUND TRUE CACHE BOOL "" FORCE) - set(OPENCV_FOUND TRUE CACHE BOOL "" FORCE) - if(NOT OpenCV_FIND_QUIETLY) message(STATUS "Found OpenCV ${OpenCV_VERSION} in ${OpenCV_LIB_PATH}") if(NOT OpenCV_LIB_PATH MATCHES "/staticlib") @@ -173,6 +138,5 @@ else() You should manually point CMake variable OpenCV_DIR to your build of OpenCV library." ) endif() - set(OpenCV_FOUND FALSE CACHE BOOL "" FORCE) - set(OPENCV_FOUND FALSE CACHE BOOL "" FORCE) + set(OpenCV_FOUND FALSE) endif() From f5306a0740115af930780b38597fdfb50cc21e58 Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Mon, 20 Jun 2016 17:19:13 +0300 Subject: [PATCH 26/95] cmake: change CMP0042 policy value --- CMakeLists.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 18887f4712..11a64080ca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -81,9 +81,8 @@ if(POLICY CMP0026) cmake_policy(SET CMP0026 OLD) endif() -if (POLICY CMP0042) - # silence cmake 3.0+ warnings about MACOSX_RPATH - cmake_policy(SET CMP0042 OLD) +if(POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) endif() include(cmake/OpenCVUtils.cmake) From 2fb670cf09ca83da694365024efa288661c5340d Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Mon, 20 Jun 2016 19:25:49 +0300 Subject: [PATCH 27/95] hal: fix missing include "opencv2/imgproc/hal/interface.h" --- modules/imgproc/src/hal_replacement.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/imgproc/src/hal_replacement.hpp b/modules/imgproc/src/hal_replacement.hpp index e42cc44ad9..2fd3539bcb 100644 --- a/modules/imgproc/src/hal_replacement.hpp +++ b/modules/imgproc/src/hal_replacement.hpp @@ -46,6 +46,7 @@ #define OPENCV_IMGPROC_HAL_REPLACEMENT_HPP #include "opencv2/core/hal/interface.h" +#include "opencv2/imgproc/hal/interface.h" #if defined __GNUC__ # pragma GCC diagnostic push From 9b959072a20ccf1af8693db04e200f72713f7971 Mon Sep 17 00:00:00 2001 From: Matthew Skolaut Date: Mon, 20 Jun 2016 16:24:15 -0500 Subject: [PATCH 28/95] added python binding for createButton --- modules/python/src2/cv2.cpp | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 3bb98e4f8c..eb0d4c998c 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -1251,6 +1251,7 @@ static void OnChange(int pos, void *param) } #ifdef HAVE_OPENCV_HIGHGUI + static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args) { PyObject *on_change; @@ -1270,6 +1271,55 @@ static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args) } #endif +static void OnButtonChange(int state, void *param) +{ + PyGILState_STATE gstate; + gstate = PyGILState_Ensure(); + + PyObject *o = (PyObject*)param; + PyObject *args; + if(PyTuple_GetItem(o, 1) != NULL) + { + args = Py_BuildValue("(iO)", state, PyTuple_GetItem(o,1)); + } + else + { + args = Py_BuildValue("(i)", state); + } + + PyObject *r = PyObject_Call(PyTuple_GetItem(o, 0), args, NULL); + if (r == NULL) + PyErr_Print(); + Py_DECREF(args); + PyGILState_Release(gstate); +} + +#ifdef HAVE_OPENCV_HIGHGUI + +static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw) +{ + const char* keywords[] = {"buttonName", "onChange", "userData", "buttonType", "initialButtonState", NULL}; + PyObject *on_change; + PyObject *userdata = NULL; + char* button_name; + int button_type = 0; + int initial_button_state = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|Oii", (char**)keywords, &button_name, &on_change, &userdata, &button_type, &initial_button_state)) + return NULL; + if (!PyCallable_Check(on_change)) { + PyErr_SetString(PyExc_TypeError, "onChange must be callable"); + return NULL; + } + if (userdata == NULL) { + userdata = Py_None; + } + + ERRWRAP2(createButton(button_name, OnButtonChange, Py_BuildValue("OO", on_change, userdata), button_type, initial_button_state)); + Py_RETURN_NONE; +} +#endif + /////////////////////////////////////////////////////////////////////////////////////// static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name") @@ -1300,6 +1350,7 @@ static int convert_to_char(PyObject *o, char *dst, const char *name = "no_name") static PyMethodDef special_methods[] = { #ifdef HAVE_OPENCV_HIGHGUI {"createTrackbar", pycvCreateTrackbar, METH_VARARGS, "createTrackbar(trackbarName, windowName, value, count, onChange) -> None"}, + {"createButton", (PyCFunction)pycvCreateButton, METH_VARARGS | METH_KEYWORDS, "createButton(buttonName, onChange [, userData, buttonType, initialButtonState]) -> None"}, {"setMouseCallback", (PyCFunction)pycvSetMouseCallback, METH_VARARGS | METH_KEYWORDS, "setMouseCallback(windowName, onMouse [, param]) -> None"}, #endif {NULL, NULL}, From 7284a77cd35c81947a9ce3c8f95ab4fef4952ae6 Mon Sep 17 00:00:00 2001 From: Matthew Skolaut Date: Mon, 20 Jun 2016 21:07:24 -0500 Subject: [PATCH 29/95] fix casting warning in python createButton binding --- modules/python/src2/cv2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index eb0d4c998c..537e85422b 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -1303,7 +1303,7 @@ static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw) PyObject *userdata = NULL; char* button_name; int button_type = 0; - int initial_button_state = 0; + bool initial_button_state = false; if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|Oii", (char**)keywords, &button_name, &on_change, &userdata, &button_type, &initial_button_state)) return NULL; From 09c2a8b7ad5356fd21544369a6d7e2b0f2abafa8 Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Tue, 21 Jun 2016 19:50:32 +0300 Subject: [PATCH 30/95] cmake: fix HAL dependencies for core module Linker dependencies are transitive for non-private --- modules/core/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/core/CMakeLists.txt b/modules/core/CMakeLists.txt index 171fa9b082..36c4eea5d4 100644 --- a/modules/core/CMakeLists.txt +++ b/modules/core/CMakeLists.txt @@ -1,6 +1,7 @@ set(the_description "The Core Functionality") ocv_add_module(core - PRIVATE_REQUIRED ${ZLIB_LIBRARIES} "${OPENCL_LIBRARIES}" "${VA_LIBRARIES}" "${OPENCV_HAL_LINKER_LIBS}" + "${OPENCV_HAL_LINKER_LIBS}" + PRIVATE_REQUIRED ${ZLIB_LIBRARIES} "${OPENCL_LIBRARIES}" "${VA_LIBRARIES}" OPTIONAL opencv_cudev WRAP java python) From 33ab236ed3d34284374e8b2741ceedf19664edbf Mon Sep 17 00:00:00 2001 From: Julien Dubiel Date: Tue, 21 Jun 2016 20:00:50 +0200 Subject: [PATCH 31/95] Use CMAKE_LIBRARY_PATH_FLAG variable instead of -L. --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11a64080ca..5066246b1f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -659,7 +659,7 @@ if(HAVE_CUDA) set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${CUDA_cufft_LIBRARY}) endif() foreach(p ${CUDA_LIBS_PATH}) - set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} -L${p}) + set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} ${CMAKE_LIBRARY_PATH_FLAG}${p}) endforeach() endif() # ---------------------------------------------------------------------------- From f861d0d64377b76a7ebf7d9369c6d40f706578da Mon Sep 17 00:00:00 2001 From: Matthew Skolaut Date: Tue, 21 Jun 2016 17:16:16 -0500 Subject: [PATCH 32/95] merge #ifs in highgui bindings --- modules/python/src2/cv2.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 537e85422b..4b07e60fa4 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -1251,7 +1251,6 @@ static void OnChange(int pos, void *param) } #ifdef HAVE_OPENCV_HIGHGUI - static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args) { PyObject *on_change; @@ -1269,7 +1268,6 @@ static PyObject *pycvCreateTrackbar(PyObject*, PyObject *args) ERRWRAP2(createTrackbar(trackbar_name, window_name, value, count, OnChange, Py_BuildValue("OO", on_change, Py_None))); Py_RETURN_NONE; } -#endif static void OnButtonChange(int state, void *param) { @@ -1294,8 +1292,6 @@ static void OnButtonChange(int state, void *param) PyGILState_Release(gstate); } -#ifdef HAVE_OPENCV_HIGHGUI - static PyObject *pycvCreateButton(PyObject*, PyObject *args, PyObject *kw) { const char* keywords[] = {"buttonName", "onChange", "userData", "buttonType", "initialButtonState", NULL}; From 09ce9875527f0c2041d720c22f079cc0dfe6aa9e Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Tue, 21 Jun 2016 22:32:30 +0300 Subject: [PATCH 33/95] cmake: fix export issue opencv_ts is static internal library and in case of exporting it requires all static dependencies (include HAL files) --- cmake/OpenCVModule.cmake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmake/OpenCVModule.cmake b/cmake/OpenCVModule.cmake index bd3286c2a2..ee14c7922c 100644 --- a/cmake/OpenCVModule.cmake +++ b/cmake/OpenCVModule.cmake @@ -859,7 +859,8 @@ macro(_ocv_create_module) endif() get_target_property(_target_type ${the_module} TYPE) - if("${_target_type}" STREQUAL "SHARED_LIBRARY" OR (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)) + if(OPENCV_MODULE_${the_module}_CLASS STREQUAL "PUBLIC" AND + ("${_target_type}" STREQUAL "SHARED_LIBRARY" OR (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB))) ocv_install_target(${the_module} EXPORT OpenCVModules OPTIONAL RUNTIME DESTINATION ${OPENCV_BIN_INSTALL_PATH} COMPONENT libs LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT libs NAMELINK_SKIP From f57e3ce5f3a77e541c25912dce4cf6d8ddff94b1 Mon Sep 17 00:00:00 2001 From: Alexander Alekhin Date: Wed, 22 Jun 2016 16:12:52 +0300 Subject: [PATCH 34/95] cmake: don't use absolute paths with/without CMAKE_INSTALL_PREFIX CPack can't work with absolute paths. --- CMakeLists.txt | 2 +- cmake/OpenCVGenConfig.cmake | 4 ++-- cmake/OpenCVUtils.cmake | 6 +++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11a64080ca..c79338bc20 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -386,7 +386,7 @@ else() ocv_update(OPENCV_SAMPLES_SRC_INSTALL_PATH samples/native) ocv_update(OPENCV_JAR_INSTALL_PATH java) ocv_update(OPENCV_OTHER_INSTALL_PATH etc) - ocv_update(OPENCV_CONFIG_INSTALL_PATH "") + ocv_update(OPENCV_CONFIG_INSTALL_PATH ".") else() ocv_update(OPENCV_LIB_INSTALL_PATH lib${LIB_SUFFIX}) ocv_update(OPENCV_3P_LIB_INSTALL_PATH share/OpenCV/3rdparty/${OPENCV_LIB_INSTALL_PATH}) diff --git a/cmake/OpenCVGenConfig.cmake b/cmake/OpenCVGenConfig.cmake index 29517cdb12..206acfdad9 100644 --- a/cmake/OpenCVGenConfig.cmake +++ b/cmake/OpenCVGenConfig.cmake @@ -79,7 +79,7 @@ function(ocv_gen_config TMP_DIR NESTED_PATH ROOT_NAME) install(FILES "${TMP_DIR}/OpenCVConfig-version.cmake" "${__tmp_nested}/OpenCVConfig.cmake" - DESTINATION "${CMAKE_INSTALL_PREFIX}/${__install_nested}" COMPONENT dev) + DESTINATION "${__install_nested}" COMPONENT dev) if(ROOT_NAME) # Root config file @@ -87,7 +87,7 @@ function(ocv_gen_config TMP_DIR NESTED_PATH ROOT_NAME) install(FILES "${TMP_DIR}/OpenCVConfig-version.cmake" "${TMP_DIR}/OpenCVConfig.cmake" - DESTINATION "${CMAKE_INSTALL_PREFIX}/${OPENCV_CONFIG_INSTALL_PATH}" COMPONENT dev) + DESTINATION "${OPENCV_CONFIG_INSTALL_PATH}" COMPONENT dev) endif() endfunction() diff --git a/cmake/OpenCVUtils.cmake b/cmake/OpenCVUtils.cmake index 2816100872..33f3dd8454 100644 --- a/cmake/OpenCVUtils.cmake +++ b/cmake/OpenCVUtils.cmake @@ -87,7 +87,11 @@ endmacro() macro(ocv_path_join result_var P1 P2) string(REGEX REPLACE "^[/]+" "" P2 "${P2}") if("${P1}" STREQUAL "") - set(${result_var} "${P2}") + if("${P2}" STREQUAL "") + set(${result_var} ".") + else() + set(${result_var} "${P2}") + endif() elseif("${P1}" STREQUAL "/") set(${result_var} "/${P2}") elseif("${P2}" STREQUAL "") From eaec95dcf2a7866d4cfc951d33718b2eae29011e Mon Sep 17 00:00:00 2001 From: Vitaly Tuzov Date: Wed, 22 Jun 2016 19:20:24 +0300 Subject: [PATCH 35/95] Update TBB --- 3rdparty/tbb/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/3rdparty/tbb/CMakeLists.txt b/3rdparty/tbb/CMakeLists.txt index a76854d4a3..eddeaef56a 100644 --- a/3rdparty/tbb/CMakeLists.txt +++ b/3rdparty/tbb/CMakeLists.txt @@ -5,9 +5,9 @@ if (WIN32 AND NOT ARM) message(FATAL_ERROR "BUILD_TBB option supports Windows on ARM only!\nUse regular official TBB build instead of the BUILD_TBB option!") endif() -set(tbb_ver "tbb43_20141204oss") -set(tbb_url "http://www.threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb43_20141204oss_src.tgz") -set(tbb_md5 "e903dd92d9433701f097fa7ca29a3c1f") +set(tbb_ver "tbb44_20160128oss") +set(tbb_url "http://www.threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb44_20160128oss_src_0.tgz") +set(tbb_md5 "9d8a4cdf43496f1b3f7c473a5248e5cc") set(tbb_version_file "version_string.ver") ocv_warnings_disable(CMAKE_CXX_FLAGS /wd4702) ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow) From d2bad6febb9e8f76ca67e485905c0575d1a311ad Mon Sep 17 00:00:00 2001 From: Suleyman TURKMEN Date: Wed, 25 May 2016 17:16:09 +0300 Subject: [PATCH 36/95] cv::TickMeter class addition --- modules/core/include/opencv2/core/utility.hpp | 120 +++++++++++++++++- samples/gpu/cascadeclassifier.cpp | 2 - samples/gpu/generalized_hough.cpp | 2 - samples/gpu/stereo_multi.cpp | 2 - samples/gpu/super_resolution.cpp | 2 - samples/gpu/tick_meter.hpp | 48 ------- samples/gpu/video_reader.cpp | 2 - samples/gpu/video_writer.cpp | 2 - 8 files changed, 119 insertions(+), 61 deletions(-) delete mode 100644 samples/gpu/tick_meter.hpp diff --git a/modules/core/include/opencv2/core/utility.hpp b/modules/core/include/opencv2/core/utility.hpp index 60b2d3a064..c74c1184f2 100644 --- a/modules/core/include/opencv2/core/utility.hpp +++ b/modules/core/include/opencv2/core/utility.hpp @@ -251,7 +251,8 @@ CV_EXPORTS_W const String& getBuildInformation(); The function returns the number of ticks after the certain event (for example, when the machine was turned on). It can be used to initialize RNG or to measure a function execution time by reading the -tick count before and after the function call. See also the tick frequency. +tick count before and after the function call. +@sa getTickFrequency, TickMeter */ CV_EXPORTS_W int64 getTickCount(); @@ -264,9 +265,126 @@ execution time in seconds: // do something ... t = ((double)getTickCount() - t)/getTickFrequency(); @endcode +@sa getTickCount, TickMeter */ CV_EXPORTS_W double getTickFrequency(); +/** @brief a Class to measure passing time. + +The class computes passing time by counting the number of ticks per second. That is, the following code computes the +execution time in seconds: +@code +TickMeter tm; +tm.start(); +// do something ... +tm.stop(); +std::cout << tm.getTimeSec(); +@endcode +@sa getTickCount, getTickFrequency +*/ + +class CV_EXPORTS_W TickMeter +{ +public: + //! the default constructor + CV_WRAP TickMeter() + { + reset(); + } + + /** + starts counting ticks. + */ + CV_WRAP void start() + { + startTime = cv::getTickCount(); + } + + /** + stops counting ticks. + */ + CV_WRAP void stop() + { + int64 time = cv::getTickCount(); + if (startTime == 0) + return; + ++counter; + sumTime += (time - startTime); + startTime = 0; + } + + /** + returns counted ticks. + */ + CV_WRAP int64 getTimeTicks() const + { + return sumTime; + } + + /** + returns passed time in microseconds. + */ + CV_WRAP double getTimeMicro() const + { + return getTimeMilli()*1e3; + } + + /** + returns passed time in milliseconds. + */ + CV_WRAP double getTimeMilli() const + { + return getTimeSec()*1e3; + } + + /** + returns passed time in seconds. + */ + CV_WRAP double getTimeSec() const + { + return (double)getTimeTicks() / getTickFrequency(); + } + + /** + returns internal counter value. + */ + CV_WRAP int64 getCounter() const + { + return counter; + } + + /** + resets internal values. + */ + CV_WRAP void reset() + { + startTime = 0; + sumTime = 0; + counter = 0; + } + +private: + int64 counter; + int64 sumTime; + int64 startTime; +}; + +/** @brief output operator +@code +TickMeter tm; +tm.start(); +// do something ... +tm.stop(); +std::cout << tm; +@endcode +*/ + +static inline +std::ostream& operator << (std::ostream& out, const TickMeter& tm) +{ + return out << tm.getTimeSec() << "sec"; +} + /** @brief Returns the number of CPU ticks. The function returns the current number of CPU ticks on some architectures (such as x86, x64, diff --git a/samples/gpu/cascadeclassifier.cpp b/samples/gpu/cascadeclassifier.cpp index f6209f9fa3..156efbf035 100644 --- a/samples/gpu/cascadeclassifier.cpp +++ b/samples/gpu/cascadeclassifier.cpp @@ -13,8 +13,6 @@ #include "opencv2/cudaimgproc.hpp" #include "opencv2/cudawarping.hpp" -#include "tick_meter.hpp" - using namespace std; using namespace cv; using namespace cv::cuda; diff --git a/samples/gpu/generalized_hough.cpp b/samples/gpu/generalized_hough.cpp index fb1cb8979c..7b7e80ab9d 100644 --- a/samples/gpu/generalized_hough.cpp +++ b/samples/gpu/generalized_hough.cpp @@ -8,8 +8,6 @@ #include "opencv2/cudaimgproc.hpp" #include "opencv2/highgui.hpp" -#include "tick_meter.hpp" - using namespace std; using namespace cv; diff --git a/samples/gpu/stereo_multi.cpp b/samples/gpu/stereo_multi.cpp index bfb3e8a48b..7ef656719d 100644 --- a/samples/gpu/stereo_multi.cpp +++ b/samples/gpu/stereo_multi.cpp @@ -17,8 +17,6 @@ #include "opencv2/imgproc.hpp" #include "opencv2/cudastereo.hpp" -#include "tick_meter.hpp" - using namespace std; using namespace cv; using namespace cv::cuda; diff --git a/samples/gpu/super_resolution.cpp b/samples/gpu/super_resolution.cpp index 026afd9710..94a922cdba 100644 --- a/samples/gpu/super_resolution.cpp +++ b/samples/gpu/super_resolution.cpp @@ -11,8 +11,6 @@ #include "opencv2/superres/optical_flow.hpp" #include "opencv2/opencv_modules.hpp" -#include "tick_meter.hpp" - using namespace std; using namespace cv; using namespace cv::superres; diff --git a/samples/gpu/tick_meter.hpp b/samples/gpu/tick_meter.hpp deleted file mode 100644 index c11a22d140..0000000000 --- a/samples/gpu/tick_meter.hpp +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef OPENCV_CUDA_SAMPLES_TICKMETER_ -#define OPENCV_CUDA_SAMPLES_TICKMETER_ - -class CV_EXPORTS TickMeter -{ -public: - TickMeter(); - void start(); - void stop(); - - int64 getTimeTicks() const; - double getTimeMicro() const; - double getTimeMilli() const; - double getTimeSec() const; - int64 getCounter() const; - - void reset(); -private: - int64 counter; - int64 sumTime; - int64 startTime; -}; - -std::ostream& operator << (std::ostream& out, const TickMeter& tm); - - -TickMeter::TickMeter() { reset(); } -int64 TickMeter::getTimeTicks() const { return sumTime; } -double TickMeter::getTimeMicro() const { return getTimeMilli()*1e3;} -double TickMeter::getTimeMilli() const { return getTimeSec()*1e3; } -double TickMeter::getTimeSec() const { return (double)getTimeTicks()/cv::getTickFrequency();} -int64 TickMeter::getCounter() const { return counter; } -void TickMeter::reset() {startTime = 0; sumTime = 0; counter = 0; } - -void TickMeter::start(){ startTime = cv::getTickCount(); } -void TickMeter::stop() -{ - int64 time = cv::getTickCount(); - if ( startTime == 0 ) - return; - ++counter; - sumTime += ( time - startTime ); - startTime = 0; -} - -std::ostream& operator << (std::ostream& out, const TickMeter& tm) { return out << tm.getTimeSec() << "sec"; } - -#endif diff --git a/samples/gpu/video_reader.cpp b/samples/gpu/video_reader.cpp index d8d6e136f8..a40a6800b4 100644 --- a/samples/gpu/video_reader.cpp +++ b/samples/gpu/video_reader.cpp @@ -14,8 +14,6 @@ #include #include -#include "tick_meter.hpp" - int main(int argc, const char* argv[]) { if (argc != 2) diff --git a/samples/gpu/video_writer.cpp b/samples/gpu/video_writer.cpp index 6c5d1412d6..80d2cfc47b 100644 --- a/samples/gpu/video_writer.cpp +++ b/samples/gpu/video_writer.cpp @@ -11,8 +11,6 @@ #include "opencv2/cudacodec.hpp" #include "opencv2/highgui.hpp" -#include "tick_meter.hpp" - int main(int argc, const char* argv[]) { if (argc != 2) From 7c92ee2e6e758d6454f5cbc13f84f60ceb36a651 Mon Sep 17 00:00:00 2001 From: MYLS Date: Fri, 24 Jun 2016 22:27:42 +0800 Subject: [PATCH 37/95] Split `cvWriteRawData_Base64` into three functions The three new functions: ```cpp void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt); void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len); void cvEndWriteRawData_Base64(::CvFileStorage * fs); ``` Test is also updated. (And it's remarkable that there is a bug in `cvWriteReadData`.) --- .../core/include/opencv2/core/persistence.hpp | 6 +- modules/core/src/persistence.cpp | 154 ++++++++--- modules/core/test/test_io.cpp | 245 +++++++++--------- 3 files changed, 252 insertions(+), 153 deletions(-) diff --git a/modules/core/include/opencv2/core/persistence.hpp b/modules/core/include/opencv2/core/persistence.hpp index 6ceeca438b..65a1ff4c4c 100644 --- a/modules/core/include/opencv2/core/persistence.hpp +++ b/modules/core/include/opencv2/core/persistence.hpp @@ -1241,7 +1241,11 @@ inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, * //! @endcond -CV_EXPORTS void cvWriteRawData_Base64(FileStorage & fs, const void* _data, int len, const char* dt); +CV_EXPORTS void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt); + +CV_EXPORTS void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len); + +CV_EXPORTS void cvEndWriteRawData_Base64(::CvFileStorage * fs); CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat); diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index fade7a71a4..2fc4f9f5bb 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -183,6 +183,8 @@ typedef struct CvXMLStackRecord } CvXMLStackRecord; +namespace base64 { class Base64Writer; } + #define CV_XML_OPENING_TAG 1 #define CV_XML_CLOSING_TAG 2 #define CV_XML_EMPTY_TAG 3 @@ -240,6 +242,8 @@ typedef struct CvFileStorage size_t strbufsize, strbufpos; std::deque* outbuf; + base64::Base64Writer * base64_writer; + bool is_opened; } CvFileStorage; @@ -319,6 +323,10 @@ namespace base64 /* sample */ + void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt); + void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len); + void cvEndWriteRawData_Base64(::CvFileStorage * fs); + void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt); void cvWriteMat_Base64(CvFileStorage * fs, const char * name, ::cv::Mat const & mat); } @@ -6414,14 +6422,14 @@ public: , binary_buffer(BUFFER_LEN) , base64_buffer(base64_encode_buffer_size(BUFFER_LEN)) , src_beg(0) - , src_end(0) , src_cur(0) + , src_end(0) { src_beg = binary_buffer.data(); src_end = src_beg + BUFFER_LEN; src_cur = src_beg; - // TODO: check if fs.state is valid. + CV_CHECK_OUTPUT_FILE_STORAGE(fs); ::icvFSFlush(file_storage); } @@ -6515,8 +6523,8 @@ private: std::vector binary_buffer; std::vector base64_buffer; uchar * src_beg; - uchar * src_end; uchar * src_cur; + uchar * src_end; }; class base64::MatToBinaryConvertor @@ -6927,9 +6935,72 @@ private: * Wapper ***************************************************************************/ -void base64::make_seq(void * binary, int elem_cnt, const char * dt, CvSeq & seq) +class base64::Base64Writer { - CvFileNode node; +public: + + Base64Writer(::CvFileStorage * fs, const char * name, int len, const char* dt) + : file_storage(fs) + , emitter(fs) + , remaining_data_length(len) + , data_type_string(dt) + { + CV_CHECK_OUTPUT_FILE_STORAGE(fs); + + cvStartWriteStruct(fs, name, CV_NODE_SEQ, "binary"); + icvFSFlush(fs); + + /* output header */ + + /* total byte size(before encode) */ + int size = len * ::icvCalcStructSize(dt, 0); + + std::string buffer = make_base64_header(size, dt); + const uchar * beg = reinterpret_cast(buffer.data()); + const uchar * end = beg + buffer.size(); + + emitter.write(beg, end); + } + + void write(const void* _data, int len) + { + CV_Assert(len >= 0); + CV_Assert(remaining_data_length >= static_cast(len)); + remaining_data_length -= static_cast(len); + + RawDataToBinaryConvertor convertor(_data, len, data_type_string); + emitter.write(convertor); + } + + template inline + void write(_to_binary_convertor_t & convertor, int data_length_of_convertor) + { + CV_Assert(data_length_of_convertor >= 0); + CV_Assert(remaining_data_length >= static_cast(data_length_of_convertor)); + remaining_data_length -= static_cast(data_length_of_convertor); + + emitter.write(convertor); + } + + ~Base64Writer() + { + CV_Assert(remaining_data_length == 0U); + emitter.flush(); + cvEndWriteStruct(file_storage); + icvFSFlush(file_storage); + } + +private: + + ::CvFileStorage * file_storage; + Base64ContextEmitter emitter; + size_t remaining_data_length; + const char* data_type_string; +}; + +void base64::make_seq(void * binary, int elem_cnt, const char * dt, ::CvSeq & seq) +{ + ::CvFileNode node; node.info = 0; BinaryToCvSeqConvertor convertor(binary, elem_cnt, dt); while (convertor) { @@ -6938,7 +7009,32 @@ void base64::make_seq(void * binary, int elem_cnt, const char * dt, CvSeq & seq) } } -void base64::cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int len, const char* dt) +void base64::cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt) +{ + CV_Assert(fs); + CV_CHECK_OUTPUT_FILE_STORAGE(fs); + CV_Assert(fs->base64_writer == 0); + fs->base64_writer = new Base64Writer(fs, name, len, dt); +} + +void base64::cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len) +{ + CV_Assert(fs); + CV_CHECK_OUTPUT_FILE_STORAGE(fs); + CV_Assert(fs->base64_writer != 0); + fs->base64_writer->write(_data, len); +} + +void base64::cvEndWriteRawData_Base64(::CvFileStorage * fs) +{ + CV_Assert(fs); + CV_CHECK_OUTPUT_FILE_STORAGE(fs); + CV_Assert(fs->base64_writer != 0); + delete fs->base64_writer; + fs->base64_writer = 0; +} + +void base64::cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt) { cvStartWriteStruct(*fs, fs.elname.c_str(), CV_NODE_SEQ, "binary"); { @@ -6960,7 +7056,7 @@ void base64::cvWriteRawData_Base64(cv::FileStorage & fs, const void* _data, int cvEndWriteStruct(*fs); } -void base64::cvWriteMat_Base64(CvFileStorage * fs, const char * name, cv::Mat const & mat) +void base64::cvWriteMat_Base64(::CvFileStorage * fs, const char * name, ::cv::Mat const & mat) { char dt[4]; ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt); @@ -6982,27 +7078,14 @@ void base64::cvWriteMat_Base64(CvFileStorage * fs, const char * name, cv::Mat co cvWriteString(fs, "dt", ::icvEncodeFormat(CV_MAT_TYPE(mat.type()), dt ), 0 ); } - cvStartWriteStruct(fs, "data", CV_NODE_SEQ, "binary"); { /* [2]deal with matrix's data */ - Base64ContextEmitter emitter(fs); + int len = static_cast(mat.total()); + MatToBinaryConvertor convertor(mat); - { /* [2][1]define base64 header */ - /* total byte size */ - int size = static_cast(mat.total() * mat.elemSize()); - std::string buffer = make_base64_header(size, dt); - const uchar * beg = reinterpret_cast(buffer.data()); - const uchar * end = beg + buffer.size(); - - emitter.write(beg, end); - } - - { /* [2][2]base64 body */ - MatToBinaryConvertor convertor(mat); - - emitter.write(convertor); - } + cvStartWriteRawData_Base64(fs, "data", len, dt); + fs->base64_writer->write(convertor, len); + cvEndWriteRawData_Base64(fs); } - cvEndWriteStruct(fs); { /* [3]output end */ cvEndWriteStruct(fs); @@ -7015,11 +7098,6 @@ void base64::cvWriteMat_Base64(CvFileStorage * fs, const char * name, cv::Mat co namespace cv { - void cvWriteRawData_Base64(::cv::FileStorage & fs, const void* _data, int len, const char* dt) - { - ::base64::cvWriteRawData_Base64(fs, _data, len, dt); - } - void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat) { ::cv::Mat holder = ::cv::cvarrToMat(mat); @@ -7031,6 +7109,22 @@ namespace cv ::cv::Mat holder = ::cv::cvarrToMat(mat); ::base64::cvWriteMat_Base64(fs, name, holder); } + + void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt) + { + ::base64::cvStartWriteRawData_Base64(fs, name, len, dt); + } + + void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len) + { + ::base64::cvWriteRawData_Base64(fs, _data, len); + } + + void cvEndWriteRawData_Base64(::CvFileStorage * fs) + { + ::base64::cvEndWriteRawData_Base64(fs); + } + } diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 99646e43f0..39cd2ca176 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -583,132 +583,133 @@ TEST(Core_InputOutput, filestorage_yml_compatibility) //EXPECT_ANY_THROW(); } +class CV_Base64IOTest : public cvtest::BaseTest +{ +private: + std::string file_name; + +public: + CV_Base64IOTest(std::string const & file_name) + : file_name(file_name) {} + ~CV_Base64IOTest() {} +protected: + void run(int) + { + try + { + struct data_t + { + uchar u1, u2; + int i1, i2, i3; + double d1, d2; + int i4; + }; + std::vector rawdata; + + cv::Mat _em_out, _em_in; + cv::Mat _2d_out, _2d_in; + cv::Mat _nd_out, _nd_in; + + { /* init */ + + /* normal mat */ + _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); + for (int i = 0; i < _2d_out.rows; ++i) + for (int j = 0; j < _2d_out.cols; ++j) + _2d_out.at(i, j)[1] = i % 256; + + /* 4d mat */ + const int Size[] = {4, 4, 4, 4}; + cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444)); + const cv::Range ranges[] = { + cv::Range(0, 2), + cv::Range(0, 2), + cv::Range(1, 2), + cv::Range(0, 2) }; + _nd_out = _4d(ranges); + + /* raw data */ + for (int i = 0; i < 1000; i++) + rawdata.push_back(data_t{1, 2, 1, 2, 3, 0.1, 0.2, i}); + } + + { /* write */ + cv::FileStorage fs(file_name, cv::FileStorage::WRITE); + CvMat holder = _2d_out; + cv::cvWriteMat_Base64(*fs, "normal_2d_mat", &holder); + CvMatND holder_nd = _nd_out; + cv::cvWriteMatND_Base64(*fs, "normal_nd_mat", &holder_nd); + holder = _em_out; + cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); + + cv::cvStartWriteRawData_Base64(*fs, "rawdata", rawdata.size(), "2u3i2di"); + for (int i = 0; i < 10; i++) + cv::cvWriteRawData_Base64(*fs, rawdata.data() + i * 100, 100); + cv::cvEndWriteRawData_Base64(*fs); + + fs.release(); + } + + { /* read */ + cv::FileStorage fs(file_name, cv::FileStorage::READ); + + /* mat */ + fs["empty_2d_mat"] >> _em_in; + fs["normal_2d_mat"] >> _2d_in; + fs["normal_nd_mat"] >> _nd_in; + + /* raw data */ + std::vector(1000).swap(rawdata); + cvReadRawData(*fs, fs["rawdata"].node, rawdata.data(), "2u3i2di"); + + fs.release(); + } + + for (int i = 0; i < 1000; i++) { + // TODO: Solve this bug + //EXPECT_EQ(rawdata[i].u1, 1); + //EXPECT_EQ(rawdata[i].u2, 2); + //EXPECT_EQ(rawdata[i].i1, 1); + //EXPECT_EQ(rawdata[i].i2, 2); + //EXPECT_EQ(rawdata[i].i3, 3); + //EXPECT_EQ(rawdata[i].d1, 0.1); + //EXPECT_EQ(rawdata[i].d2, 0.2); + //EXPECT_EQ(rawdata[i].i4, i); + } + + EXPECT_EQ(_em_in.rows , _em_out.rows); + EXPECT_EQ(_em_in.cols , _em_out.cols); + EXPECT_EQ(_em_in.dims , _em_out.dims); + EXPECT_EQ(_em_in.depth(), _em_out.depth()); + EXPECT_TRUE(_em_in.empty()); + + EXPECT_EQ(_2d_in.rows , _2d_in.rows); + EXPECT_EQ(_2d_in.cols , _2d_in.cols); + EXPECT_EQ(_2d_in.dims , _2d_in.dims); + EXPECT_EQ(_2d_in.depth(), _2d_in.depth()); + for(int i = 0; i < _2d_in.rows; ++i) + for (int j = 0; j < _2d_in.cols; ++j) + EXPECT_EQ(_2d_in.at(i, j), _2d_out.at(i, j)); + + EXPECT_EQ(_nd_in.rows , _nd_in.rows); + EXPECT_EQ(_nd_in.cols , _nd_in.cols); + EXPECT_EQ(_nd_in.dims , _nd_in.dims); + EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); + EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0); + } + catch(...) + { + ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH); + } + } +}; + TEST(Core_InputOutput, filestorage_yml_base64) { - cv::Mat _em_out, _em_in; - cv::Mat _2d_out, _2d_in; - cv::Mat _nd_out, _nd_in; - - { /* init */ - - /* normal mat */ - _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); - for (int i = 0; i < _2d_out.rows; ++i) - for (int j = 0; j < _2d_out.cols; ++j) - _2d_out.at(i, j)[1] = i % 256; - - /* 4d mat */ - const int Size[] = {4, 4, 4, 4}; - cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444)); - const cv::Range ranges[] = { - cv::Range(0, 2), - cv::Range(0, 2), - cv::Range(1, 2), - cv::Range(0, 2) }; - _nd_out = _4d(ranges); - } - - { /* write */ - cv::FileStorage fs("test.yml", cv::FileStorage::WRITE); - CvMat holder = _2d_out; - cv::cvWriteMat_Base64(*fs, "normal_2d_mat", &holder); - CvMatND holder_nd = _nd_out; - cv::cvWriteMatND_Base64(*fs, "normal_nd_mat", &holder_nd); - holder = _em_out; - cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); - fs.release(); - } - - { /* read */ - cv::FileStorage fs("test.yml", cv::FileStorage::READ); - fs["empty_2d_mat"] >> _em_in; - fs["normal_2d_mat"] >> _2d_in; - fs["normal_nd_mat"] >> _nd_in; - fs.release(); - } - - EXPECT_EQ(_em_in.rows , _em_out.rows); - EXPECT_EQ(_em_in.cols , _em_out.cols); - EXPECT_EQ(_em_in.dims , _em_out.dims); - EXPECT_EQ(_em_in.depth(), _em_out.depth()); - EXPECT_TRUE(_em_in.empty()); - - EXPECT_EQ(_2d_in.rows , _2d_in.rows); - EXPECT_EQ(_2d_in.cols , _2d_in.cols); - EXPECT_EQ(_2d_in.dims , _2d_in.dims); - EXPECT_EQ(_2d_in.depth(), _2d_in.depth()); - for(int i = 0; i < _2d_in.rows; ++i) - for (int j = 0; j < _2d_in.cols; ++j) - EXPECT_EQ(_2d_in.at(i, j), _2d_out.at(i, j)); - - EXPECT_EQ(_nd_in.rows , _nd_in.rows); - EXPECT_EQ(_nd_in.cols , _nd_in.cols); - EXPECT_EQ(_nd_in.dims , _nd_in.dims); - EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); - EXPECT_EQ(cv::countNonZero(cv::mean(_nd_in != _nd_out)), 0); + CV_Base64IOTest test("base64_test.yml"); test.safe_run(); } TEST(Core_InputOutput, filestorage_xml_base64) { - cv::Mat _em_out, _em_in; - cv::Mat _2d_out, _2d_in; - cv::Mat _nd_out, _nd_in; - - { /* init */ - - /* normal mat */ - _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); - for (int i = 0; i < _2d_out.rows; ++i) - for (int j = 0; j < _2d_out.cols; ++j) - _2d_out.at(i, j)[1] = i % 256; - - /* 4d mat */ - const int Size[] = {4, 4, 4, 4}; - cv::Mat _4d(4, Size, CV_64FC4, cvScalar(0.888, 0.111, 0.666, 0.444)); - const cv::Range ranges[] = { - cv::Range(0, 2), - cv::Range(0, 2), - cv::Range(1, 2), - cv::Range(0, 2) }; - _nd_out = _4d(ranges); - } - - { /* write */ - cv::FileStorage fs("test.xml", cv::FileStorage::WRITE); - CvMat holder = _2d_out; - cv::cvWriteMat_Base64(*fs, "normal_2d_mat", &holder); - CvMatND holder_nd = _nd_out; - cv::cvWriteMatND_Base64(*fs, "normal_nd_mat", &holder_nd); - holder = _em_out; - cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); - fs.release(); - } - - { /* read */ - cv::FileStorage fs("test.xml", cv::FileStorage::READ); - fs["empty_2d_mat"] >> _em_in; - fs["normal_2d_mat"] >> _2d_in; - fs["normal_nd_mat"] >> _nd_in; - fs.release(); - } - - EXPECT_EQ(_em_in.rows , _em_out.rows); - EXPECT_EQ(_em_in.cols , _em_out.cols); - EXPECT_EQ(_em_in.dims , _em_out.dims); - EXPECT_EQ(_em_in.depth(), _em_out.depth()); - EXPECT_TRUE(_em_in.empty()); - - EXPECT_EQ(_2d_in.rows , _2d_in.rows); - EXPECT_EQ(_2d_in.cols , _2d_in.cols); - EXPECT_EQ(_2d_in.dims , _2d_in.dims); - EXPECT_EQ(_2d_in.depth(), _2d_in.depth()); - for(int i = 0; i < _2d_in.rows; ++i) - for (int j = 0; j < _2d_in.cols; ++j) - EXPECT_EQ(_2d_in.at(i, j), _2d_out.at(i, j)); - - EXPECT_EQ(_nd_in.rows , _nd_in.rows); - EXPECT_EQ(_nd_in.cols , _nd_in.cols); - EXPECT_EQ(_nd_in.dims , _nd_in.dims); - EXPECT_EQ(_nd_in.depth(), _nd_in.depth()); - EXPECT_EQ(cv::countNonZero(cv::sum(_nd_in != _nd_out)), 0); + CV_Base64IOTest test("base64_test.xml"); test.safe_run(); } From 959002fb96cea52b71454229e01d775fbd4c0896 Mon Sep 17 00:00:00 2001 From: MYLS Date: Fri, 24 Jun 2016 23:41:40 +0800 Subject: [PATCH 38/95] solve warnings and errors in test. --- modules/core/test/test_io.cpp | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 39cd2ca176..3376965c2a 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -588,22 +588,23 @@ class CV_Base64IOTest : public cvtest::BaseTest private: std::string file_name; + struct data_t + { + uchar u1, u2; + int i1, i2, i3; + double d1, d2; + int i4; + }; + public: - CV_Base64IOTest(std::string const & file_name) - : file_name(file_name) {} + CV_Base64IOTest(std::string const & test_file_name) + : file_name(test_file_name) {} ~CV_Base64IOTest() {} protected: void run(int) { try { - struct data_t - { - uchar u1, u2; - int i1, i2, i3; - double d1, d2; - int i4; - }; std::vector rawdata; cv::Mat _em_out, _em_in; @@ -629,8 +630,18 @@ protected: _nd_out = _4d(ranges); /* raw data */ - for (int i = 0; i < 1000; i++) - rawdata.push_back(data_t{1, 2, 1, 2, 3, 0.1, 0.2, i}); + for (int i = 0; i < 1000; i++) { + data_t tmp; + rawdata[i].u1 = 1; + rawdata[i].u2 = 2; + rawdata[i].i1 = 1; + rawdata[i].i2 = 2; + rawdata[i].i3 = 3; + rawdata[i].d1 = 0.1; + rawdata[i].d2 = 0.2; + rawdata[i].i4 = i; + rawdata.push_back(tmp); + } } { /* write */ @@ -642,7 +653,7 @@ protected: holder = _em_out; cv::cvWriteMat_Base64(*fs, "empty_2d_mat", &holder); - cv::cvStartWriteRawData_Base64(*fs, "rawdata", rawdata.size(), "2u3i2di"); + cv::cvStartWriteRawData_Base64(*fs, "rawdata", static_cast(rawdata.size()), "2u3i2di"); for (int i = 0; i < 10; i++) cv::cvWriteRawData_Base64(*fs, rawdata.data() + i * 100, 100); cv::cvEndWriteRawData_Base64(*fs); From 677d4d20ce9de6b548887a05bbdd0ffb207281b0 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sat, 25 Jun 2016 00:37:13 +0800 Subject: [PATCH 39/95] fixed an error in the test... --- modules/core/test/test_io.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 3376965c2a..dcb25d72e0 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -632,14 +632,14 @@ protected: /* raw data */ for (int i = 0; i < 1000; i++) { data_t tmp; - rawdata[i].u1 = 1; - rawdata[i].u2 = 2; - rawdata[i].i1 = 1; - rawdata[i].i2 = 2; - rawdata[i].i3 = 3; - rawdata[i].d1 = 0.1; - rawdata[i].d2 = 0.2; - rawdata[i].i4 = i; + tmp.u1 = 1; + tmp.u2 = 2; + tmp.i1 = 1; + tmp.i2 = 2; + tmp.i3 = 3; + tmp.d1 = 0.1; + tmp.d2 = 0.2; + tmp.i4 = i; rawdata.push_back(tmp); } } From df5a7c8ee9d877655a6981dd263c0f303e239b51 Mon Sep 17 00:00:00 2001 From: MYLS Date: Sat, 25 Jun 2016 02:24:33 +0800 Subject: [PATCH 40/95] build again for OpenCL. I could not find the cause of the error: ``` C:\builds_ocv\precommit_opencl\opencv\modules\ts\src\ts_perf.cpp(361): error: The difference between expect_max and actual_max is 8445966.0000002384, which exceeds eps, where expect_max evaluates to 0.9999997615814209, actual_max evaluates to 8445967, and eps evaluates to 1.0000000000000001e-005. Argument "dst0" has unexpected maximal value ``` Hope this is a false alarm. --- modules/core/test/test_io.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index dcb25d72e0..1367776f2d 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -580,7 +580,7 @@ TEST(Core_InputOutput, FileStorageKey) TEST(Core_InputOutput, filestorage_yml_compatibility) { - //EXPECT_ANY_THROW(); + // TODO: } class CV_Base64IOTest : public cvtest::BaseTest @@ -617,7 +617,7 @@ protected: _2d_out = cv::Mat(100, 100, CV_8UC3, cvScalar(1U, 2U, 127U)); for (int i = 0; i < _2d_out.rows; ++i) for (int j = 0; j < _2d_out.cols; ++j) - _2d_out.at(i, j)[1] = i % 256; + _2d_out.at(i, j)[1] = (i + j) % 256; /* 4d mat */ const int Size[] = {4, 4, 4, 4}; @@ -677,7 +677,7 @@ protected: } for (int i = 0; i < 1000; i++) { - // TODO: Solve this bug + // TODO: Solve this bug in `cvReadRawData` //EXPECT_EQ(rawdata[i].u1, 1); //EXPECT_EQ(rawdata[i].u2, 2); //EXPECT_EQ(rawdata[i].i1, 1); @@ -717,10 +717,10 @@ protected: TEST(Core_InputOutput, filestorage_yml_base64) { - CV_Base64IOTest test("base64_test.yml"); test.safe_run(); + CV_Base64IOTest test("base64_test_tmp_file.yml"); test.safe_run(); } TEST(Core_InputOutput, filestorage_xml_base64) { - CV_Base64IOTest test("base64_test.xml"); test.safe_run(); + CV_Base64IOTest test("base64_test_tmp_file.xml"); test.safe_run(); } From 1b22783d4636a74512171d67b95e6482f73cd897 Mon Sep 17 00:00:00 2001 From: Suleyman TURKMEN Date: Sun, 26 Jun 2016 16:39:19 +0300 Subject: [PATCH 41/95] Update grfmt_png.cpp --- modules/imgcodecs/src/grfmt_png.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/modules/imgcodecs/src/grfmt_png.cpp b/modules/imgcodecs/src/grfmt_png.cpp index d5d175f89e..e672e0cc96 100644 --- a/modules/imgcodecs/src/grfmt_png.cpp +++ b/modules/imgcodecs/src/grfmt_png.cpp @@ -370,22 +370,23 @@ bool PngEncoder::write( const Mat& img, const std::vector& params ) } int compression_level = -1; // Invalid value to allow setting 0-9 as valid - int compression_strategy = Z_RLE; // Default strategy + int compression_strategy = IMWRITE_PNG_STRATEGY_RLE; // Default strategy bool isBilevel = false; for( size_t i = 0; i < params.size(); i += 2 ) { - if( params[i] == CV_IMWRITE_PNG_COMPRESSION ) + if( params[i] == IMWRITE_PNG_COMPRESSION ) { + compression_strategy = IMWRITE_PNG_STRATEGY_DEFAULT; // Default strategy compression_level = params[i+1]; compression_level = MIN(MAX(compression_level, 0), Z_BEST_COMPRESSION); } - if( params[i] == CV_IMWRITE_PNG_STRATEGY ) + if( params[i] == IMWRITE_PNG_STRATEGY ) { compression_strategy = params[i+1]; compression_strategy = MIN(MAX(compression_strategy, 0), Z_FIXED); } - if( params[i] == CV_IMWRITE_PNG_BILEVEL ) + if( params[i] == IMWRITE_PNG_BILEVEL ) { isBilevel = params[i+1] != 0; } From 11ca1c95f8ee86a0f38e48c19605b8f0f4791924 Mon Sep 17 00:00:00 2001 From: Suleyman TURKMEN Date: Mon, 15 Feb 2016 15:37:29 +0200 Subject: [PATCH 42/95] update cpp samples and tutorials --- .../jni/DetectionBasedTracker_jni.cpp | 2 +- .../jni/jni_part.cpp | 6 +- samples/cpp/3calibration.cpp | 8 +- samples/cpp/contours2.cpp | 4 +- samples/cpp/convexhull.cpp | 5 +- samples/cpp/cout_mat.cpp | 2 +- samples/cpp/dbt_face_detection.cpp | 12 +-- samples/cpp/delaunay2.cpp | 4 +- samples/cpp/facedetect.cpp | 6 +- samples/cpp/facial_features.cpp | 6 +- samples/cpp/fback.cpp | 6 +- samples/cpp/ffilldemo.cpp | 6 +- samples/cpp/filestorage.cpp | 2 +- samples/cpp/fitellipse.cpp | 5 +- samples/cpp/grabcut.cpp | 4 +- samples/cpp/houghcircles.cpp | 4 +- samples/cpp/houghlines.cpp | 4 +- samples/cpp/image.cpp | 4 +- samples/cpp/image_sequence.cpp | 6 +- samples/cpp/imagelist_creator.cpp | 4 +- samples/cpp/inpaint.cpp | 6 +- samples/cpp/intelperc_capture.cpp | 4 +- samples/cpp/kalman.cpp | 2 +- samples/cpp/laplace.cpp | 6 +- samples/cpp/letter_recog.cpp | 4 +- samples/cpp/lkdemo.cpp | 6 +- samples/cpp/lsd_lines.cpp | 10 +- samples/cpp/minarea.cpp | 4 +- samples/cpp/morphology2.cpp | 6 +- samples/cpp/openni_capture.cpp | 4 +- samples/cpp/pca.cpp | 4 +- samples/cpp/phase_corr.cpp | 8 +- samples/cpp/polar_transforms.cpp | 95 ++++++++----------- samples/cpp/segment_objects.cpp | 6 +- samples/cpp/squares.cpp | 19 ++-- samples/cpp/starter_imagelist.cpp | 2 +- samples/cpp/starter_video.cpp | 4 +- samples/cpp/stereo_calib.cpp | 6 +- samples/cpp/stereo_match.cpp | 4 +- samples/cpp/tree_engine.cpp | 4 +- .../HighGUI/AddingImagesTrackbar.cpp | 2 +- .../HighGUI/BasicLinearTransformsTrackbar.cpp | 2 +- .../Histograms_Matching/EqualizeHist_Demo.cpp | 9 +- .../MatchTemplate_Demo.cpp | 24 +++-- .../calcBackProject_Demo1.cpp | 12 ++- .../calcBackProject_Demo2.cpp | 6 +- .../Histograms_Matching/calcHist_Demo.cpp | 16 +++- .../Histograms_Matching/compareHist_Demo.cpp | 19 ++-- .../tutorial_code/ImgProc/AddingImages.cpp | 2 +- .../ImgProc/BasicLinearTransforms.cpp | 2 +- .../tutorial_code/ImgProc/Morphology_1.cpp | 8 +- .../tutorial_code/ImgProc/Morphology_2.cpp | 9 +- .../cpp/tutorial_code/ImgProc/Pyramids.cpp | 7 +- .../cpp/tutorial_code/ImgProc/Smoothing.cpp | 9 +- .../cpp/tutorial_code/ImgProc/Threshold.cpp | 13 +-- .../ImgTrans/CannyDetector_Demo.cpp | 8 +- .../ImgTrans/Geometric_Transforms_Demo.cpp | 7 +- .../ImgTrans/HoughCircle_Demo.cpp | 6 +- .../ImgTrans/HoughLines_Demo.cpp | 7 +- .../tutorial_code/ImgTrans/Laplace_Demo.cpp | 8 +- .../cpp/tutorial_code/ImgTrans/Remap_Demo.cpp | 7 +- .../cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp | 8 +- .../ImgTrans/copyMakeBorder_demo.cpp | 8 +- .../tutorial_code/ImgTrans/filter2D_demo.cpp | 8 +- .../ShapeDescriptors/findContours_demo.cpp | 8 +- .../generalContours_demo1.cpp | 8 +- .../generalContours_demo2.cpp | 8 +- .../ShapeDescriptors/hull_demo.cpp | 8 +- .../ShapeDescriptors/moments_demo.cpp | 8 +- .../pointPolygonTest_demo.cpp | 6 +- .../TrackingMotion/cornerDetector_Demo.cpp | 9 +- .../TrackingMotion/cornerHarris_Demo.cpp | 8 +- .../TrackingMotion/cornerSubPix_Demo.cpp | 8 +- .../goodFeaturesToTrack_Demo.cpp | 8 +- .../camera_calibration/camera_calibration.cpp | 4 +- .../real_time_pose_estimation/src/Utils.cpp | 4 +- .../src/main_detection.cpp | 8 +- .../src/main_registration.cpp | 8 +- .../calib3d/stereoBM/SBM_Sample.cpp | 6 +- .../discrete_fourier_transform.cpp | 6 +- .../file_input_output/file_input_output.cpp | 2 +- .../how_to_scan_images/how_to_scan_images.cpp | 2 +- .../interoperability_with_OpenCV_1.cpp | 7 +- .../mat_mask_operations.cpp | 30 +++--- .../mat_the_basic_image_container.cpp | 4 +- .../imgcodecs/GDAL_IO/gdal-image.cpp | 10 +- .../display_image/display_image.cpp | 8 +- .../photo/decolorization/decolor.cpp | 10 +- .../non_photorealistic_rendering/npr_demo.cpp | 12 +-- samples/cpp/tutorial_code/video/bg_sub.cpp | 6 +- .../video-input-psnr-ssim.cpp | 10 +- .../videoio/video-write/video-write.cpp | 6 +- samples/gpu/alpha_comp.cpp | 2 +- samples/gpu/cascadeclassifier.cpp | 6 +- samples/gpu/driver_api_multi.cpp | 2 +- samples/gpu/driver_api_stereo_multi.cpp | 4 +- samples/gpu/multi.cpp | 2 +- samples/gpu/opengl.cpp | 4 +- samples/gpu/opticalflow_nvidia_api.cpp | 3 +- samples/gpu/surf_keypoint_matcher.cpp | 6 +- samples/tapi/camshift.cpp | 6 +- samples/tapi/clahe.cpp | 6 +- samples/tapi/squares.cpp | 4 +- samples/tapi/tvl1_optical_flow.cpp | 4 +- .../FaceDetection/MainPage.xaml.cpp | 8 +- .../OcvTransform/OcvTransform.cpp | 6 +- .../OcvImageProcessing/MainPage.xaml.cpp | 4 +- .../PhoneTutorial/MainPage.xaml.cpp | 4 +- .../Direct3DInterop.cpp | 6 +- .../OpenCVComponent/OpenCVComponent.cpp | 7 +- 110 files changed, 394 insertions(+), 423 deletions(-) diff --git a/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp b/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp index 9fd8494b2f..7d198dc53e 100644 --- a/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp +++ b/samples/android/face-detection/jni/DetectionBasedTracker_jni.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include diff --git a/samples/android/tutorial-2-mixedprocessing/jni/jni_part.cpp b/samples/android/tutorial-2-mixedprocessing/jni/jni_part.cpp index 2c09961563..72fa0b24ab 100644 --- a/samples/android/tutorial-2-mixedprocessing/jni/jni_part.cpp +++ b/samples/android/tutorial-2-mixedprocessing/jni/jni_part.cpp @@ -1,7 +1,7 @@ #include -#include -#include -#include +#include +#include +#include #include using namespace std; diff --git a/samples/cpp/3calibration.cpp b/samples/cpp/3calibration.cpp index 12f2c81fca..7079b6d062 100644 --- a/samples/cpp/3calibration.cpp +++ b/samples/cpp/3calibration.cpp @@ -2,10 +2,10 @@ * 3calibration.cpp -- Calibrate 3 cameras in a horizontal line together. */ -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/imgcodecs/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/calib3d.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/imgcodecs.hpp" +#include "opencv2/highgui.hpp" #include "opencv2/core/utility.hpp" #include diff --git a/samples/cpp/contours2.cpp b/samples/cpp/contours2.cpp index c5a1fa70f5..437f76cb24 100644 --- a/samples/cpp/contours2.cpp +++ b/samples/cpp/contours2.cpp @@ -1,5 +1,5 @@ -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/highgui.hpp" #include #include diff --git a/samples/cpp/convexhull.cpp b/samples/cpp/convexhull.cpp index 36e5544548..fd2275645d 100644 --- a/samples/cpp/convexhull.cpp +++ b/samples/cpp/convexhull.cpp @@ -1,6 +1,5 @@ -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/highgui/highgui.hpp" -#include +#include "opencv2/imgproc.hpp" +#include "opencv2/highgui.hpp" #include using namespace cv; diff --git a/samples/cpp/cout_mat.cpp b/samples/cpp/cout_mat.cpp index bf1dfb2a41..ed2cd71c86 100644 --- a/samples/cpp/cout_mat.cpp +++ b/samples/cpp/cout_mat.cpp @@ -5,7 +5,7 @@ * */ -#include "opencv2/core/core.hpp" +#include "opencv2/core.hpp" #include using namespace std; diff --git a/samples/cpp/dbt_face_detection.cpp b/samples/cpp/dbt_face_detection.cpp index d7409bf5b5..920ae001d8 100644 --- a/samples/cpp/dbt_face_detection.cpp +++ b/samples/cpp/dbt_face_detection.cpp @@ -1,11 +1,11 @@ #if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(ANDROID) -#include // Gaussian Blur -#include // Basic OpenCV structures (cv::Mat, Scalar) -#include -#include // OpenCV window I/O -#include -#include +#include // Gaussian Blur +#include // Basic OpenCV structures (cv::Mat, Scalar) +#include +#include // OpenCV window I/O +#include +#include #include #include diff --git a/samples/cpp/delaunay2.cpp b/samples/cpp/delaunay2.cpp index a370feb2a7..4807cd373f 100644 --- a/samples/cpp/delaunay2.cpp +++ b/samples/cpp/delaunay2.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include #include using namespace cv; diff --git a/samples/cpp/facedetect.cpp b/samples/cpp/facedetect.cpp index 39717b7336..e9b648a7e9 100644 --- a/samples/cpp/facedetect.cpp +++ b/samples/cpp/facedetect.cpp @@ -177,7 +177,7 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade, resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); - t = (double)cvGetTickCount(); + t = (double)getTickCount(); cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0 //|CASCADE_FIND_BIGGEST_OBJECT @@ -198,8 +198,8 @@ void detectAndDraw( Mat& img, CascadeClassifier& cascade, faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height)); } } - t = (double)cvGetTickCount() - t; - printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) ); + t = (double)getTickCount() - t; + printf( "detection time = %g ms\n", t*1000/getTickFrequency()); for ( size_t i = 0; i < faces.size(); i++ ) { Rect r = faces[i]; diff --git a/samples/cpp/facial_features.cpp b/samples/cpp/facial_features.cpp index f46fa3fb56..3ed6a442f9 100644 --- a/samples/cpp/facial_features.cpp +++ b/samples/cpp/facial_features.cpp @@ -6,9 +6,9 @@ * */ -#include "opencv2/objdetect/objdetect.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/objdetect.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include #include diff --git a/samples/cpp/fback.cpp b/samples/cpp/fback.cpp index 5fbec6913c..a044844023 100644 --- a/samples/cpp/fback.cpp +++ b/samples/cpp/fback.cpp @@ -1,7 +1,7 @@ #include "opencv2/video/tracking.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" #include diff --git a/samples/cpp/ffilldemo.cpp b/samples/cpp/ffilldemo.cpp index 93bdd672bd..d10d72e0eb 100644 --- a/samples/cpp/ffilldemo.cpp +++ b/samples/cpp/ffilldemo.cpp @@ -1,7 +1,7 @@ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" #include diff --git a/samples/cpp/filestorage.cpp b/samples/cpp/filestorage.cpp index 60ea51acab..46b4da2414 100644 --- a/samples/cpp/filestorage.cpp +++ b/samples/cpp/filestorage.cpp @@ -2,7 +2,7 @@ * filestorage_sample demonstrate the usage of the opencv serialization functionality */ -#include "opencv2/core/core.hpp" +#include "opencv2/core.hpp" #include #include diff --git a/samples/cpp/fitellipse.cpp b/samples/cpp/fitellipse.cpp index b83f617c1d..0cd6c4a6db 100644 --- a/samples/cpp/fitellipse.cpp +++ b/samples/cpp/fitellipse.cpp @@ -14,10 +14,11 @@ * * ********************************************************************************/ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include + using namespace cv; using namespace std; diff --git a/samples/cpp/grabcut.cpp b/samples/cpp/grabcut.cpp index b6b406000b..726906c6ff 100644 --- a/samples/cpp/grabcut.cpp +++ b/samples/cpp/grabcut.cpp @@ -1,6 +1,6 @@ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include diff --git a/samples/cpp/houghcircles.cpp b/samples/cpp/houghcircles.cpp index bdafffec30..26c4dbae08 100644 --- a/samples/cpp/houghcircles.cpp +++ b/samples/cpp/houghcircles.cpp @@ -1,6 +1,6 @@ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include diff --git a/samples/cpp/houghlines.cpp b/samples/cpp/houghlines.cpp index ddeb3bd751..94eec86eeb 100644 --- a/samples/cpp/houghlines.cpp +++ b/samples/cpp/houghlines.cpp @@ -1,6 +1,6 @@ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include diff --git a/samples/cpp/image.cpp b/samples/cpp/image.cpp index b5925c69af..fc57738a77 100644 --- a/samples/cpp/image.cpp +++ b/samples/cpp/image.cpp @@ -1,7 +1,7 @@ #include #include -#include -#include +#include +#include #include using namespace cv; // all the new API is put into "cv" namespace. Export its content diff --git a/samples/cpp/image_sequence.cpp b/samples/cpp/image_sequence.cpp index 14b63e39c4..6a84fab4bd 100644 --- a/samples/cpp/image_sequence.cpp +++ b/samples/cpp/image_sequence.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include #include diff --git a/samples/cpp/imagelist_creator.cpp b/samples/cpp/imagelist_creator.cpp index bdb023187b..5b2dc38d47 100644 --- a/samples/cpp/imagelist_creator.cpp +++ b/samples/cpp/imagelist_creator.cpp @@ -1,9 +1,9 @@ /*this creates a yaml or xml list of files from the command line args */ -#include "opencv2/core/core.hpp" +#include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include #include diff --git a/samples/cpp/inpaint.cpp b/samples/cpp/inpaint.cpp index 62d7521932..86e6e37416 100644 --- a/samples/cpp/inpaint.cpp +++ b/samples/cpp/inpaint.cpp @@ -1,7 +1,7 @@ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/photo/photo.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/photo.hpp" #include diff --git a/samples/cpp/intelperc_capture.cpp b/samples/cpp/intelperc_capture.cpp index daae4420fb..d8a1c32241 100644 --- a/samples/cpp/intelperc_capture.cpp +++ b/samples/cpp/intelperc_capture.cpp @@ -1,8 +1,8 @@ // testOpenCVCam.cpp : Defines the entry point for the console application. // -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" #include diff --git a/samples/cpp/kalman.cpp b/samples/cpp/kalman.cpp index 8f9adc6c27..501a749124 100644 --- a/samples/cpp/kalman.cpp +++ b/samples/cpp/kalman.cpp @@ -1,5 +1,5 @@ #include "opencv2/video/tracking.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include diff --git a/samples/cpp/laplace.cpp b/samples/cpp/laplace.cpp index b33b49cbdb..462f62804e 100644 --- a/samples/cpp/laplace.cpp +++ b/samples/cpp/laplace.cpp @@ -1,6 +1,6 @@ -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include #include diff --git a/samples/cpp/letter_recog.cpp b/samples/cpp/letter_recog.cpp index 3d7e34ab7a..0eb67d1e42 100644 --- a/samples/cpp/letter_recog.cpp +++ b/samples/cpp/letter_recog.cpp @@ -1,5 +1,5 @@ -#include "opencv2/core/core.hpp" -#include "opencv2/ml/ml.hpp" +#include "opencv2/core.hpp" +#include "opencv2/ml.hpp" #include #include diff --git a/samples/cpp/lkdemo.cpp b/samples/cpp/lkdemo.cpp index 3881aa8650..5e57aa84a4 100644 --- a/samples/cpp/lkdemo.cpp +++ b/samples/cpp/lkdemo.cpp @@ -1,7 +1,7 @@ #include "opencv2/video/tracking.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" #include #include diff --git a/samples/cpp/lsd_lines.cpp b/samples/cpp/lsd_lines.cpp index 4c8c7e0a41..e0db6c3669 100644 --- a/samples/cpp/lsd_lines.cpp +++ b/samples/cpp/lsd_lines.cpp @@ -1,11 +1,8 @@ #include -#include -#include "opencv2/core/core.hpp" -#include "opencv2/core/utility.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" using namespace std; using namespace cv; @@ -23,6 +20,9 @@ int main(int argc, char** argv) Mat image = imread(in, IMREAD_GRAYSCALE); + if( image.empty() ) + { return -1; } + #if 0 Canny(image, image, 50, 200, 3); // Apply canny edge #endif diff --git a/samples/cpp/minarea.cpp b/samples/cpp/minarea.cpp index 91ad5a37bf..ac79db5e5a 100644 --- a/samples/cpp/minarea.cpp +++ b/samples/cpp/minarea.cpp @@ -1,5 +1,5 @@ -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include diff --git a/samples/cpp/morphology2.cpp b/samples/cpp/morphology2.cpp index 04e916c64a..8439080b2b 100644 --- a/samples/cpp/morphology2.cpp +++ b/samples/cpp/morphology2.cpp @@ -1,6 +1,6 @@ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include #include #include @@ -66,7 +66,7 @@ int main( int argc, char** argv ) return 0; } std::string filename = parser.get("@image"); - if( (src = imread(filename,1)).empty() ) + if( (src = imread(filename,IMREAD_COLOR)).empty() ) { help(); return -1; diff --git a/samples/cpp/openni_capture.cpp b/samples/cpp/openni_capture.cpp index 70d4a7c610..6c51624977 100644 --- a/samples/cpp/openni_capture.cpp +++ b/samples/cpp/openni_capture.cpp @@ -1,6 +1,6 @@ #include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include diff --git a/samples/cpp/pca.cpp b/samples/cpp/pca.cpp index 35fd0c1a04..b33a463211 100644 --- a/samples/cpp/pca.cpp +++ b/samples/cpp/pca.cpp @@ -42,9 +42,9 @@ #include #include -#include +#include #include "opencv2/imgcodecs.hpp" -#include +#include using namespace cv; using namespace std; diff --git a/samples/cpp/phase_corr.cpp b/samples/cpp/phase_corr.cpp index 5e8685fcfa..c3120fe084 100644 --- a/samples/cpp/phase_corr.cpp +++ b/samples/cpp/phase_corr.cpp @@ -1,7 +1,7 @@ -#include "opencv2/core/core.hpp" -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/core.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" using namespace cv; diff --git a/samples/cpp/polar_transforms.cpp b/samples/cpp/polar_transforms.cpp index 872dda8c3f..3cbc431c3c 100644 --- a/samples/cpp/polar_transforms.cpp +++ b/samples/cpp/polar_transforms.cpp @@ -1,94 +1,75 @@ -#include "opencv2/imgproc/imgproc_c.h" -#include "opencv2/videoio/videoio_c.h" -#include "opencv2/highgui/highgui_c.h" -#include "opencv2/core/utility.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include -#include -#include +using namespace cv; static void help( void ) { printf("\nThis program illustrates Linear-Polar and Log-Polar image transforms\n" "Usage :\n" - "./polar_transforms [[camera number -- Default 0],[AVI path_filename]]\n\n" - ); + "./polar_transforms [[camera number -- Default 0],[path_to_filename]]\n\n"); } + int main( int argc, char** argv ) { - CvCapture* capture = 0; - IplImage* log_polar_img = 0; - IplImage* lin_polar_img = 0; - IplImage* recovered_img = 0; + VideoCapture capture; + Mat log_polar_img, lin_polar_img, recovered_log_polar, recovered_lin_polar_img; help(); - cv::CommandLineParser parser(argc, argv, "{help h||}{@input|0|}"); - if (parser.has("help")) - { - help(); - return 0; - } + + CommandLineParser parser(argc, argv, "{@input|0|}"); std::string arg = parser.get("@input"); + if( arg.size() == 1 && isdigit(arg[0]) ) - capture = cvCaptureFromCAM( arg[0] - '0' ); + capture.open( arg[0] - '0' ); else - capture = cvCaptureFromAVI( arg.c_str() ); - if( !capture ) + capture.open( arg.c_str() ); + + if( !capture.isOpened() ) { const char* name = argv[0]; fprintf(stderr,"Could not initialize capturing...\n"); fprintf(stderr,"Usage: %s , or \n %s \n", name, name); - help(); return -1; } - cvNamedWindow( "Linear-Polar", 0 ); - cvNamedWindow( "Log-Polar", 0 ); - cvNamedWindow( "Recovered image", 0 ); + namedWindow( "Linear-Polar", WINDOW_NORMAL ); + namedWindow( "Log-Polar", WINDOW_NORMAL ); + namedWindow( "Recovered Linear-Polar", WINDOW_NORMAL ); + namedWindow( "Recovered Log-Polar", WINDOW_NORMAL ); - cvMoveWindow( "Linear-Polar", 20,20 ); - cvMoveWindow( "Log-Polar", 700,20 ); - cvMoveWindow( "Recovered image", 20,700 ); + moveWindow( "Linear-Polar", 20,20 ); + moveWindow( "Log-Polar", 700,20 ); + moveWindow( "Recovered Linear-Polar", 20, 350 ); + moveWindow( "Recovered Log-Polar", 700, 350 ); for(;;) { - IplImage* frame = 0; + Mat frame; + capture >> frame; - frame = cvQueryFrame( capture ); - if( !frame ) + if( frame.empty() ) break; - if( !log_polar_img ) - { - log_polar_img = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); - lin_polar_img = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); - recovered_img = cvCreateImage( cvSize(frame->width,frame->height), IPL_DEPTH_8U, frame->nChannels ); - } + Point2f center( (float)frame.cols / 2, (float)frame.rows / 2 ); + double M = (double)frame.cols / 8; - cvLogPolar(frame,log_polar_img,cvPoint2D32f(frame->width >> 1,frame->height >> 1),70, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS); - cvLinearPolar(frame,lin_polar_img,cvPoint2D32f(frame->width >> 1,frame->height >> 1),70, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS); + logPolar(frame,log_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS); + linearPolar(frame,lin_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS); -#if 0 - cvLogPolar(log_polar_img,recovered_img,cvPoint2D32f(frame->width >> 1,frame->height >> 1),70, CV_WARP_INVERSE_MAP+CV_INTER_LINEAR); -#else - cvLinearPolar(lin_polar_img,recovered_img,cvPoint2D32f(frame->width >> 1,frame->height >> 1),70, CV_WARP_INVERSE_MAP+CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS); -#endif + logPolar(log_polar_img, recovered_log_polar, center, M, WARP_INVERSE_MAP + INTER_LINEAR); + linearPolar(lin_polar_img, recovered_lin_polar_img, center, M, WARP_INVERSE_MAP + INTER_LINEAR + WARP_FILL_OUTLIERS); - cvShowImage("Log-Polar", log_polar_img ); - cvShowImage("Linear-Polar", lin_polar_img ); - cvShowImage("Recovered image", recovered_img ); + imshow("Log-Polar", log_polar_img ); + imshow("Linear-Polar", lin_polar_img ); + imshow("Recovered Linear-Polar", recovered_lin_polar_img ); + imshow("Recovered Log-Polar", recovered_log_polar ); - if( cvWaitKey(10) >= 0 ) + if( waitKey(10) >= 0 ) break; } - cvReleaseCapture( &capture ); - cvDestroyWindow("Linear-Polar"); - cvDestroyWindow("Log-Polar"); - cvDestroyWindow("Recovered image"); - + waitKey(0); return 0; } - -#ifdef _EiC -main(1,"laplace.c"); -#endif diff --git a/samples/cpp/segment_objects.cpp b/samples/cpp/segment_objects.cpp index 3c217f679d..916283124f 100644 --- a/samples/cpp/segment_objects.cpp +++ b/samples/cpp/segment_objects.cpp @@ -1,6 +1,6 @@ -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/videoio/videoio.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/videoio.hpp" +#include "opencv2/highgui.hpp" #include "opencv2/video/background_segm.hpp" #include #include diff --git a/samples/cpp/squares.cpp b/samples/cpp/squares.cpp index f53e931e75..df8459caa4 100644 --- a/samples/cpp/squares.cpp +++ b/samples/cpp/squares.cpp @@ -2,10 +2,10 @@ // It loads several images sequentially and tries to find squares in // each image -#include "opencv2/core/core.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include #include @@ -23,8 +23,8 @@ static void help() "Returns sequence of squares detected on the image.\n" "the sequence is stored in the specified memory storage\n" "Call:\n" - "./squares\n" - "Using OpenCV version %s\n" << CV_VERSION << "\n" << endl; + "./squares [file_name (optional)]\n" + "Using OpenCV version " << CV_VERSION << "\n" << endl; } @@ -140,11 +140,18 @@ static void drawSquares( Mat& image, const vector >& squares ) } -int main(int /*argc*/, char** /*argv*/) +int main(int argc, char** argv) { static const char* names[] = { "../data/pic1.png", "../data/pic2.png", "../data/pic3.png", "../data/pic4.png", "../data/pic5.png", "../data/pic6.png", 0 }; help(); + + if( argc > 1) + { + names[0] = argv[1]; + names[1] = "0"; + } + namedWindow( wndname, 1 ); vector > squares; diff --git a/samples/cpp/starter_imagelist.cpp b/samples/cpp/starter_imagelist.cpp index 89df0cc1b5..6f4f71466c 100644 --- a/samples/cpp/starter_imagelist.cpp +++ b/samples/cpp/starter_imagelist.cpp @@ -9,7 +9,7 @@ * easy as CV_PI right? */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include #include diff --git a/samples/cpp/starter_video.cpp b/samples/cpp/starter_video.cpp index d6bf1b7664..2839b03d7e 100644 --- a/samples/cpp/starter_video.cpp +++ b/samples/cpp/starter_video.cpp @@ -12,8 +12,8 @@ */ #include -#include -#include +#include +#include #include #include diff --git a/samples/cpp/stereo_calib.cpp b/samples/cpp/stereo_calib.cpp index 117c9bac5d..842a6492bd 100644 --- a/samples/cpp/stereo_calib.cpp +++ b/samples/cpp/stereo_calib.cpp @@ -22,10 +22,10 @@ GitHub: https://github.com/Itseez/opencv/ ************************************************** */ -#include "opencv2/calib3d/calib3d.hpp" +#include "opencv2/calib3d.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include #include diff --git a/samples/cpp/stereo_match.cpp b/samples/cpp/stereo_match.cpp index e88b139a16..4868a63950 100644 --- a/samples/cpp/stereo_match.cpp +++ b/samples/cpp/stereo_match.cpp @@ -8,9 +8,9 @@ */ #include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include "opencv2/core/utility.hpp" #include diff --git a/samples/cpp/tree_engine.cpp b/samples/cpp/tree_engine.cpp index 4412588753..96b2adf837 100644 --- a/samples/cpp/tree_engine.cpp +++ b/samples/cpp/tree_engine.cpp @@ -1,5 +1,5 @@ -#include "opencv2/ml/ml.hpp" -#include "opencv2/core/core.hpp" +#include "opencv2/ml.hpp" +#include "opencv2/core.hpp" #include "opencv2/core/utility.hpp" #include #include diff --git a/samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp b/samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp index 9e04dd912e..93a7b48b19 100644 --- a/samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp +++ b/samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp @@ -5,7 +5,7 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include using namespace cv; diff --git a/samples/cpp/tutorial_code/HighGUI/BasicLinearTransformsTrackbar.cpp b/samples/cpp/tutorial_code/HighGUI/BasicLinearTransformsTrackbar.cpp index 213850f995..1834e35e22 100644 --- a/samples/cpp/tutorial_code/HighGUI/BasicLinearTransformsTrackbar.cpp +++ b/samples/cpp/tutorial_code/HighGUI/BasicLinearTransformsTrackbar.cpp @@ -6,7 +6,7 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" using namespace cv; diff --git a/samples/cpp/tutorial_code/Histograms_Matching/EqualizeHist_Demo.cpp b/samples/cpp/tutorial_code/Histograms_Matching/EqualizeHist_Demo.cpp index 45db5854e5..80d4d4645b 100644 --- a/samples/cpp/tutorial_code/Histograms_Matching/EqualizeHist_Demo.cpp +++ b/samples/cpp/tutorial_code/Histograms_Matching/EqualizeHist_Demo.cpp @@ -5,10 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace cv; using namespace std; @@ -24,10 +23,10 @@ int main( int, char** argv ) const char* equalized_window = "Equalized Image"; /// Load image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) - { cout<<"Usage: ./Histogram_Demo "<"< -#include using namespace std; using namespace cv; @@ -27,11 +26,24 @@ void MatchingMethod( int, void* ); /** * @function main */ -int main( int, char** argv ) +int main( int argc, char** argv ) { + if (argc < 3) + { + cout << "Not enough parameters" << endl; + cout << "Usage:\n./MatchTemplate_Demo " << endl; + return -1; + } + /// Load image and template - img = imread( argv[1], 1 ); - templ = imread( argv[2], 1 ); + img = imread( argv[1], IMREAD_COLOR ); + templ = imread( argv[2], IMREAD_COLOR ); + + if(img.empty() || templ.empty()) + { + cout << "Can't read one of the images" << endl; + return -1; + } /// Create windows namedWindow( image_window, WINDOW_AUTOSIZE ); diff --git a/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo1.cpp b/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo1.cpp index ce0e911237..1e2fe928f7 100644 --- a/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo1.cpp +++ b/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo1.cpp @@ -4,9 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include @@ -27,7 +27,13 @@ void Hist_and_Backproj(int, void* ); int main( int, char** argv ) { /// Read the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); + + if( src.empty() ) + { cout<<"Usage: ./calcBackProject_Demo1 "< @@ -30,7 +30,7 @@ void pickPoint (int event, int x, int y, int, void* ); int main( int, char** argv ) { /// Read the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Transform it to HSV cvtColor( src, hsv, COLOR_BGR2HSV ); diff --git a/samples/cpp/tutorial_code/Histograms_Matching/calcHist_Demo.cpp b/samples/cpp/tutorial_code/Histograms_Matching/calcHist_Demo.cpp index 1540cd85da..27e21e76b2 100644 --- a/samples/cpp/tutorial_code/Histograms_Matching/calcHist_Demo.cpp +++ b/samples/cpp/tutorial_code/Histograms_Matching/calcHist_Demo.cpp @@ -4,11 +4,10 @@ * @author */ -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace std; using namespace cv; @@ -16,12 +15,19 @@ using namespace cv; /** * @function main */ -int main( int, char** argv ) +int main(int argc, char** argv) { Mat src, dst; /// Load image - src = imread( argv[1], 1 ); + String imageName( "../data/lena.jpg" ); // by default + + if (argc > 1) + { + imageName = argv[1]; + } + + src = imread( imageName, IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/Histograms_Matching/compareHist_Demo.cpp b/samples/cpp/tutorial_code/Histograms_Matching/compareHist_Demo.cpp index 122e19bebc..4d0123b247 100644 --- a/samples/cpp/tutorial_code/Histograms_Matching/compareHist_Demo.cpp +++ b/samples/cpp/tutorial_code/Histograms_Matching/compareHist_Demo.cpp @@ -5,10 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace std; using namespace cv; @@ -26,13 +25,19 @@ int main( int argc, char** argv ) /// Load three images with different environment settings if( argc < 4 ) { - printf("** Error. Usage: ./compareHist_Demo \n"); + printf("** Error. Usage: ./compareHist_Demo \n"); return -1; } - src_base = imread( argv[1], 1 ); - src_test1 = imread( argv[2], 1 ); - src_test2 = imread( argv[3], 1 ); + src_base = imread( argv[1], IMREAD_COLOR ); + src_test1 = imread( argv[2], IMREAD_COLOR ); + src_test2 = imread( argv[3], IMREAD_COLOR ); + + if(src_base.empty() || src_test1.empty() || src_test2.empty()) + { + cout << "Can't read one of the images" << endl; + return -1; + } /// Convert to HSV cvtColor( src_base, hsv_base, COLOR_BGR2HSV ); diff --git a/samples/cpp/tutorial_code/ImgProc/AddingImages.cpp b/samples/cpp/tutorial_code/ImgProc/AddingImages.cpp index 32ce10f4b2..20b09ec32b 100644 --- a/samples/cpp/tutorial_code/ImgProc/AddingImages.cpp +++ b/samples/cpp/tutorial_code/ImgProc/AddingImages.cpp @@ -5,7 +5,7 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include using namespace cv; diff --git a/samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp b/samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp index 9ffe1563de..b24451de35 100644 --- a/samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp +++ b/samples/cpp/tutorial_code/ImgProc/BasicLinearTransforms.cpp @@ -5,7 +5,7 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include using namespace cv; diff --git a/samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp b/samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp index e8fac91300..626bd8b960 100644 --- a/samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp +++ b/samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -32,7 +30,7 @@ void Dilation( int, void* ); int main( int, char** argv ) { /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp b/samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp index 3f43eeeedb..97304a4612 100644 --- a/samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp +++ b/samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -34,7 +32,7 @@ void Morphology_Operations( int, void* ); int main( int, char** argv ) { /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } @@ -67,7 +65,6 @@ int main( int, char** argv ) */ void Morphology_Operations( int, void* ) { - // Since MORPH_X : 2,3,4,5 and 6 int operation = morph_operator + 2; diff --git a/samples/cpp/tutorial_code/ImgProc/Pyramids.cpp b/samples/cpp/tutorial_code/ImgProc/Pyramids.cpp index c52c0e04f4..e4b7096e6d 100644 --- a/samples/cpp/tutorial_code/ImgProc/Pyramids.cpp +++ b/samples/cpp/tutorial_code/ImgProc/Pyramids.cpp @@ -4,12 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; diff --git a/samples/cpp/tutorial_code/ImgProc/Smoothing.cpp b/samples/cpp/tutorial_code/ImgProc/Smoothing.cpp index e7ac4d40f5..6a84da073b 100644 --- a/samples/cpp/tutorial_code/ImgProc/Smoothing.cpp +++ b/samples/cpp/tutorial_code/ImgProc/Smoothing.cpp @@ -3,13 +3,10 @@ * brief Sample code for simple filters * author OpenCV team */ -#include -#include -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/features2d/features2d.hpp" +#include "opencv2/highgui.hpp" using namespace std; using namespace cv; @@ -35,7 +32,7 @@ int main( void ) namedWindow( window_name, WINDOW_AUTOSIZE ); /// Load the source image - src = imread( "../data/lena.jpg", 1 ); + src = imread( "../data/lena.jpg", IMREAD_COLOR ); if( display_caption( "Original Image" ) != 0 ) { return 0; } diff --git a/samples/cpp/tutorial_code/ImgProc/Threshold.cpp b/samples/cpp/tutorial_code/ImgProc/Threshold.cpp index 0944f6cd3b..36943028d9 100644 --- a/samples/cpp/tutorial_code/ImgProc/Threshold.cpp +++ b/samples/cpp/tutorial_code/ImgProc/Threshold.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -35,10 +33,13 @@ void Threshold_Demo( int, void* ); int main( int, char** argv ) { /// Load an image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); + + if( src.empty() ) + { return -1; } /// Convert the image to Gray - cvtColor( src, src_gray, COLOR_RGB2GRAY ); + cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// Create a window to display results namedWindow( window_name, WINDOW_AUTOSIZE ); diff --git a/samples/cpp/tutorial_code/ImgTrans/CannyDetector_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/CannyDetector_Demo.cpp index 92e10e4b0d..8b94bb3207 100644 --- a/samples/cpp/tutorial_code/ImgTrans/CannyDetector_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/CannyDetector_Demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -50,7 +48,7 @@ static void CannyThreshold(int, void*) int main( int, char** argv ) { /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/ImgTrans/Geometric_Transforms_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/Geometric_Transforms_Demo.cpp index 00184a3f87..edbb1e7387 100644 --- a/samples/cpp/tutorial_code/ImgTrans/Geometric_Transforms_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/Geometric_Transforms_Demo.cpp @@ -5,10 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace cv; using namespace std; @@ -31,7 +30,7 @@ int main( int, char** argv ) Mat src, warp_dst, warp_rotate_dst; /// Load the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Set the dst image the same type and size as src warp_dst = Mat::zeros( src.rows, src.cols, src.type() ); diff --git a/samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp index 02f03813f2..81bb3f8895 100644 --- a/samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp @@ -5,8 +5,8 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include using namespace std; @@ -63,7 +63,7 @@ int main(int argc, char** argv) } // Read the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { diff --git a/samples/cpp/tutorial_code/ImgTrans/HoughLines_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/HoughLines_Demo.cpp index 2d9b7b6454..5610cfefe5 100644 --- a/samples/cpp/tutorial_code/ImgTrans/HoughLines_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/HoughLines_Demo.cpp @@ -5,10 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace cv; using namespace std; @@ -39,7 +38,7 @@ void Probabilistic_Hough( int, void* ); int main( int, char** argv ) { /// Read the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { help(); diff --git a/samples/cpp/tutorial_code/ImgTrans/Laplace_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/Laplace_Demo.cpp index f0d45e715b..386b26da74 100644 --- a/samples/cpp/tutorial_code/ImgTrans/Laplace_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/Laplace_Demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -26,7 +24,7 @@ int main( int, char** argv ) const char* window_name = "Laplace Demo"; /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/ImgTrans/Remap_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/Remap_Demo.cpp index 49727e9cf0..b5a76faa47 100644 --- a/samples/cpp/tutorial_code/ImgTrans/Remap_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/Remap_Demo.cpp @@ -5,10 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include using namespace cv; @@ -27,7 +26,7 @@ void update_map( void ); int main( int, char** argv ) { /// Load the image - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Create dst, map_x and map_y with the same size as src: dst.create( src.size(), src.type() ); diff --git a/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp b/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp index 7d57e8ec6c..efe4c71691 100644 --- a/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -26,7 +24,7 @@ int main( int, char** argv ) int ddepth = CV_16S; /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp b/samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp index 5f786d568f..6da2b296b2 100644 --- a/samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -28,7 +26,7 @@ int main( int, char** argv ) int c; /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { diff --git a/samples/cpp/tutorial_code/ImgTrans/filter2D_demo.cpp b/samples/cpp/tutorial_code/ImgTrans/filter2D_demo.cpp index 3c580bb216..6fc04d8f41 100644 --- a/samples/cpp/tutorial_code/ImgTrans/filter2D_demo.cpp +++ b/samples/cpp/tutorial_code/ImgTrans/filter2D_demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include -#include +#include "opencv2/highgui.hpp" using namespace cv; @@ -30,7 +28,7 @@ int main ( int, char** argv ) int c; /// Load an image - src = imread( argv[1] ); + src = imread( argv[1], IMREAD_COLOR ); if( src.empty() ) { return -1; } diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/findContours_demo.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/findContours_demo.cpp index 6a6de95394..b831441b33 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/findContours_demo.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/findContours_demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -28,7 +26,7 @@ void thresh_callback(int, void* ); int main( int, char** argv ) { /// Load source image - src = imread(argv[1]); + src = imread(argv[1], IMREAD_COLOR); if (src.empty()) { cerr << "No image supplied ..." << endl; diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo1.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo1.cpp index a9c22e60fc..29d75515cf 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo1.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo1.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -28,7 +26,7 @@ void thresh_callback(int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo2.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo2.cpp index c6fd379328..742c6cf0a9 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo2.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/generalContours_demo2.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -28,7 +26,7 @@ void thresh_callback(int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/hull_demo.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/hull_demo.cpp index 0b354291a9..7fe5b71f98 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/hull_demo.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/hull_demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -28,7 +26,7 @@ void thresh_callback(int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/moments_demo.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/moments_demo.cpp index c3a5cbf60a..4064048df7 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/moments_demo.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/moments_demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -28,7 +26,7 @@ void thresh_callback(int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); diff --git a/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp b/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp index f55f8f6879..757b8dc0f8 100644 --- a/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp +++ b/samples/cpp/tutorial_code/ShapeDescriptors/pointPolygonTest_demo.cpp @@ -4,11 +4,9 @@ * @author OpenCV team */ -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; diff --git a/samples/cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp b/samples/cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp index c5dceab48b..52d7561522 100644 --- a/samples/cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp +++ b/samples/cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp @@ -3,12 +3,11 @@ * @brief Demo code for detecting corners using OpenCV built-in functions * @author OpenCV team */ + #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -40,7 +39,7 @@ void myHarris_function( int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// Set some parameters diff --git a/samples/cpp/tutorial_code/TrackingMotion/cornerHarris_Demo.cpp b/samples/cpp/tutorial_code/TrackingMotion/cornerHarris_Demo.cpp index 4314a97e26..4f1df4b844 100644 --- a/samples/cpp/tutorial_code/TrackingMotion/cornerHarris_Demo.cpp +++ b/samples/cpp/tutorial_code/TrackingMotion/cornerHarris_Demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -31,7 +29,7 @@ void cornerHarris_demo( int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// Create a window and a trackbar diff --git a/samples/cpp/tutorial_code/TrackingMotion/cornerSubPix_Demo.cpp b/samples/cpp/tutorial_code/TrackingMotion/cornerSubPix_Demo.cpp index 775e566ce7..8e4876bcee 100644 --- a/samples/cpp/tutorial_code/TrackingMotion/cornerSubPix_Demo.cpp +++ b/samples/cpp/tutorial_code/TrackingMotion/cornerSubPix_Demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -32,7 +30,7 @@ void goodFeaturesToTrack_Demo( int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// Create Window diff --git a/samples/cpp/tutorial_code/TrackingMotion/goodFeaturesToTrack_Demo.cpp b/samples/cpp/tutorial_code/TrackingMotion/goodFeaturesToTrack_Demo.cpp index cff59f5390..da357e7407 100644 --- a/samples/cpp/tutorial_code/TrackingMotion/goodFeaturesToTrack_Demo.cpp +++ b/samples/cpp/tutorial_code/TrackingMotion/goodFeaturesToTrack_Demo.cpp @@ -5,11 +5,9 @@ */ #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui.hpp" +#include "opencv2/imgproc.hpp" #include -#include -#include using namespace cv; using namespace std; @@ -32,7 +30,7 @@ void goodFeaturesToTrack_Demo( int, void* ); int main( int, char** argv ) { /// Load source image and convert it to gray - src = imread( argv[1], 1 ); + src = imread( argv[1], IMREAD_COLOR ); cvtColor( src, src_gray, COLOR_BGR2GRAY ); /// Create Window diff --git a/samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp b/samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp index 0322519839..580fe73792 100644 --- a/samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp +++ b/samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp @@ -21,7 +21,7 @@ using namespace std; static void help() { cout << "This is a camera calibration sample." << endl - << "Usage: calibration configurationFile" << endl + << "Usage: camera_calibration [configuration_file -- default ./default.xml]" << endl << "Near the sample file you'll find the configuration file, which has detailed help of " "how to edit it. It may be any OpenCV supported file format XML/YAML." << endl; } @@ -415,7 +415,7 @@ int main(int argc, char* argv[]) for(size_t i = 0; i < s.imageList.size(); i++ ) { - view = imread(s.imageList[i], 1); + view = imread(s.imageList[i], IMREAD_COLOR); if(view.empty()) continue; remap(view, rview, map1, map2, INTER_LINEAR); diff --git a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/Utils.cpp b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/Utils.cpp index fa2bad442e..b548bed463 100644 --- a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/Utils.cpp +++ b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/Utils.cpp @@ -11,8 +11,8 @@ #include "ModelRegistration.h" #include "Utils.h" -#include -#include +#include +#include // For text int fontFace = cv::FONT_ITALIC; diff --git a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_detection.cpp b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_detection.cpp index 6de590e684..4808e64135 100644 --- a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_detection.cpp +++ b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_detection.cpp @@ -2,11 +2,11 @@ #include #include // OpenCV -#include +#include #include -#include -#include -#include +#include +#include +#include #include // PnP Tutorial #include "Mesh.h" diff --git a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_registration.cpp b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_registration.cpp index da775a063e..5ddb83f0da 100644 --- a/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_registration.cpp +++ b/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/src/main_registration.cpp @@ -1,10 +1,10 @@ // C++ #include // OpenCV -#include -#include -#include -#include +#include +#include +#include +#include // PnP Tutorial #include "Mesh.h" #include "Model.h" diff --git a/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp b/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp index 90fa2801be..d114a9582f 100644 --- a/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp +++ b/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp @@ -4,12 +4,10 @@ * @author A. Huaman */ -#include #include -#include "opencv2/calib3d/calib3d.hpp" -#include "opencv2/core/core.hpp" +#include "opencv2/calib3d.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" using namespace cv; diff --git a/samples/cpp/tutorial_code/core/discrete_fourier_transform/discrete_fourier_transform.cpp b/samples/cpp/tutorial_code/core/discrete_fourier_transform/discrete_fourier_transform.cpp index dbebeea923..e23ab1c326 100644 --- a/samples/cpp/tutorial_code/core/discrete_fourier_transform/discrete_fourier_transform.cpp +++ b/samples/cpp/tutorial_code/core/discrete_fourier_transform/discrete_fourier_transform.cpp @@ -1,7 +1,7 @@ -#include "opencv2/core/core.hpp" -#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/highgui.hpp" #include diff --git a/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp b/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp index 8fc722df78..faeacfb967 100644 --- a/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp +++ b/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include diff --git a/samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp b/samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp index c673c66592..47a5547837 100644 --- a/samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp +++ b/samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp @@ -16,7 +16,7 @@ static void help() << " we take an input image and divide the native color palette (255) with the " << endl << "input. Shows C operator[] method, iterators and at function for on-the-fly item address calculation."<< endl << "Usage:" << endl - << "./howToScanImages imageNameToUse divideWith [G]" << endl + << "./how_to_scan_images [G]" << endl << "if you add a G parameter the image is processed in gray scale" << endl << "--------------------------------------------------------------------------" << endl << endl; diff --git a/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp b/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp index b6aa6131de..79e7c99d85 100644 --- a/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp +++ b/samples/cpp/tutorial_code/core/interoperability_with_OpenCV_1/interoperability_with_OpenCV_1.cpp @@ -1,12 +1,9 @@ //! [head] -#include #include -#include -#include +#include #include "opencv2/imgcodecs.hpp" -#include -#include +#include using namespace cv; // The new C++ interface API is inside this namespace. Import it. using namespace std; diff --git a/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp b/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp index f0cbca1695..8eb9ca7efd 100644 --- a/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp +++ b/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp @@ -1,5 +1,3 @@ -#include -#include #include #include #include @@ -25,38 +23,44 @@ int main( int argc, char* argv[]) help(argv[0]); const char* filename = argc >=2 ? argv[1] : "../data/lena.jpg"; - Mat I, J, K; + Mat src, dst0, dst1; if (argc >= 3 && !strcmp("G", argv[2])) - I = imread( filename, IMREAD_GRAYSCALE); + src = imread( filename, IMREAD_GRAYSCALE); else - I = imread( filename, IMREAD_COLOR); + src = imread( filename, IMREAD_COLOR); + + if (src.empty()) + { + cerr << "Can't open image [" << filename << "]" << endl; + return -1; + } namedWindow("Input", WINDOW_AUTOSIZE); namedWindow("Output", WINDOW_AUTOSIZE); - imshow("Input", I); + imshow( "Input", src ); double t = (double)getTickCount(); - Sharpen(I, J); + Sharpen( src, dst0 ); t = ((double)getTickCount() - t)/getTickFrequency(); cout << "Hand written function times passed in seconds: " << t << endl; - imshow("Output", J); - waitKey(0); + imshow( "Output", dst0 ); + waitKey(); - Mat kern = (Mat_(3,3) << 0, -1, 0, + Mat kernel = (Mat_(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); t = (double)getTickCount(); - filter2D(I, K, I.depth(), kern ); + filter2D( src, dst1, src.depth(), kernel ); t = ((double)getTickCount() - t)/getTickFrequency(); cout << "Built-in filter2D time passed in seconds: " << t << endl; - imshow("Output", K); + imshow( "Output", dst1 ); - waitKey(0); + waitKey(); return 0; } void Sharpen(const Mat& myImage,Mat& Result) diff --git a/samples/cpp/tutorial_code/core/mat_the_basic_image_container/mat_the_basic_image_container.cpp b/samples/cpp/tutorial_code/core/mat_the_basic_image_container/mat_the_basic_image_container.cpp index 7fb060bddd..77ea93827f 100644 --- a/samples/cpp/tutorial_code/core/mat_the_basic_image_container/mat_the_basic_image_container.cpp +++ b/samples/cpp/tutorial_code/core/mat_the_basic_image_container/mat_the_basic_image_container.cpp @@ -1,6 +1,6 @@ /* For description look into the help() function. */ -#include "opencv2/core/core.hpp" +#include "opencv2/core.hpp" #include using namespace std; @@ -15,7 +15,7 @@ static void help() << "That is, cv::Mat M(...); M.create and cout << M. " << endl << "Shows how output can be formated to OpenCV, python, numpy, csv and C styles." << endl << "Usage:" << endl - << "./cvout_sample" << endl + << "./mat_the_basic_image_container" << endl << "--------------------------------------------------------------------------" << endl << endl; } diff --git a/samples/cpp/tutorial_code/imgcodecs/GDAL_IO/gdal-image.cpp b/samples/cpp/tutorial_code/imgcodecs/GDAL_IO/gdal-image.cpp index 6e7c950a26..66084df78a 100644 --- a/samples/cpp/tutorial_code/imgcodecs/GDAL_IO/gdal-image.cpp +++ b/samples/cpp/tutorial_code/imgcodecs/GDAL_IO/gdal-image.cpp @@ -3,9 +3,9 @@ */ // OpenCV Headers -#include "opencv2/core/core.hpp" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/highgui/highgui.hpp" +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/highgui.hpp" // C++ Standard Libraries #include @@ -159,8 +159,8 @@ int main( int argc, char* argv[] ){ * Check input arguments */ if( argc < 3 ){ - cout << "usage: " << argv[0] << " " << endl; - return 1; + cout << "usage: " << argv[0] << " " << endl; + return -1; } // load the image (note that we don't have the projection information. You will diff --git a/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp b/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp index 558cb66d55..456286741e 100644 --- a/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp +++ b/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp @@ -1,7 +1,7 @@ //! [includes] -#include +#include #include -#include +#include #include #include @@ -16,7 +16,7 @@ using namespace std; int main( int argc, char** argv ) { //! [load] - string imageName("../data/HappyFish.jpg"); // by default + String imageName( "../data/HappyFish.jpg" ); // by default if( argc > 1) { imageName = argv[1]; @@ -28,7 +28,7 @@ int main( int argc, char** argv ) //! [mat] //! [imread] - image = imread(imageName.c_str(), IMREAD_COLOR); // Read the file + image = imread( imageName, IMREAD_COLOR ); // Read the file //! [imread] if( image.empty() ) // Check for invalid input diff --git a/samples/cpp/tutorial_code/photo/decolorization/decolor.cpp b/samples/cpp/tutorial_code/photo/decolorization/decolor.cpp index 067bad1178..13c1b0c5f7 100644 --- a/samples/cpp/tutorial_code/photo/decolorization/decolor.cpp +++ b/samples/cpp/tutorial_code/photo/decolorization/decolor.cpp @@ -27,13 +27,13 @@ using namespace cv; int main(int argc, char *argv[]) { CV_Assert(argc == 2); - Mat I; - I = imread(argv[1]); + Mat src; + src = imread(argv[1], IMREAD_COLOR); - Mat gray = Mat(I.size(),CV_8UC1); - Mat color_boost = Mat(I.size(),CV_8UC3); + Mat gray = Mat(src.size(),CV_8UC1); + Mat color_boost = Mat(src.size(),CV_8UC3); - decolor(I,gray,color_boost); + decolor(src,gray,color_boost); imshow("grayscale",gray); imshow("color_boost",color_boost); waitKey(0); diff --git a/samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp b/samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp index f81204c88b..8a24ddb7e6 100644 --- a/samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp +++ b/samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp @@ -35,9 +35,9 @@ int main(int argc, char* argv[]) int num,type; - Mat I = imread(argv[1]); + Mat src = imread(argv[1], IMREAD_COLOR); - if(I.empty()) + if(src.empty()) { cout << "Image not found" << endl; exit(0); @@ -71,25 +71,25 @@ int main(int argc, char* argv[]) cin >> type; - edgePreservingFilter(I,img,type); + edgePreservingFilter(src,img,type); imshow("Edge Preserve Smoothing",img); } else if(num == 2) { - detailEnhance(I,img); + detailEnhance(src,img); imshow("Detail Enhanced",img); } else if(num == 3) { Mat img1; - pencilSketch(I,img1, img, 10 , 0.1f, 0.03f); + pencilSketch(src,img1, img, 10 , 0.1f, 0.03f); imshow("Pencil Sketch",img1); imshow("Color Pencil Sketch",img); } else if(num == 4) { - stylization(I,img); + stylization(src,img); imshow("Stylization",img); } waitKey(0); diff --git a/samples/cpp/tutorial_code/video/bg_sub.cpp b/samples/cpp/tutorial_code/video/bg_sub.cpp index d37c7bd0f9..94799f388b 100644 --- a/samples/cpp/tutorial_code/video/bg_sub.cpp +++ b/samples/cpp/tutorial_code/video/bg_sub.cpp @@ -38,9 +38,9 @@ void help() << " OpenCV. You can process both videos (-vid) and images (-img)." << endl << endl << "Usage:" << endl - << "./bs {-vid