stat.cpp 115.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
I
Ilya Lavrenov 已提交
44
#include "opencl_kernels.hpp"
45
#include <climits>
46
#include <limits>
47 48 49 50 51 52 53 54 55 56 57 58

namespace cv
{

template<typename T> static inline Scalar rawToScalar(const T& v)
{
    Scalar s;
    typedef typename DataType<T>::channel_type T1;
    int i, n = DataType<T>::channels;
    for( i = 0; i < n; i++ )
        s.val[i] = ((T1*)&v)[i];
    return s;
59
}
60 61 62 63 64

/****************************************************************************************\
*                                        sum                                             *
\****************************************************************************************/

65
template<typename T, typename ST>
66
static int sum_(const T* src0, const uchar* mask, ST* dst, int len, int cn )
67
{
68 69
    const T* src = src0;
    if( !mask )
70
    {
V
Victoria Zhislina 已提交
71
        int i=0;
72 73 74 75
        int k = cn % 4;
        if( k == 1 )
        {
            ST s0 = dst[0];
V
Victoria Zhislina 已提交
76

77
            #if CV_ENABLE_UNROLLED
V
Victoria Zhislina 已提交
78
            for(; i <= len - 4; i += 4, src += cn*4 )
79
                s0 += src[0] + src[cn] + src[cn*2] + src[cn*3];
V
Victoria Zhislina 已提交
80
            #endif
81 82 83 84 85
            for( ; i < len; i++, src += cn )
                s0 += src[0];
            dst[0] = s0;
        }
        else if( k == 2 )
86
        {
87 88
            ST s0 = dst[0], s1 = dst[1];
            for( i = 0; i < len; i++, src += cn )
89
            {
90 91
                s0 += src[0];
                s1 += src[1];
92
            }
93 94 95 96 97 98 99
            dst[0] = s0;
            dst[1] = s1;
        }
        else if( k == 3 )
        {
            ST s0 = dst[0], s1 = dst[1], s2 = dst[2];
            for( i = 0; i < len; i++, src += cn )
100
            {
101 102 103
                s0 += src[0];
                s1 += src[1];
                s2 += src[2];
104
            }
105 106 107
            dst[0] = s0;
            dst[1] = s1;
            dst[2] = s2;
108
        }
109

110
        for( ; k < cn; k += 4 )
111
        {
112 113 114 115 116 117 118 119 120 121 122
            src = src0 + k;
            ST s0 = dst[k], s1 = dst[k+1], s2 = dst[k+2], s3 = dst[k+3];
            for( i = 0; i < len; i++, src += cn )
            {
                s0 += src[0]; s1 += src[1];
                s2 += src[2]; s3 += src[3];
            }
            dst[k] = s0;
            dst[k+1] = s1;
            dst[k+2] = s2;
            dst[k+3] = s3;
123
        }
124
        return len;
125
    }
126

127 128
    int i, nzm = 0;
    if( cn == 1 )
129
    {
130 131 132 133 134 135 136 137 138 139
        ST s = dst[0];
        for( i = 0; i < len; i++ )
            if( mask[i] )
            {
                s += src[i];
                nzm++;
            }
        dst[0] = s;
    }
    else if( cn == 3 )
V
Vadim Pisarevsky 已提交
140
    {
141 142 143 144 145 146 147 148 149 150 151 152
        ST s0 = dst[0], s1 = dst[1], s2 = dst[2];
        for( i = 0; i < len; i++, src += 3 )
            if( mask[i] )
            {
                s0 += src[0];
                s1 += src[1];
                s2 += src[2];
                nzm++;
            }
        dst[0] = s0;
        dst[1] = s1;
        dst[2] = s2;
V
Vadim Pisarevsky 已提交
153
    }
154 155 156 157 158 159
    else
    {
        for( i = 0; i < len; i++, src += cn )
            if( mask[i] )
            {
                int k = 0;
160
                #if CV_ENABLE_UNROLLED
161 162 163 164 165 166 167 168 169 170
                for( ; k <= cn - 4; k += 4 )
                {
                    ST s0, s1;
                    s0 = dst[k] + src[k];
                    s1 = dst[k+1] + src[k+1];
                    dst[k] = s0; dst[k+1] = s1;
                    s0 = dst[k+2] + src[k+2];
                    s1 = dst[k+3] + src[k+3];
                    dst[k+2] = s0; dst[k+3] = s1;
                }
V
Victoria Zhislina 已提交
171
                #endif
172 173 174 175 176 177
                for( ; k < cn; k++ )
                    dst[k] += src[k];
                nzm++;
            }
    }
    return nzm;
178 179
}

180

181 182
static int sum8u( const uchar* src, const uchar* mask, int* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
183

184 185
static int sum8s( const schar* src, const uchar* mask, int* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
186

187 188
static int sum16u( const ushort* src, const uchar* mask, int* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
189

190 191
static int sum16s( const short* src, const uchar* mask, int* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
192

193 194
static int sum32s( const int* src, const uchar* mask, double* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
195

196 197
static int sum32f( const float* src, const uchar* mask, double* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
198

199 200
static int sum64f( const double* src, const uchar* mask, double* dst, int len, int cn )
{ return sum_(src, mask, dst, len, cn); }
201

202 203
typedef int (*SumFunc)(const uchar*, const uchar* mask, uchar*, int, int);

204
static SumFunc getSumFunc(int depth)
205
{
206 207 208 209 210 211 212 213 214 215 216
    static SumFunc sumTab[] =
    {
        (SumFunc)GET_OPTIMIZED(sum8u), (SumFunc)sum8s,
        (SumFunc)sum16u, (SumFunc)sum16s,
        (SumFunc)sum32s,
        (SumFunc)GET_OPTIMIZED(sum32f), (SumFunc)sum64f,
        0
    };

    return sumTab[depth];
}
217

218 219 220
template<typename T>
static int countNonZero_(const T* src, int len )
{
V
Victoria Zhislina 已提交
221
    int i=0, nz = 0;
222
    #if CV_ENABLE_UNROLLED
V
Victoria Zhislina 已提交
223
    for(; i <= len - 4; i += 4 )
224
        nz += (src[i] != 0) + (src[i+1] != 0) + (src[i+2] != 0) + (src[i+3] != 0);
V
Victoria Zhislina 已提交
225
    #endif
226 227 228
    for( ; i < len; i++ )
        nz += src[i] != 0;
    return nz;
229 230
}

231
static int countNonZero8u( const uchar* src, int len )
232
{
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    int i=0, nz = 0;
#if CV_SSE2
    if(USE_SSE2)//5x-6x
    {
        __m128i pattern = _mm_setzero_si128 ();
        static uchar tab[256];
        static volatile bool initialized = false;
        if( !initialized )
        {
            // we compute inverse popcount table,
            // since we pass (img[x] == 0) mask as index in the table.
            for( int j = 0; j < 256; j++ )
            {
                int val = 0;
                for( int mask = 1; mask < 256; mask += mask )
                    val += (j & mask) == 0;
                tab[j] = (uchar)val;
            }
            initialized = true;
        }
253

254 255 256 257 258 259 260 261 262 263
        for (; i<=len-16; i+=16)
        {
            __m128i r0 = _mm_loadu_si128((const __m128i*)(src+i));
            int val = _mm_movemask_epi8(_mm_cmpeq_epi8(r0, pattern));
            nz += tab[val & 255] + tab[val >> 8];
        }
    }
#endif
    for( ; i < len; i++ )
        nz += src[i] != 0;
264 265 266
    return nz;
}

267 268
static int countNonZero16u( const ushort* src, int len )
{ return countNonZero_(src, len); }
269

270 271 272 273 274
static int countNonZero32s( const int* src, int len )
{ return countNonZero_(src, len); }

static int countNonZero32f( const float* src, int len )
{ return countNonZero_(src, len); }
275

276 277
static int countNonZero64f( const double* src, int len )
{ return countNonZero_(src, len); }
278

279
typedef int (*CountNonZeroFunc)(const uchar*, int);
280

281
static CountNonZeroFunc getCountNonZeroTab(int depth)
282
{
283 284 285 286 287 288 289
    static CountNonZeroFunc countNonZeroTab[] =
    {
        (CountNonZeroFunc)GET_OPTIMIZED(countNonZero8u), (CountNonZeroFunc)GET_OPTIMIZED(countNonZero8u),
        (CountNonZeroFunc)GET_OPTIMIZED(countNonZero16u), (CountNonZeroFunc)GET_OPTIMIZED(countNonZero16u),
        (CountNonZeroFunc)GET_OPTIMIZED(countNonZero32s), (CountNonZeroFunc)GET_OPTIMIZED(countNonZero32f),
        (CountNonZeroFunc)GET_OPTIMIZED(countNonZero64f), 0
    };
290

291 292
    return countNonZeroTab[depth];
}
293

294 295
template<typename T, typename ST, typename SQT>
static int sumsqr_(const T* src0, const uchar* mask, ST* sum, SQT* sqsum, int len, int cn )
296
{
297
    const T* src = src0;
298

299
    if( !mask )
V
Vadim Pisarevsky 已提交
300
    {
301 302
        int i;
        int k = cn % 4;
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        if( k == 1 )
        {
            ST s0 = sum[0];
            SQT sq0 = sqsum[0];
            for( i = 0; i < len; i++, src += cn )
            {
                T v = src[0];
                s0 += v; sq0 += (SQT)v*v;
            }
            sum[0] = s0;
            sqsum[0] = sq0;
        }
        else if( k == 2 )
        {
            ST s0 = sum[0], s1 = sum[1];
            SQT sq0 = sqsum[0], sq1 = sqsum[1];
            for( i = 0; i < len; i++, src += cn )
            {
                T v0 = src[0], v1 = src[1];
                s0 += v0; sq0 += (SQT)v0*v0;
                s1 += v1; sq1 += (SQT)v1*v1;
            }
            sum[0] = s0; sum[1] = s1;
            sqsum[0] = sq0; sqsum[1] = sq1;
        }
        else if( k == 3 )
        {
            ST s0 = sum[0], s1 = sum[1], s2 = sum[2];
            SQT sq0 = sqsum[0], sq1 = sqsum[1], sq2 = sqsum[2];
            for( i = 0; i < len; i++, src += cn )
            {
                T v0 = src[0], v1 = src[1], v2 = src[2];
                s0 += v0; sq0 += (SQT)v0*v0;
                s1 += v1; sq1 += (SQT)v1*v1;
                s2 += v2; sq2 += (SQT)v2*v2;
            }
            sum[0] = s0; sum[1] = s1; sum[2] = s2;
            sqsum[0] = sq0; sqsum[1] = sq1; sqsum[2] = sq2;
        }
343

344
        for( ; k < cn; k += 4 )
V
Vadim Pisarevsky 已提交
345
        {
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
            src = src0 + k;
            ST s0 = sum[k], s1 = sum[k+1], s2 = sum[k+2], s3 = sum[k+3];
            SQT sq0 = sqsum[k], sq1 = sqsum[k+1], sq2 = sqsum[k+2], sq3 = sqsum[k+3];
            for( i = 0; i < len; i++, src += cn )
            {
                T v0, v1;
                v0 = src[0], v1 = src[1];
                s0 += v0; sq0 += (SQT)v0*v0;
                s1 += v1; sq1 += (SQT)v1*v1;
                v0 = src[2], v1 = src[3];
                s2 += v0; sq2 += (SQT)v0*v0;
                s3 += v1; sq3 += (SQT)v1*v1;
            }
            sum[k] = s0; sum[k+1] = s1;
            sum[k+2] = s2; sum[k+3] = s3;
            sqsum[k] = sq0; sqsum[k+1] = sq1;
            sqsum[k+2] = sq2; sqsum[k+3] = sq3;
V
Vadim Pisarevsky 已提交
363
        }
364
        return len;
V
Vadim Pisarevsky 已提交
365
    }
366

367
    int i, nzm = 0;
368

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    if( cn == 1 )
    {
        ST s0 = sum[0];
        SQT sq0 = sqsum[0];
        for( i = 0; i < len; i++ )
            if( mask[i] )
            {
                T v = src[i];
                s0 += v; sq0 += (SQT)v*v;
                nzm++;
            }
        sum[0] = s0;
        sqsum[0] = sq0;
    }
    else if( cn == 3 )
    {
        ST s0 = sum[0], s1 = sum[1], s2 = sum[2];
        SQT sq0 = sqsum[0], sq1 = sqsum[1], sq2 = sqsum[2];
        for( i = 0; i < len; i++, src += 3 )
            if( mask[i] )
            {
                T v0 = src[0], v1 = src[1], v2 = src[2];
                s0 += v0; sq0 += (SQT)v0*v0;
                s1 += v1; sq1 += (SQT)v1*v1;
                s2 += v2; sq2 += (SQT)v2*v2;
                nzm++;
            }
        sum[0] = s0; sum[1] = s1; sum[2] = s2;
        sqsum[0] = sq0; sqsum[1] = sq1; sqsum[2] = sq2;
    }
    else
    {
        for( i = 0; i < len; i++, src += cn )
            if( mask[i] )
            {
                for( int k = 0; k < cn; k++ )
                {
                    T v = src[k];
                    ST s = sum[k] + v;
                    SQT sq = sqsum[k] + (SQT)v*v;
                    sum[k] = s; sqsum[k] = sq;
                }
                nzm++;
            }
    }
    return nzm;
415
}
416 417


418 419
static int sqsum8u( const uchar* src, const uchar* mask, int* sum, int* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
420

421 422
static int sqsum8s( const schar* src, const uchar* mask, int* sum, int* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
423

424 425
static int sqsum16u( const ushort* src, const uchar* mask, int* sum, double* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
426

427 428
static int sqsum16s( const short* src, const uchar* mask, int* sum, double* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
429

430 431
static int sqsum32s( const int* src, const uchar* mask, double* sum, double* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
432

433 434
static int sqsum32f( const float* src, const uchar* mask, double* sum, double* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
435

436 437
static int sqsum64f( const double* src, const uchar* mask, double* sum, double* sqsum, int len, int cn )
{ return sumsqr_(src, mask, sum, sqsum, len, cn); }
438

439
typedef int (*SumSqrFunc)(const uchar*, const uchar* mask, uchar*, uchar*, int, int);
440

441
static SumSqrFunc getSumSqrTab(int depth)
442
{
443 444 445 446 447 448 449 450
    static SumSqrFunc sumSqrTab[] =
    {
        (SumSqrFunc)GET_OPTIMIZED(sqsum8u), (SumSqrFunc)sqsum8s, (SumSqrFunc)sqsum16u, (SumSqrFunc)sqsum16s,
        (SumSqrFunc)sqsum32s, (SumSqrFunc)GET_OPTIMIZED(sqsum32f), (SumSqrFunc)sqsum64f, 0
    };

    return sumSqrTab[depth];
}
451

I
Ilya Lavrenov 已提交
452 453
#ifdef HAVE_OPENCL

I
Ilya Lavrenov 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
template <typename T> Scalar ocl_part_sum(Mat m)
{
    CV_Assert(m.rows == 1);

    Scalar s = Scalar::all(0);
    int cn = m.channels();
    const T * const ptr = m.ptr<T>(0);

    for (int x = 0, w = m.cols * cn; x < w; )
        for (int c = 0; c < cn; ++c, ++x)
            s[c] += ptr[x];

    return s;
}

I
Ilya Lavrenov 已提交
469
enum { OCL_OP_SUM = 0, OCL_OP_SUM_ABS =  1, OCL_OP_SUM_SQR = 2 };
I
Ilya Lavrenov 已提交
470

471
static bool ocl_sum( InputArray _src, Scalar & res, int sum_op, InputArray _mask = noArray() )
I
Ilya Lavrenov 已提交
472
{
I
Ilya Lavrenov 已提交
473
    CV_Assert(sum_op == OCL_OP_SUM || sum_op == OCL_OP_SUM_ABS || sum_op == OCL_OP_SUM_SQR);
I
Ilya Lavrenov 已提交
474 475 476 477

    int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
    bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0;

I
Ilya Lavrenov 已提交
478
    if ( (!doubleSupport && depth == CV_64F) || cn > 4 )
I
Ilya Lavrenov 已提交
479 480 481 482 483
        return false;

    int dbsize = ocl::Device::getDefault().maxComputeUnits();
    size_t wgs = ocl::Device::getDefault().maxWorkGroupSize();

484 485
    int ddepth = std::max(sum_op == OCL_OP_SUM_SQR ? CV_32F : CV_32S, depth),
            dtype = CV_MAKE_TYPE(ddepth, cn);
486 487
    bool haveMask = _mask.kind() != _InputArray::NONE;
    CV_Assert(!haveMask || _mask.type() == CV_8UC1);
I
Ilya Lavrenov 已提交
488 489 490 491 492 493 494 495 496

    int wgs2_aligned = 1;
    while (wgs2_aligned < (int)wgs)
        wgs2_aligned <<= 1;
    wgs2_aligned >>= 1;

    static const char * const opMap[3] = { "OP_SUM", "OP_SUM_ABS", "OP_SUM_SQR" };
    char cvt[40];
    ocl::Kernel k("reduce", ocl::core::reduce_oclsrc,
I
Ilya Lavrenov 已提交
497 498 499 500 501
                  format("-D srcT=%s -D srcT1=%s -D dstT=%s -D dstT1=%s -D ddepth=%d -D cn=%d"
                         " -D convertToDT=%s -D %s -D WGS=%d -D WGS2_ALIGNED=%d%s%s",
                         ocl::typeToStr(type), ocl::typeToStr(depth),
                         ocl::typeToStr(dtype), ocl::typeToStr(ddepth), ddepth, cn,
                         ocl::convertTypeStr(depth, ddepth, cn, cvt),
I
Ilya Lavrenov 已提交
502
                         opMap[sum_op], (int)wgs, wgs2_aligned,
503 504
                         doubleSupport ? " -D DOUBLE_SUPPORT" : "",
                         haveMask ? " -D HAVE_MASK" : ""));
I
Ilya Lavrenov 已提交
505 506 507
    if (k.empty())
        return false;

508 509 510 511 512 513 514 515 516 517
    UMat src = _src.getUMat(), db(1, dbsize, dtype), mask = _mask.getUMat();

    ocl::KernelArg srcarg = ocl::KernelArg::ReadOnlyNoSize(src),
            dbarg = ocl::KernelArg::PtrWriteOnly(db),
            maskarg = ocl::KernelArg::ReadOnlyNoSize(mask);

    if (haveMask)
        k.args(srcarg, src.cols, (int)src.total(), dbsize, dbarg, maskarg);
    else
        k.args(srcarg, src.cols, (int)src.total(), dbsize, dbarg);
I
Ilya Lavrenov 已提交
518 519

    size_t globalsize = dbsize * wgs;
520
    if (k.run(1, &globalsize, &wgs, false))
I
Ilya Lavrenov 已提交
521 522 523 524 525 526 527 528 529 530
    {
        typedef Scalar (*part_sum)(Mat m);
        part_sum funcs[3] = { ocl_part_sum<int>, ocl_part_sum<float>, ocl_part_sum<double> },
                func = funcs[ddepth - CV_32S];
        res = func(db.getMat(ACCESS_READ));
        return true;
    }
    return false;
}

I
Ilya Lavrenov 已提交
531 532
#endif

533
}
534

535
cv::Scalar cv::sum( InputArray _src )
536
{
I
Ilya Lavrenov 已提交
537
#ifdef HAVE_OPENCL
I
Ilya Lavrenov 已提交
538
    Scalar _res;
I
Ilya Lavrenov 已提交
539 540 541
    CV_OCL_RUN_(_src.isUMat() && _src.dims() <= 2,
                ocl_sum(_src, _res, OCL_OP_SUM),
                _res)
I
Ilya Lavrenov 已提交
542
#endif
I
Ilya Lavrenov 已提交
543

544 545
    Mat src = _src.getMat();
    int k, cn = src.channels(), depth = src.depth();
546

547
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
R
Roman Donchenko 已提交
548 549 550 551 552 553
    size_t total_size = src.total();
    int rows = src.size[0], cols = (int)(total_size/rows);
    if( src.dims == 2 || (src.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) )
    {
        IppiSize sz = { cols, rows };
        int type = src.type();
554 555 556 557 558 559
        typedef IppStatus (CV_STDCALL* ippiSumFuncHint)(const void*, int, IppiSize, double *, IppHintAlgorithm);
        typedef IppStatus (CV_STDCALL* ippiSumFuncNoHint)(const void*, int, IppiSize, double *);
        ippiSumFuncHint ippFuncHint =
            type == CV_32FC1 ? (ippiSumFuncHint)ippiSum_32f_C1R :
            type == CV_32FC3 ? (ippiSumFuncHint)ippiSum_32f_C3R :
            type == CV_32FC4 ? (ippiSumFuncHint)ippiSum_32f_C4R :
R
Roman Donchenko 已提交
560
            0;
561 562 563 564 565 566 567 568 569 570
        ippiSumFuncNoHint ippFuncNoHint =
            type == CV_8UC1 ? (ippiSumFuncNoHint)ippiSum_8u_C1R :
            type == CV_8UC3 ? (ippiSumFuncNoHint)ippiSum_8u_C3R :
            type == CV_8UC4 ? (ippiSumFuncNoHint)ippiSum_8u_C4R :
            type == CV_16UC1 ? (ippiSumFuncNoHint)ippiSum_16u_C1R :
            type == CV_16UC3 ? (ippiSumFuncNoHint)ippiSum_16u_C3R :
            type == CV_16UC4 ? (ippiSumFuncNoHint)ippiSum_16u_C4R :
            type == CV_16SC1 ? (ippiSumFuncNoHint)ippiSum_16s_C1R :
            type == CV_16SC3 ? (ippiSumFuncNoHint)ippiSum_16s_C3R :
            type == CV_16SC4 ? (ippiSumFuncNoHint)ippiSum_16s_C4R :
571 572 573
            0;
        CV_Assert(!ippFuncHint || !ippFuncNoHint);
        if( ippFuncHint || ippFuncNoHint )
R
Roman Donchenko 已提交
574 575
        {
            Ipp64f res[4];
576 577 578
            IppStatus ret = ippFuncHint ? ippFuncHint(src.data, (int)src.step[0], sz, res, ippAlgHintAccurate) :
                            ippFuncNoHint(src.data, (int)src.step[0], sz, res);
            if( ret >= 0 )
R
Roman Donchenko 已提交
579 580 581 582 583 584 585 586 587 588
            {
                Scalar sc;
                for( int i = 0; i < cn; i++ )
                {
                    sc[i] = res[i];
                }
                return sc;
            }
        }
    }
589 590
#endif

591
    SumFunc func = getSumFunc(depth);
592

593
    CV_Assert( cn <= 4 && func != 0 );
594

595 596 597 598 599 600 601 602 603 604
    const Mat* arrays[] = {&src, 0};
    uchar* ptrs[1];
    NAryMatIterator it(arrays, ptrs);
    Scalar s;
    int total = (int)it.size, blockSize = total, intSumBlockSize = 0;
    int j, count = 0;
    AutoBuffer<int> _buf;
    int* buf = (int*)&s[0];
    size_t esz = 0;
    bool blockSum = depth < CV_32S;
605

606
    if( blockSum )
607
    {
608 609 610 611
        intSumBlockSize = depth <= CV_8S ? (1 << 23) : (1 << 15);
        blockSize = std::min(blockSize, intSumBlockSize);
        _buf.allocate(cn);
        buf = _buf;
612

613 614 615 616
        for( k = 0; k < cn; k++ )
            buf[k] = 0;
        esz = src.elemSize();
    }
617

618 619 620
    for( size_t i = 0; i < it.nplanes; i++, ++it )
    {
        for( j = 0; j < total; j += blockSize )
621
        {
622 623 624 625 626 627 628 629 630 631 632 633 634
            int bsz = std::min(total - j, blockSize);
            func( ptrs[0], 0, (uchar*)buf, bsz, cn );
            count += bsz;
            if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) )
            {
                for( k = 0; k < cn; k++ )
                {
                    s[k] += buf[k];
                    buf[k] = 0;
                }
                count = 0;
            }
            ptrs[0] += bsz*esz;
635 636
        }
    }
637
    return s;
638 639
}

I
Ilya Lavrenov 已提交
640 641
#ifdef HAVE_OPENCL

I
Ilya Lavrenov 已提交
642 643 644 645
namespace cv {

static bool ocl_countNonZero( InputArray _src, int & res )
{
I
Ilya Lavrenov 已提交
646
    int type = _src.type(), depth = CV_MAT_DEPTH(type);
I
Ilya Lavrenov 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659
    bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0;

    if (depth == CV_64F && !doubleSupport)
        return false;

    int dbsize = ocl::Device::getDefault().maxComputeUnits();
    size_t wgs = ocl::Device::getDefault().maxWorkGroupSize();

    int wgs2_aligned = 1;
    while (wgs2_aligned < (int)wgs)
        wgs2_aligned <<= 1;
    wgs2_aligned >>= 1;

I
Ilya Lavrenov 已提交
660 661
    ocl::Kernel k("reduce", ocl::core::reduce_oclsrc,
                  format("-D srcT=%s -D OP_COUNT_NON_ZERO -D WGS=%d -D WGS2_ALIGNED=%d%s",
I
Ilya Lavrenov 已提交
662
                         ocl::typeToStr(type), (int)wgs,
I
Ilya Lavrenov 已提交
663
                         wgs2_aligned, doubleSupport ? " -D DOUBLE_SUPPORT" : ""));
I
Ilya Lavrenov 已提交
664 665 666 667
    if (k.empty())
        return false;

    UMat src = _src.getUMat(), db(1, dbsize, CV_32SC1);
I
Ilya Lavrenov 已提交
668 669 670 671 672
    k.args(ocl::KernelArg::ReadOnlyNoSize(src), src.cols, (int)src.total(),
           dbsize, ocl::KernelArg::PtrWriteOnly(db));

    size_t globalsize = dbsize * wgs;
    if (k.run(1, &globalsize, &wgs, true))
673
        return res = saturate_cast<int>(cv::sum(db.getMat(ACCESS_READ))[0]), true;
I
Ilya Lavrenov 已提交
674 675 676 677 678
    return false;
}

}

I
Ilya Lavrenov 已提交
679 680
#endif

681
int cv::countNonZero( InputArray _src )
682
{
I
Ilya Lavrenov 已提交
683 684
    CV_Assert( _src.channels() == 1 );

I
Ilya Lavrenov 已提交
685
#ifdef HAVE_OPENCL
I
Ilya Lavrenov 已提交
686
    int res = -1;
687 688 689
    CV_OCL_RUN_(_src.isUMat() && _src.dims() <= 2,
                ocl_countNonZero(_src, res),
                res)
I
Ilya Lavrenov 已提交
690
#endif
I
Ilya Lavrenov 已提交
691

692
    Mat src = _src.getMat();
693
    CountNonZeroFunc func = getCountNonZeroTab(src.depth());
694

I
Ilya Lavrenov 已提交
695
    CV_Assert( func != 0 );
696

697 698 699 700
    const Mat* arrays[] = {&src, 0};
    uchar* ptrs[1];
    NAryMatIterator it(arrays, ptrs);
    int total = (int)it.size, nz = 0;
701

702 703
    for( size_t i = 0; i < it.nplanes; i++, ++it )
        nz += func( ptrs[0], total );
704

705
    return nz;
706
}
707

708
cv::Scalar cv::mean( InputArray _src, InputArray _mask )
709
{
710
    Mat src = _src.getMat(), mask = _mask.getMat();
711
    CV_Assert( mask.empty() || mask.type() == CV_8U );
712

713
    int k, cn = src.channels(), depth = src.depth();
714

K
kdrobnyh 已提交
715
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
R
Roman Donchenko 已提交
716 717 718 719 720 721 722 723
    size_t total_size = src.total();
    int rows = src.size[0], cols = (int)(total_size/rows);
    if( src.dims == 2 || (src.isContinuous() && mask.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) )
    {
        IppiSize sz = { cols, rows };
        int type = src.type();
        if( !mask.empty() )
        {
724 725 726 727 728
            typedef IppStatus (CV_STDCALL* ippiMaskMeanFuncC1)(const void *, int, void *, int, IppiSize, Ipp64f *);
            ippiMaskMeanFuncC1 ippFuncC1 =
            type == CV_8UC1 ? (ippiMaskMeanFuncC1)ippiMean_8u_C1MR :
            type == CV_16UC1 ? (ippiMaskMeanFuncC1)ippiMean_16u_C1MR :
            type == CV_32FC1 ? (ippiMaskMeanFuncC1)ippiMean_32f_C1MR :
R
Roman Donchenko 已提交
729 730 731 732
            0;
            if( ippFuncC1 )
            {
                Ipp64f res;
I
Ilya Lavrenov 已提交
733
                if( ippFuncC1(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, &res) >= 0 )
R
Roman Donchenko 已提交
734 735 736 737
                {
                    return Scalar(res);
                }
            }
738 739 740 741 742
            typedef IppStatus (CV_STDCALL* ippiMaskMeanFuncC3)(const void *, int, void *, int, IppiSize, int, Ipp64f *);
            ippiMaskMeanFuncC3 ippFuncC3 =
            type == CV_8UC3 ? (ippiMaskMeanFuncC3)ippiMean_8u_C3CMR :
            type == CV_16UC3 ? (ippiMaskMeanFuncC3)ippiMean_16u_C3CMR :
            type == CV_32FC3 ? (ippiMaskMeanFuncC3)ippiMean_32f_C3CMR :
R
Roman Donchenko 已提交
743 744 745 746
            0;
            if( ippFuncC3 )
            {
                Ipp64f res1, res2, res3;
I
Ilya Lavrenov 已提交
747 748 749
                if( ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 1, &res1) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 2, &res2) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 3, &res3) >= 0 )
R
Roman Donchenko 已提交
750 751 752 753 754 755 756
                {
                    return Scalar(res1, res2, res3);
                }
            }
        }
        else
        {
757 758 759 760 761 762
            typedef IppStatus (CV_STDCALL* ippiMeanFuncHint)(const void*, int, IppiSize, double *, IppHintAlgorithm);
            typedef IppStatus (CV_STDCALL* ippiMeanFuncNoHint)(const void*, int, IppiSize, double *);
            ippiMeanFuncHint ippFuncHint =
                type == CV_32FC1 ? (ippiMeanFuncHint)ippiMean_32f_C1R :
                type == CV_32FC3 ? (ippiMeanFuncHint)ippiMean_32f_C3R :
                type == CV_32FC4 ? (ippiMeanFuncHint)ippiMean_32f_C4R :
763
                0;
764 765 766 767 768 769 770 771 772 773
            ippiMeanFuncNoHint ippFuncNoHint =
                type == CV_8UC1 ? (ippiMeanFuncNoHint)ippiMean_8u_C1R :
                type == CV_8UC3 ? (ippiMeanFuncNoHint)ippiMean_8u_C3R :
                type == CV_8UC4 ? (ippiMeanFuncNoHint)ippiMean_8u_C4R :
                type == CV_16UC1 ? (ippiMeanFuncNoHint)ippiMean_16u_C1R :
                type == CV_16UC3 ? (ippiMeanFuncNoHint)ippiMean_16u_C3R :
                type == CV_16UC4 ? (ippiMeanFuncNoHint)ippiMean_16u_C4R :
                type == CV_16SC1 ? (ippiMeanFuncNoHint)ippiMean_16s_C1R :
                type == CV_16SC3 ? (ippiMeanFuncNoHint)ippiMean_16s_C3R :
                type == CV_16SC4 ? (ippiMeanFuncNoHint)ippiMean_16s_C4R :
R
Roman Donchenko 已提交
774
                0;
775 776 777
            // Make sure only zero or one version of the function pointer is valid
            CV_Assert(!ippFuncHint || !ippFuncNoHint);
            if( ippFuncHint || ippFuncNoHint )
R
Roman Donchenko 已提交
778 779
            {
                Ipp64f res[4];
780 781 782
                IppStatus ret = ippFuncHint ? ippFuncHint(src.data, (int)src.step[0], sz, res, ippAlgHintAccurate) :
                                ippFuncNoHint(src.data, (int)src.step[0], sz, res);
                if( ret >= 0 )
R
Roman Donchenko 已提交
783 784 785 786 787 788 789 790 791 792 793
                {
                    Scalar sc;
                    for( int i = 0; i < cn; i++ )
                    {
                        sc[i] = res[i];
                    }
                    return sc;
                }
            }
        }
    }
K
kdrobnyh 已提交
794
#endif
795

796
    SumFunc func = getSumFunc(depth);
797

798
    CV_Assert( cn <= 4 && func != 0 );
799

800 801 802 803 804 805 806 807 808 809
    const Mat* arrays[] = {&src, &mask, 0};
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs);
    Scalar s;
    int total = (int)it.size, blockSize = total, intSumBlockSize = 0;
    int j, count = 0;
    AutoBuffer<int> _buf;
    int* buf = (int*)&s[0];
    bool blockSum = depth <= CV_16S;
    size_t esz = 0, nz0 = 0;
810

811 812 813 814 815 816
    if( blockSum )
    {
        intSumBlockSize = depth <= CV_8S ? (1 << 23) : (1 << 15);
        blockSize = std::min(blockSize, intSumBlockSize);
        _buf.allocate(cn);
        buf = _buf;
817

818 819 820 821
        for( k = 0; k < cn; k++ )
            buf[k] = 0;
        esz = src.elemSize();
    }
822

823
    for( size_t i = 0; i < it.nplanes; i++, ++it )
824
    {
825 826 827 828 829 830 831
        for( j = 0; j < total; j += blockSize )
        {
            int bsz = std::min(total - j, blockSize);
            int nz = func( ptrs[0], ptrs[1], (uchar*)buf, bsz, cn );
            count += nz;
            nz0 += nz;
            if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) )
832
            {
833 834 835 836 837 838
                for( k = 0; k < cn; k++ )
                {
                    s[k] += buf[k];
                    buf[k] = 0;
                }
                count = 0;
839
            }
840 841 842 843
            ptrs[0] += bsz*esz;
            if( ptrs[1] )
                ptrs[1] += bsz;
        }
844
    }
845
    return s*(nz0 ? 1./nz0 : 0);
846
}
847

I
Ilya Lavrenov 已提交
848 849
#ifdef HAVE_OPENCL

I
Ilya Lavrenov 已提交
850 851
namespace cv {

852
static bool ocl_meanStdDev( InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray _mask )
I
Ilya Lavrenov 已提交
853
{
854 855
    bool haveMask = _mask.kind() != _InputArray::NONE;

I
Ilya Lavrenov 已提交
856
    Scalar mean, stddev;
857
    if (!ocl_sum(_src, mean, OCL_OP_SUM, _mask))
I
Ilya Lavrenov 已提交
858
        return false;
859
    if (!ocl_sum(_src, stddev, OCL_OP_SUM_SQR, _mask))
I
Ilya Lavrenov 已提交
860 861
        return false;

I
Ilya Lavrenov 已提交
862 863
    int nz = haveMask ? countNonZero(_mask) : (int)_src.total();
    double total = nz != 0 ? 1.0 / nz : 0;
I
Ilya Lavrenov 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    int k, j, cn = _src.channels();
    for (int i = 0; i < cn; ++i)
    {
        mean[i] *= total;
        stddev[i] = std::sqrt(std::max(stddev[i] * total - mean[i] * mean[i] , 0.));
    }

    for( j = 0; j < 2; j++ )
    {
        const double * const sptr = j == 0 ? &mean[0] : &stddev[0];
        _OutputArray _dst = j == 0 ? _mean : _sdv;
        if( !_dst.needed() )
            continue;

        if( !_dst.fixedSize() )
            _dst.create(cn, 1, CV_64F, -1, true);
        Mat dst = _dst.getMat();
        int dcn = (int)dst.total();
        CV_Assert( dst.type() == CV_64F && dst.isContinuous() &&
                   (dst.cols == 1 || dst.rows == 1) && dcn >= cn );
        double* dptr = dst.ptr<double>();
        for( k = 0; k < cn; k++ )
            dptr[k] = sptr[k];
        for( ; k < dcn; k++ )
            dptr[k] = 0;
    }

    return true;
}

}
895

I
Ilya Lavrenov 已提交
896 897
#endif

898
void cv::meanStdDev( InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray _mask )
899
{
I
Ilya Lavrenov 已提交
900 901
    CV_OCL_RUN(_src.isUMat() && _src.dims() <= 2,
               ocl_meanStdDev(_src, _mean, _sdv, _mask))
I
Ilya Lavrenov 已提交
902

903
    Mat src = _src.getMat(), mask = _mask.getMat();
904
    CV_Assert( mask.empty() || mask.type() == CV_8U );
905

906
    int k, cn = src.channels(), depth = src.depth();
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943

#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
    size_t total_size = src.total();
    int rows = src.size[0], cols = (int)(total_size/rows);
    if( src.dims == 2 || (src.isContinuous() && mask.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) )
    {
        Ipp64f mean_temp[3];
        Ipp64f stddev_temp[3];
        Ipp64f *pmean = &mean_temp[0];
        Ipp64f *pstddev = &stddev_temp[0];
        Mat mean, stddev;
        int dcn_mean = -1;
        if( _mean.needed() )
        {
            if( !_mean.fixedSize() )
                _mean.create(cn, 1, CV_64F, -1, true);
            mean = _mean.getMat();
            dcn_mean = (int)mean.total();
            pmean = (Ipp64f *)mean.data;
        }
        int dcn_stddev = -1;
        if( _sdv.needed() )
        {
            if( !_sdv.fixedSize() )
                _sdv.create(cn, 1, CV_64F, -1, true);
            stddev = _sdv.getMat();
            dcn_stddev = (int)stddev.total();
            pstddev = (Ipp64f *)stddev.data;
        }
        for( int k = cn; k < dcn_mean; k++ )
            pmean[k] = 0;
        for( int k = cn; k < dcn_stddev; k++ )
            pstddev[k] = 0;
        IppiSize sz = { cols, rows };
        int type = src.type();
        if( !mask.empty() )
        {
944 945 946 947 948
            typedef IppStatus (CV_STDCALL* ippiMaskMeanStdDevFuncC1)(const void *, int, void *, int, IppiSize, Ipp64f *, Ipp64f *);
            ippiMaskMeanStdDevFuncC1 ippFuncC1 =
            type == CV_8UC1 ? (ippiMaskMeanStdDevFuncC1)ippiMean_StdDev_8u_C1MR :
            type == CV_16UC1 ? (ippiMaskMeanStdDevFuncC1)ippiMean_StdDev_16u_C1MR :
            type == CV_32FC1 ? (ippiMaskMeanStdDevFuncC1)ippiMean_StdDev_32f_C1MR :
949 950 951 952 953 954
            0;
            if( ippFuncC1 )
            {
                if( ippFuncC1(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, pmean, pstddev) >= 0 )
                    return;
            }
955 956 957 958 959
            typedef IppStatus (CV_STDCALL* ippiMaskMeanStdDevFuncC3)(const void *, int, void *, int, IppiSize, int, Ipp64f *, Ipp64f *);
            ippiMaskMeanStdDevFuncC3 ippFuncC3 =
            type == CV_8UC3 ? (ippiMaskMeanStdDevFuncC3)ippiMean_StdDev_8u_C3CMR :
            type == CV_16UC3 ? (ippiMaskMeanStdDevFuncC3)ippiMean_StdDev_16u_C3CMR :
            type == CV_32FC3 ? (ippiMaskMeanStdDevFuncC3)ippiMean_StdDev_32f_C3CMR :
960 961 962 963 964 965 966 967 968 969 970
            0;
            if( ippFuncC3 )
            {
                if( ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 1, &pmean[0], &pstddev[0]) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 2, &pmean[1], &pstddev[1]) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 3, &pmean[2], &pstddev[2]) >= 0 )
                    return;
            }
        }
        else
        {
971 972 973 974
            typedef IppStatus (CV_STDCALL* ippiMeanStdDevFuncC1)(const void *, int, IppiSize, Ipp64f *, Ipp64f *);
            ippiMeanStdDevFuncC1 ippFuncC1 =
            type == CV_8UC1 ? (ippiMeanStdDevFuncC1)ippiMean_StdDev_8u_C1R :
            type == CV_16UC1 ? (ippiMeanStdDevFuncC1)ippiMean_StdDev_16u_C1R :
975
#if ((IPP_VERSION_MAJOR >= 8) && (IPP_VERSION_MINOR >= 1)) || (IPP_VERSION_MAJOR > 8)
976
            type == CV_32FC1 ? (ippiMeanStdDevFuncC1)ippiMean_StdDev_32f_C1R ://Aug 2013: bug in IPP 7.1, 8.0
977
#endif
978 979 980 981 982 983
            0;
            if( ippFuncC1 )
            {
                if( ippFuncC1(src.data, (int)src.step[0], sz, pmean, pstddev) >= 0 )
                    return;
            }
984 985 986 987 988
            typedef IppStatus (CV_STDCALL* ippiMeanStdDevFuncC3)(const void *, int, IppiSize, int, Ipp64f *, Ipp64f *);
            ippiMeanStdDevFuncC3 ippFuncC3 =
            type == CV_8UC3 ? (ippiMeanStdDevFuncC3)ippiMean_StdDev_8u_C3CR :
            type == CV_16UC3 ? (ippiMeanStdDevFuncC3)ippiMean_StdDev_16u_C3CR :
            type == CV_32FC3 ? (ippiMeanStdDevFuncC3)ippiMean_StdDev_32f_C3CR :
989 990 991 992 993 994 995 996 997 998 999 1000 1001
            0;
            if( ippFuncC3 )
            {
                if( ippFuncC3(src.data, (int)src.step[0], sz, 1, &pmean[0], &pstddev[0]) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], sz, 2, &pmean[1], &pstddev[1]) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], sz, 3, &pmean[2], &pstddev[2]) >= 0 )
                    return;
            }
        }
    }
#endif


1002
    SumSqrFunc func = getSumSqrTab(depth);
1003

1004
    CV_Assert( func != 0 );
1005

1006 1007 1008
    const Mat* arrays[] = {&src, &mask, 0};
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs);
1009
    int total = (int)it.size, blockSize = total, intSumBlockSize = 0;
1010 1011 1012 1013 1014 1015
    int j, count = 0, nz0 = 0;
    AutoBuffer<double> _buf(cn*4);
    double *s = (double*)_buf, *sq = s + cn;
    int *sbuf = (int*)s, *sqbuf = (int*)sq;
    bool blockSum = depth <= CV_16S, blockSqSum = depth <= CV_8S;
    size_t esz = 0;
1016

1017 1018
    for( k = 0; k < cn; k++ )
        s[k] = sq[k] = 0;
1019

1020
    if( blockSum )
1021
    {
1022 1023 1024 1025 1026 1027 1028 1029 1030
        intSumBlockSize = 1 << 15;
        blockSize = std::min(blockSize, intSumBlockSize);
        sbuf = (int*)(sq + cn);
        if( blockSqSum )
            sqbuf = sbuf + cn;
        for( k = 0; k < cn; k++ )
            sbuf[k] = sqbuf[k] = 0;
        esz = src.elemSize();
    }
1031

1032
    for( size_t i = 0; i < it.nplanes; i++, ++it )
1033
    {
1034
        for( j = 0; j < total; j += blockSize )
V
Vadim Pisarevsky 已提交
1035
        {
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
            int bsz = std::min(total - j, blockSize);
            int nz = func( ptrs[0], ptrs[1], (uchar*)sbuf, (uchar*)sqbuf, bsz, cn );
            count += nz;
            nz0 += nz;
            if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) )
            {
                for( k = 0; k < cn; k++ )
                {
                    s[k] += sbuf[k];
                    sbuf[k] = 0;
                }
                if( blockSqSum )
                {
                    for( k = 0; k < cn; k++ )
                    {
                        sq[k] += sqbuf[k];
                        sqbuf[k] = 0;
                    }
                }
                count = 0;
            }
            ptrs[0] += bsz*esz;
            if( ptrs[1] )
                ptrs[1] += bsz;
V
Vadim Pisarevsky 已提交
1060
        }
1061
    }
1062

1063
    double scale = nz0 ? 1./nz0 : 0.;
1064
    for( k = 0; k < cn; k++ )
1065
    {
1066 1067
        s[k] *= scale;
        sq[k] = std::sqrt(std::max(sq[k]*scale - s[k]*s[k], 0.));
1068
    }
1069

1070
    for( j = 0; j < 2; j++ )
1071
    {
1072
        const double* sptr = j == 0 ? s : sq;
1073
        _OutputArray _dst = j == 0 ? _mean : _sdv;
1074 1075 1076 1077 1078 1079 1080 1081
        if( !_dst.needed() )
            continue;

        if( !_dst.fixedSize() )
            _dst.create(cn, 1, CV_64F, -1, true);
        Mat dst = _dst.getMat();
        int dcn = (int)dst.total();
        CV_Assert( dst.type() == CV_64F && dst.isContinuous() &&
1082
                   (dst.cols == 1 || dst.rows == 1) && dcn >= cn );
1083 1084 1085 1086 1087
        double* dptr = dst.ptr<double>();
        for( k = 0; k < cn; k++ )
            dptr[k] = sptr[k];
        for( ; k < dcn; k++ )
            dptr[k] = 0;
1088 1089 1090 1091 1092 1093 1094
    }
}

/****************************************************************************************\
*                                       minMaxLoc                                        *
\****************************************************************************************/

1095 1096 1097
namespace cv
{

1098
template<typename T, typename WT> static void
1099 1100
minMaxIdx_( const T* src, const uchar* mask, WT* _minVal, WT* _maxVal,
            size_t* _minIdx, size_t* _maxIdx, int len, size_t startIdx )
1101
{
1102
    WT minVal = *_minVal, maxVal = *_maxVal;
1103
    size_t minIdx = *_minIdx, maxIdx = *_maxIdx;
1104

1105
    if( !mask )
1106
    {
1107
        for( int i = 0; i < len; i++ )
1108
        {
1109
            T val = src[i];
1110
            if( val < minVal )
1111
            {
1112
                minVal = val;
1113
                minIdx = startIdx + i;
1114
            }
1115
            if( val > maxVal )
1116
            {
1117
                maxVal = val;
1118
                maxIdx = startIdx + i;
1119 1120 1121
            }
        }
    }
1122
    else
1123
    {
1124
        for( int i = 0; i < len; i++ )
1125
        {
1126 1127
            T val = src[i];
            if( mask[i] && val < minVal )
1128
            {
1129
                minVal = val;
1130
                minIdx = startIdx + i;
1131
            }
1132
            if( mask[i] && val > maxVal )
1133
            {
1134
                maxVal = val;
1135
                maxIdx = startIdx + i;
1136 1137 1138 1139
            }
        }
    }

1140 1141 1142 1143
    *_minIdx = minIdx;
    *_maxIdx = maxIdx;
    *_minVal = minVal;
    *_maxVal = maxVal;
1144 1145
}

1146 1147 1148
static void minMaxIdx_8u(const uchar* src, const uchar* mask, int* minval, int* maxval,
                         size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1149

1150 1151 1152
static void minMaxIdx_8s(const schar* src, const uchar* mask, int* minval, int* maxval,
                         size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1153

1154 1155 1156
static void minMaxIdx_16u(const ushort* src, const uchar* mask, int* minval, int* maxval,
                          size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1157

1158 1159 1160
static void minMaxIdx_16s(const short* src, const uchar* mask, int* minval, int* maxval,
                          size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1161

1162 1163 1164
static void minMaxIdx_32s(const int* src, const uchar* mask, int* minval, int* maxval,
                          size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1165

1166 1167 1168
static void minMaxIdx_32f(const float* src, const uchar* mask, float* minval, float* maxval,
                          size_t* minidx, size_t* maxidx, int len, size_t startidx )
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1169

1170 1171
static void minMaxIdx_64f(const double* src, const uchar* mask, double* minval, double* maxval,
                          size_t* minidx, size_t* maxidx, int len, size_t startidx )
1172
{ minMaxIdx_(src, mask, minval, maxval, minidx, maxidx, len, startidx ); }
1173

1174
typedef void (*MinMaxIdxFunc)(const uchar*, const uchar*, int*, int*, size_t*, size_t*, int, size_t);
1175

1176
static MinMaxIdxFunc getMinmaxTab(int depth)
1177
{
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    static MinMaxIdxFunc minmaxTab[] =
    {
        (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_8u), (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_8s),
        (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_16u), (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_16s),
        (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_32s),
        (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_32f), (MinMaxIdxFunc)GET_OPTIMIZED(minMaxIdx_64f),
        0
    };

    return minmaxTab[depth];
}
1189

V
Vadim Pisarevsky 已提交
1190 1191 1192
static void ofs2idx(const Mat& a, size_t ofs, int* idx)
{
    int i, d = a.dims;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    if( ofs > 0 )
    {
        ofs--;
        for( i = d-1; i >= 0; i-- )
        {
            int sz = a.size[i];
            idx[i] = (int)(ofs % sz);
            ofs /= sz;
        }
    }
    else
V
Vadim Pisarevsky 已提交
1204
    {
1205 1206
        for( i = d-1; i >= 0; i-- )
            idx[i] = -1;
V
Vadim Pisarevsky 已提交
1207 1208
    }
}
1209

I
Ilya Lavrenov 已提交
1210
#ifdef HAVE_OPENCL
K
Konstantin Matskevich 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

template <typename T>
void getMinMaxRes(const Mat &minv, const Mat &maxv, const Mat &minl, const Mat &maxl, double* minVal,
                  double* maxVal, int* minLoc, int* maxLoc, const int groupnum, const int cn, const int cols)
{
    T min = std::numeric_limits<T>::max();
    T max = std::numeric_limits<T>::min() > 0 ? -std::numeric_limits<T>::max() : std::numeric_limits<T>::min();
    int minloc = INT_MAX, maxloc = INT_MAX;
    for( int i = 0; i < groupnum; i++)
    {
        T current_min = minv.at<T>(0,i);
        T current_max = maxv.at<T>(0,i);
        T oldmin = min, oldmax = max;
        min = std::min(min, current_min);
        max = std::max(max, current_max);
        if (cn == 1)
        {
            int current_minloc = minl.at<int>(0,i);
            int current_maxloc = maxl.at<int>(0,i);
K
Konstantin Matskevich 已提交
1230
            if(current_minloc < 0 || current_maxloc < 0) continue;
K
Konstantin Matskevich 已提交
1231 1232 1233 1234
            minloc = (oldmin == current_min) ? std::min(minloc, current_minloc) : (oldmin < current_min) ? minloc : current_minloc;
            maxloc = (oldmax == current_max) ? std::min(maxloc, current_maxloc) : (oldmax > current_max) ? maxloc : current_maxloc;
        }
    }
K
Konstantin Matskevich 已提交
1235
    bool zero_mask = (maxloc == INT_MAX) || (minloc == INT_MAX);
K
Konstantin Matskevich 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
    if(minVal)
        *minVal = zero_mask ? 0 : (double)min;
    if(maxVal)
        *maxVal = zero_mask ? 0 : (double)max;
    if(minLoc)
    {
        minLoc[0] = zero_mask ? -1 : minloc/cols;
        minLoc[1] = zero_mask ? -1 : minloc%cols;
    }
    if(maxLoc)
    {
        maxLoc[0] = zero_mask ? -1 : maxloc/cols;
        maxLoc[1] = zero_mask ? -1 : maxloc%cols;
    }
}

typedef void (*getMinMaxResFunc)(const Mat &minv, const Mat &maxv, const Mat &minl, const Mat &maxl, double *minVal,
                                 double *maxVal, int *minLoc, int *maxLoc, const int gropunum, const int cn, const int cols);

static bool ocl_minMaxIdx( InputArray _src, double* minVal, double* maxVal, int* minLoc, int* maxLoc, InputArray _mask)
{
    CV_Assert( (_src.channels() == 1 && (_mask.empty() || _mask.type() == CV_8U)) ||
        (_src.channels() >= 1 && _mask.empty() && !minLoc && !maxLoc) );

    int type = _src.type(), depth = CV_MAT_DEPTH(type);
    bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0;

    if (depth == CV_64F && !doubleSupport)
        return false;

    int groupnum = ocl::Device::getDefault().maxComputeUnits();
    size_t wgs = ocl::Device::getDefault().maxWorkGroupSize();

    int wgs2_aligned = 1;
    while (wgs2_aligned < (int)wgs)
        wgs2_aligned <<= 1;
    wgs2_aligned >>= 1;

1274 1275
    String opts = format("-D DEPTH_%d -D OP_MIN_MAX_LOC%s -D WGS=%d -D WGS2_ALIGNED=%d%s",
        depth, _mask.empty() ? "" : "_MASK", (int)wgs, wgs2_aligned, doubleSupport ? " -D DOUBLE_SUPPORT" : "");
K
Konstantin Matskevich 已提交
1276 1277 1278 1279 1280 1281 1282 1283

    ocl::Kernel k("reduce", ocl::core::reduce_oclsrc, opts);
    if (k.empty())
        return false;

    UMat src = _src.getUMat(), minval(1, groupnum, src.type()),
        maxval(1, groupnum, src.type()), minloc( 1, groupnum, CV_32SC1),
        maxloc( 1, groupnum, CV_32SC1), mask;
1284
    if (!_mask.empty())
K
Konstantin Matskevich 已提交
1285 1286
        mask = _mask.getUMat();

1287
    if (src.channels() > 1)
K
Konstantin Matskevich 已提交
1288 1289
        src = src.reshape(1);

1290
    if (mask.empty())
K
Konstantin Matskevich 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299
        k.args(ocl::KernelArg::ReadOnlyNoSize(src), src.cols, (int)src.total(),
            groupnum, ocl::KernelArg::PtrWriteOnly(minval), ocl::KernelArg::PtrWriteOnly(maxval),
            ocl::KernelArg::PtrWriteOnly(minloc), ocl::KernelArg::PtrWriteOnly(maxloc));
    else
        k.args(ocl::KernelArg::ReadOnlyNoSize(src), src.cols, (int)src.total(), groupnum,
            ocl::KernelArg::PtrWriteOnly(minval), ocl::KernelArg::PtrWriteOnly(maxval),
            ocl::KernelArg::PtrWriteOnly(minloc), ocl::KernelArg::PtrWriteOnly(maxloc), ocl::KernelArg::ReadOnlyNoSize(mask));

    size_t globalsize = groupnum * wgs;
I
Ilya Lavrenov 已提交
1300
    if (!k.run(1, &globalsize, &wgs, false))
K
Konstantin Matskevich 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        return false;

    Mat minv = minval.getMat(ACCESS_READ), maxv = maxval.getMat(ACCESS_READ),
        minl = minloc.getMat(ACCESS_READ), maxl = maxloc.getMat(ACCESS_READ);

    static getMinMaxResFunc functab[7] =
    {
        getMinMaxRes<uchar>,
        getMinMaxRes<char>,
        getMinMaxRes<ushort>,
        getMinMaxRes<short>,
        getMinMaxRes<int>,
        getMinMaxRes<float>,
        getMinMaxRes<double>
    };

    getMinMaxResFunc func;

    func = functab[depth];
    func(minv, maxv, minl, maxl, minVal, maxVal, minLoc, maxLoc, groupnum, src.channels(), src.cols);

    return true;
}
I
Ilya Lavrenov 已提交
1324 1325 1326

#endif

K
Konstantin Matskevich 已提交
1327 1328
}

1329
void cv::minMaxIdx(InputArray _src, double* minVal,
1330
                   double* maxVal, int* minIdx, int* maxIdx,
1331
                   InputArray _mask)
V
Vadim Pisarevsky 已提交
1332
{
K
Konstantin Matskevich 已提交
1333 1334 1335
    CV_Assert( (_src.channels() == 1 && (_mask.empty() || _mask.type() == CV_8U)) ||
        (_src.channels() >= 1 && _mask.empty() && !minIdx && !maxIdx) );

I
Ilya Lavrenov 已提交
1336 1337
    CV_OCL_RUN(_src.isUMat() && _src.dims() <= 2  && (_mask.empty() || _src.size() == _mask.size()),
               ocl_minMaxIdx(_src, minVal, maxVal, minIdx, maxIdx, _mask))
K
Konstantin Matskevich 已提交
1338

1339
    Mat src = _src.getMat(), mask = _mask.getMat();
1340
    int depth = src.depth(), cn = src.channels();
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
    size_t total_size = src.total();
    int rows = src.size[0], cols = (int)(total_size/rows);
    if( cn == 1 && ( src.dims == 2 || (src.isContinuous() && mask.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) ) )
    {
        IppiSize sz = { cols, rows };
        int type = src.type();
        if( !mask.empty() )
        {
1351 1352 1353 1354 1355
            typedef IppStatus (CV_STDCALL* ippiMaskMinMaxIndxFuncC1)(const void *, int, const void *, int, IppiSize, Ipp32f *, Ipp32f *, IppiPoint *, IppiPoint *);
            ippiMaskMinMaxIndxFuncC1 ippFuncC1 =
            type == CV_8UC1 ? (ippiMaskMinMaxIndxFuncC1)ippiMinMaxIndx_8u_C1MR :
            type == CV_16UC1 ? (ippiMaskMinMaxIndxFuncC1)ippiMinMaxIndx_16u_C1MR :
            type == CV_32FC1 ? (ippiMaskMinMaxIndxFuncC1)ippiMinMaxIndx_32f_C1MR :
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
            0;
            if( ippFuncC1 )
            {
                Ipp32f min, max;
                IppiPoint minp, maxp;
                if( ippFuncC1(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, &min, &max, &minp, &maxp) >= 0 )
                {
                    if( minVal )
                        *minVal = (double)min;
                    if( maxVal )
                        *maxVal = (double)max;
                    if( !minp.x && !minp.y && !maxp.x && !maxp.y && !mask.data[0] )
                        minp.x = maxp.x = -1;
                    if( minIdx )
                    {
                        size_t minidx = minp.y * cols + minp.x + 1;
                        ofs2idx(src, minidx, minIdx);
                    }
                    if( maxIdx )
                    {
                        size_t maxidx = maxp.y * cols + maxp.x + 1;
                        ofs2idx(src, maxidx, maxIdx);
                    }
                    return;
                }
            }
        }
        else
        {
1385 1386 1387 1388 1389
            typedef IppStatus (CV_STDCALL* ippiMinMaxIndxFuncC1)(const void *, int, IppiSize, Ipp32f *, Ipp32f *, IppiPoint *, IppiPoint *);
            ippiMinMaxIndxFuncC1 ippFuncC1 =
                type == CV_8UC1 ? (ippiMinMaxIndxFuncC1)ippiMinMaxIndx_8u_C1R :
                type == CV_16UC1 ? (ippiMinMaxIndxFuncC1)ippiMinMaxIndx_16u_C1R :
                type == CV_32FC1 ? (ippiMinMaxIndxFuncC1)ippiMinMaxIndx_32f_C1R :
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
                0;
            if( ippFuncC1 )
            {
                Ipp32f min, max;
                IppiPoint minp, maxp;
                if( ippFuncC1(src.data, (int)src.step[0], sz, &min, &max, &minp, &maxp) >= 0 )
                {
                    if( minVal )
                        *minVal = (double)min;
                    if( maxVal )
                        *maxVal = (double)max;
                    if( minIdx )
                    {
                        size_t minidx = minp.y * cols + minp.x + 1;
                        ofs2idx(src, minidx, minIdx);
                    }
                    if( maxIdx )
                    {
                        size_t maxidx = maxp.y * cols + maxp.x + 1;
                        ofs2idx(src, maxidx, maxIdx);
                    }
                    return;
                }
            }
        }
    }
#endif

1418
    MinMaxIdxFunc func = getMinmaxTab(depth);
1419
    CV_Assert( func != 0 );
1420

1421 1422 1423
    const Mat* arrays[] = {&src, &mask, 0};
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs);
1424

1425
    size_t minidx = 0, maxidx = 0;
1426 1427 1428 1429 1430
    int iminval = INT_MAX, imaxval = INT_MIN;
    float fminval = FLT_MAX, fmaxval = -FLT_MAX;
    double dminval = DBL_MAX, dmaxval = -DBL_MAX;
    size_t startidx = 1;
    int *minval = &iminval, *maxval = &imaxval;
1431
    int planeSize = (int)it.size*cn;
1432

1433 1434 1435 1436
    if( depth == CV_32F )
        minval = (int*)&fminval, maxval = (int*)&fmaxval;
    else if( depth == CV_64F )
        minval = (int*)&dminval, maxval = (int*)&dmaxval;
1437

1438 1439
    for( size_t i = 0; i < it.nplanes; i++, ++it, startidx += planeSize )
        func( ptrs[0], ptrs[1], minval, maxval, &minidx, &maxidx, planeSize, startidx );
1440

1441
    if( minidx == 0 )
1442 1443 1444 1445 1446
        dminval = dmaxval = 0;
    else if( depth == CV_32F )
        dminval = fminval, dmaxval = fmaxval;
    else if( depth <= CV_32S )
        dminval = iminval, dmaxval = imaxval;
1447

V
Vadim Pisarevsky 已提交
1448
    if( minVal )
1449
        *minVal = dminval;
V
Vadim Pisarevsky 已提交
1450
    if( maxVal )
1451
        *maxVal = dmaxval;
1452

V
Vadim Pisarevsky 已提交
1453
    if( minIdx )
1454
        ofs2idx(src, minidx, minIdx);
V
Vadim Pisarevsky 已提交
1455
    if( maxIdx )
1456
        ofs2idx(src, maxidx, maxIdx);
1457
}
1458

1459
void cv::minMaxLoc( InputArray _img, double* minVal, double* maxVal,
1460
                    Point* minLoc, Point* maxLoc, InputArray mask )
1461
{
K
Konstantin Matskevich 已提交
1462
    CV_Assert(_img.dims() <= 2);
1463

1464 1465 1466 1467 1468 1469
    minMaxIdx(_img, minVal, maxVal, (int*)minLoc, (int*)maxLoc, mask);
    if( minLoc )
        std::swap(minLoc->x, minLoc->y);
    if( maxLoc )
        std::swap(maxLoc->x, maxLoc->y);
}
1470

1471 1472 1473 1474
/****************************************************************************************\
*                                         norm                                           *
\****************************************************************************************/

1475
namespace cv
1476 1477
{

1478 1479 1480 1481 1482 1483 1484 1485
float normL2Sqr_(const float* a, const float* b, int n)
{
    int j = 0; float d = 0.f;
#if CV_SSE
    if( USE_SSE2 )
    {
        float CV_DECL_ALIGNED(16) buf[4];
        __m128 d0 = _mm_setzero_ps(), d1 = _mm_setzero_ps();
1486

1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        for( ; j <= n - 8; j += 8 )
        {
            __m128 t0 = _mm_sub_ps(_mm_loadu_ps(a + j), _mm_loadu_ps(b + j));
            __m128 t1 = _mm_sub_ps(_mm_loadu_ps(a + j + 4), _mm_loadu_ps(b + j + 4));
            d0 = _mm_add_ps(d0, _mm_mul_ps(t0, t0));
            d1 = _mm_add_ps(d1, _mm_mul_ps(t1, t1));
        }
        _mm_store_ps(buf, _mm_add_ps(d0, d1));
        d = buf[0] + buf[1] + buf[2] + buf[3];
    }
    else
#endif
1499
    {
1500 1501 1502 1503 1504 1505
        for( ; j <= n - 4; j += 4 )
        {
            float t0 = a[j] - b[j], t1 = a[j+1] - b[j+1], t2 = a[j+2] - b[j+2], t3 = a[j+3] - b[j+3];
            d += t0*t0 + t1*t1 + t2*t2 + t3*t3;
        }
    }
1506

1507 1508 1509 1510 1511 1512 1513 1514
    for( ; j < n; j++ )
    {
        float t = a[j] - b[j];
        d += t*t;
    }
    return d;
}

1515

1516 1517 1518 1519 1520 1521 1522
float normL1_(const float* a, const float* b, int n)
{
    int j = 0; float d = 0.f;
#if CV_SSE
    if( USE_SSE2 )
    {
        float CV_DECL_ALIGNED(16) buf[4];
1523
        static const int CV_DECL_ALIGNED(16) absbuf[4] = {0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff};
1524
        __m128 d0 = _mm_setzero_ps(), d1 = _mm_setzero_ps();
1525
        __m128 absmask = _mm_load_ps((const float*)absbuf);
1526

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
        for( ; j <= n - 8; j += 8 )
        {
            __m128 t0 = _mm_sub_ps(_mm_loadu_ps(a + j), _mm_loadu_ps(b + j));
            __m128 t1 = _mm_sub_ps(_mm_loadu_ps(a + j + 4), _mm_loadu_ps(b + j + 4));
            d0 = _mm_add_ps(d0, _mm_and_ps(t0, absmask));
            d1 = _mm_add_ps(d1, _mm_and_ps(t1, absmask));
        }
        _mm_store_ps(buf, _mm_add_ps(d0, d1));
        d = buf[0] + buf[1] + buf[2] + buf[3];
    }
    else
#endif
    {
        for( ; j <= n - 4; j += 4 )
        {
            d += std::abs(a[j] - b[j]) + std::abs(a[j+1] - b[j+1]) +
1543
                    std::abs(a[j+2] - b[j+2]) + std::abs(a[j+3] - b[j+3]);
1544 1545
        }
    }
V
Victoria Zhislina 已提交
1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    for( ; j < n; j++ )
        d += std::abs(a[j] - b[j]);
    return d;
}

int normL1_(const uchar* a, const uchar* b, int n)
{
    int j = 0, d = 0;
#if CV_SSE
    if( USE_SSE2 )
    {
        __m128i d0 = _mm_setzero_si128();
1559

1560 1561 1562 1563
        for( ; j <= n - 16; j += 16 )
        {
            __m128i t0 = _mm_loadu_si128((const __m128i*)(a + j));
            __m128i t1 = _mm_loadu_si128((const __m128i*)(b + j));
1564

1565 1566 1567 1568 1569 1570 1571
            d0 = _mm_add_epi32(d0, _mm_sad_epu8(t0, t1));
        }

        for( ; j <= n - 4; j += 4 )
        {
            __m128i t0 = _mm_cvtsi32_si128(*(const int*)(a + j));
            __m128i t1 = _mm_cvtsi32_si128(*(const int*)(b + j));
1572

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
            d0 = _mm_add_epi32(d0, _mm_sad_epu8(t0, t1));
        }
        d = _mm_cvtsi128_si32(_mm_add_epi32(d0, _mm_unpackhi_epi64(d0, d0)));
    }
    else
#endif
    {
        for( ; j <= n - 4; j += 4 )
        {
            d += std::abs(a[j] - b[j]) + std::abs(a[j+1] - b[j+1]) +
1583
                    std::abs(a[j+2] - b[j+2]) + std::abs(a[j+3] - b[j+3]);
1584 1585 1586 1587 1588 1589 1590
        }
    }
    for( ; j < n; j++ )
        d += std::abs(a[j] - b[j]);
    return d;
}

1591
static const uchar popCountTable[] =
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
{
    0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
    1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
    1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
    1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
    2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
    3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
1602

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
static const uchar popCountTable2[] =
{
    0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
    1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
    1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
    2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
    1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
    2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
    1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
    2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4
};
1614

1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
static const uchar popCountTable4[] =
{
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
};
1626

1627
static int normHamming(const uchar* a, int n)
V
Vadim Pisarevsky 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
{
    int i = 0, result = 0;
#if CV_NEON
    {
        uint32x4_t bits = vmovq_n_u32(0);
        for (; i <= n - 16; i += 16) {
            uint8x16_t A_vec = vld1q_u8 (a + i);
            uint8x16_t bitsSet = vcntq_u8 (A_vec);
            uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet);
            uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8);
            bits = vaddq_u32(bits, bitSet4);
        }
        uint64x2_t bitSet2 = vpaddlq_u32 (bits);
        result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0);
        result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2);
    }
#endif
        for( ; i <= n - 4; i += 4 )
            result += popCountTable[a[i]] + popCountTable[a[i+1]] +
            popCountTable[a[i+2]] + popCountTable[a[i+3]];
    for( ; i < n; i++ )
        result += popCountTable[a[i]];
    return result;
}
1652

1653 1654 1655
int normHamming(const uchar* a, const uchar* b, int n)
{
    int i = 0, result = 0;
A
Andrey Kamaev 已提交
1656
#if CV_NEON
1657
    {
A
Andrey Kamaev 已提交
1658 1659
        uint32x4_t bits = vmovq_n_u32(0);
        for (; i <= n - 16; i += 16) {
1660 1661 1662 1663 1664 1665
            uint8x16_t A_vec = vld1q_u8 (a + i);
            uint8x16_t B_vec = vld1q_u8 (b + i);
            uint8x16_t AxorB = veorq_u8 (A_vec, B_vec);
            uint8x16_t bitsSet = vcntq_u8 (AxorB);
            uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet);
            uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8);
A
Andrey Kamaev 已提交
1666
            bits = vaddq_u32(bits, bitSet4);
1667
        }
A
Andrey Kamaev 已提交
1668 1669 1670
        uint64x2_t bitSet2 = vpaddlq_u32 (bits);
        result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0);
        result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2);
1671 1672 1673 1674
    }
#endif
        for( ; i <= n - 4; i += 4 )
            result += popCountTable[a[i] ^ b[i]] + popCountTable[a[i+1] ^ b[i+1]] +
1675
                    popCountTable[a[i+2] ^ b[i+2]] + popCountTable[a[i+3] ^ b[i+3]];
1676 1677 1678 1679
    for( ; i < n; i++ )
        result += popCountTable[a[i] ^ b[i]];
    return result;
}
1680

1681
static int normHamming(const uchar* a, int n, int cellSize)
V
Vadim Pisarevsky 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
{
    if( cellSize == 1 )
        return normHamming(a, n);
    const uchar* tab = 0;
    if( cellSize == 2 )
        tab = popCountTable2;
    else if( cellSize == 4 )
        tab = popCountTable4;
    else
        CV_Error( CV_StsBadSize, "bad cell size (not 1, 2 or 4) in normHamming" );
    int i = 0, result = 0;
#if CV_ENABLE_UNROLLED
    for( ; i <= n - 4; i += 4 )
        result += tab[a[i]] + tab[a[i+1]] + tab[a[i+2]] + tab[a[i+3]];
#endif
    for( ; i < n; i++ )
        result += tab[a[i]];
    return result;
1700 1701
}

1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
int normHamming(const uchar* a, const uchar* b, int n, int cellSize)
{
    if( cellSize == 1 )
        return normHamming(a, b, n);
    const uchar* tab = 0;
    if( cellSize == 2 )
        tab = popCountTable2;
    else if( cellSize == 4 )
        tab = popCountTable4;
    else
        CV_Error( CV_StsBadSize, "bad cell size (not 1, 2 or 4) in normHamming" );
    int i = 0, result = 0;
1714
    #if CV_ENABLE_UNROLLED
1715 1716
    for( ; i <= n - 4; i += 4 )
        result += tab[a[i] ^ b[i]] + tab[a[i+1] ^ b[i+1]] +
1717
                tab[a[i+2] ^ b[i+2]] + tab[a[i+3] ^ b[i+3]];
V
Victoria Zhislina 已提交
1718
    #endif
1719 1720 1721 1722
    for( ; i < n; i++ )
        result += tab[a[i] ^ b[i]];
    return result;
}
1723 1724


1725 1726
template<typename T, typename ST> int
normInf_(const T* src, const uchar* mask, ST* _result, int len, int cn)
1727
{
1728 1729
    ST result = *_result;
    if( !mask )
1730
    {
1731
        result = std::max(result, normInf<T, ST>(src, len*cn));
1732 1733 1734 1735 1736
    }
    else
    {
        for( int i = 0; i < len; i++, src += cn )
            if( mask[i] )
1737
            {
1738
                for( int k = 0; k < cn; k++ )
A
Andrey Kamaev 已提交
1739
                    result = std::max(result, ST(std::abs(src[k])));
1740
            }
1741 1742 1743 1744
    }
    *_result = result;
    return 0;
}
1745

1746 1747 1748 1749 1750 1751
template<typename T, typename ST> int
normL1_(const T* src, const uchar* mask, ST* _result, int len, int cn)
{
    ST result = *_result;
    if( !mask )
    {
1752
        result += normL1<T, ST>(src, len*cn);
1753 1754 1755 1756 1757
    }
    else
    {
        for( int i = 0; i < len; i++, src += cn )
            if( mask[i] )
1758
            {
1759
                for( int k = 0; k < cn; k++ )
A
Andrey Kamaev 已提交
1760
                    result += std::abs(src[k]);
1761 1762
            }
    }
1763 1764
    *_result = result;
    return 0;
1765 1766
}

1767 1768
template<typename T, typename ST> int
normL2_(const T* src, const uchar* mask, ST* _result, int len, int cn)
1769
{
1770 1771
    ST result = *_result;
    if( !mask )
1772
    {
1773
        result += normL2Sqr<T, ST>(src, len*cn);
1774
    }
1775
    else
1776
    {
1777 1778
        for( int i = 0; i < len; i++, src += cn )
            if( mask[i] )
1779
            {
1780
                for( int k = 0; k < cn; k++ )
1781
                {
1782 1783
                    T v = src[k];
                    result += (ST)v*v;
1784
                }
1785 1786
            }
    }
1787 1788
    *_result = result;
    return 0;
1789
}
1790

1791 1792 1793 1794 1795
template<typename T, typename ST> int
normDiffInf_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
{
    ST result = *_result;
    if( !mask )
1796
    {
1797
        result = std::max(result, normInf<T, ST>(src1, src2, len*cn));
1798 1799 1800 1801 1802
    }
    else
    {
        for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
            if( mask[i] )
1803
            {
1804
                for( int k = 0; k < cn; k++ )
1805
                    result = std::max(result, (ST)std::abs(src1[k] - src2[k]));
1806
            }
1807
    }
1808 1809
    *_result = result;
    return 0;
1810 1811
}

1812 1813
template<typename T, typename ST> int
normDiffL1_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
1814
{
1815 1816
    ST result = *_result;
    if( !mask )
1817
    {
1818
        result += normL1<T, ST>(src1, src2, len*cn);
1819 1820 1821 1822 1823
    }
    else
    {
        for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
            if( mask[i] )
1824
            {
1825 1826
                for( int k = 0; k < cn; k++ )
                    result += std::abs(src1[k] - src2[k]);
1827 1828
            }
    }
1829 1830
    *_result = result;
    return 0;
1831 1832
}

1833 1834
template<typename T, typename ST> int
normDiffL2_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
1835
{
1836 1837
    ST result = *_result;
    if( !mask )
1838
    {
1839
        result += normL2Sqr<T, ST>(src1, src2, len*cn);
1840
    }
1841
    else
1842
    {
1843 1844
        for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
            if( mask[i] )
1845
            {
1846
                for( int k = 0; k < cn; k++ )
1847
                {
1848 1849
                    ST v = src1[k] - src2[k];
                    result += v*v;
1850
                }
1851 1852
            }
    }
1853 1854
    *_result = result;
    return 0;
1855
}
1856

1857 1858

#define CV_DEF_NORM_FUNC(L, suffix, type, ntype) \
1859
    static int norm##L##_##suffix(const type* src, const uchar* mask, ntype* r, int len, int cn) \
1860
{ return norm##L##_(src, mask, r, len, cn); } \
1861 1862
    static int normDiff##L##_##suffix(const type* src1, const type* src2, \
    const uchar* mask, ntype* r, int len, int cn) \
1863
{ return normDiff##L##_(src1, src2, mask, r, (int)len, cn); }
1864

1865
#define CV_DEF_NORM_ALL(suffix, type, inftype, l1type, l2type) \
1866 1867 1868
    CV_DEF_NORM_FUNC(Inf, suffix, type, inftype) \
    CV_DEF_NORM_FUNC(L1, suffix, type, l1type) \
    CV_DEF_NORM_FUNC(L2, suffix, type, l2type)
1869 1870 1871 1872 1873 1874 1875 1876

CV_DEF_NORM_ALL(8u, uchar, int, int, int)
CV_DEF_NORM_ALL(8s, schar, int, int, int)
CV_DEF_NORM_ALL(16u, ushort, int, int, double)
CV_DEF_NORM_ALL(16s, short, int, int, double)
CV_DEF_NORM_ALL(32s, int, int, double, double)
CV_DEF_NORM_ALL(32f, float, float, double, double)
CV_DEF_NORM_ALL(64f, double, double, double, double)
1877

1878

1879
typedef int (*NormFunc)(const uchar*, const uchar*, uchar*, int, int);
1880
typedef int (*NormDiffFunc)(const uchar*, const uchar*, const uchar*, uchar*, int, int);
1881

1882
static NormFunc getNormFunc(int normType, int depth)
1883
{
1884
    static NormFunc normTab[3][8] =
1885
    {
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
        {
            (NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)GET_OPTIMIZED(normInf_8s), (NormFunc)GET_OPTIMIZED(normInf_16u), (NormFunc)GET_OPTIMIZED(normInf_16s),
            (NormFunc)GET_OPTIMIZED(normInf_32s), (NormFunc)GET_OPTIMIZED(normInf_32f), (NormFunc)normInf_64f, 0
        },
        {
            (NormFunc)GET_OPTIMIZED(normL1_8u), (NormFunc)GET_OPTIMIZED(normL1_8s), (NormFunc)GET_OPTIMIZED(normL1_16u), (NormFunc)GET_OPTIMIZED(normL1_16s),
            (NormFunc)GET_OPTIMIZED(normL1_32s), (NormFunc)GET_OPTIMIZED(normL1_32f), (NormFunc)normL1_64f, 0
        },
        {
            (NormFunc)GET_OPTIMIZED(normL2_8u), (NormFunc)GET_OPTIMIZED(normL2_8s), (NormFunc)GET_OPTIMIZED(normL2_16u), (NormFunc)GET_OPTIMIZED(normL2_16s),
            (NormFunc)GET_OPTIMIZED(normL2_32s), (NormFunc)GET_OPTIMIZED(normL2_32f), (NormFunc)normL2_64f, 0
        }
    };
1899

1900 1901 1902 1903
    return normTab[normType][depth];
}

static NormDiffFunc getNormDiffFunc(int normType, int depth)
1904
{
1905
    static NormDiffFunc normDiffTab[3][8] =
1906
    {
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
        {
            (NormDiffFunc)GET_OPTIMIZED(normDiffInf_8u), (NormDiffFunc)normDiffInf_8s,
            (NormDiffFunc)normDiffInf_16u, (NormDiffFunc)normDiffInf_16s,
            (NormDiffFunc)normDiffInf_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffInf_32f),
            (NormDiffFunc)normDiffInf_64f, 0
        },
        {
            (NormDiffFunc)GET_OPTIMIZED(normDiffL1_8u), (NormDiffFunc)normDiffL1_8s,
            (NormDiffFunc)normDiffL1_16u, (NormDiffFunc)normDiffL1_16s,
            (NormDiffFunc)normDiffL1_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffL1_32f),
            (NormDiffFunc)normDiffL1_64f, 0
        },
        {
            (NormDiffFunc)GET_OPTIMIZED(normDiffL2_8u), (NormDiffFunc)normDiffL2_8s,
            (NormDiffFunc)normDiffL2_16u, (NormDiffFunc)normDiffL2_16s,
            (NormDiffFunc)normDiffL2_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffL2_32f),
            (NormDiffFunc)normDiffL2_64f, 0
        }
    };

    return normDiffTab[normType][depth];
}
1929

I
Ilya Lavrenov 已提交
1930
#ifdef HAVE_OPENCL
I
Ilya Lavrenov 已提交
1931

1932
static bool ocl_norm( InputArray _src, int normType, InputArray _mask, double & result )
1933
{
I
Ilya Lavrenov 已提交
1934
    int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
1935 1936
    bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0,
            haveMask = _mask.kind() != _InputArray::NONE;
1937

1938
    if ( !(normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR) ||
1939
         (!doubleSupport && depth == CV_64F) || (normType == NORM_INF && haveMask && cn != 1))
I
Ilya Lavrenov 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
        return false;

    UMat src = _src.getUMat();

    if (normType == NORM_INF)
    {
        UMat abssrc;

        if (depth != CV_8U && depth != CV_16U)
        {
            int wdepth = std::max(CV_32S, depth);
            char cvt[50];

            ocl::Kernel kabs("KF", ocl::core::arithm_oclsrc,
                             format("-D UNARY_OP -D OP_ABS_NOSAT -D dstT=%s -D srcT1=%s -D convertToDT=%s%s",
                                    ocl::typeToStr(wdepth), ocl::typeToStr(depth),
                                    ocl::convertTypeStr(depth, wdepth, 1, cvt),
                                    doubleSupport ? " -D DOUBLE_SUPPORT" : ""));
            if (kabs.empty())
                return false;

            abssrc.create(src.size(), CV_MAKE_TYPE(wdepth, cn));
            kabs.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(abssrc, cn));

            size_t globalsize[2] = { src.cols * cn, src.rows };
            if (!kabs.run(2, globalsize, NULL, false))
                return false;
        }
        else
            abssrc = src;

1971
        cv::minMaxIdx(haveMask ? abssrc : abssrc.reshape(1), NULL, &result, NULL, NULL, _mask);
I
Ilya Lavrenov 已提交
1972
    }
1973
    else if (normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR)
I
Ilya Lavrenov 已提交
1974
    {
1975
        Scalar sc;
I
Ilya Lavrenov 已提交
1976 1977
        bool unstype = depth == CV_8U || depth == CV_16U;

1978
        if ( !ocl_sum(haveMask ? src : src.reshape(1), sc, normType == NORM_L2 || normType == NORM_L2SQR ?
1979
                    OCL_OP_SUM_SQR : (unstype ? OCL_OP_SUM : OCL_OP_SUM_ABS), _mask) )
1980
            return false;
1981 1982 1983 1984 1985 1986 1987 1988

        if (!haveMask)
            cn = 1;

        double s = 0.0;
        for (int i = 0; i < cn; ++i)
            s += sc[i];

1989
        result = normType == NORM_L1 || normType == NORM_L2SQR ? s : std::sqrt(s);
I
Ilya Lavrenov 已提交
1990 1991 1992 1993 1994
    }

    return true;
}

I
Ilya Lavrenov 已提交
1995 1996
#endif

I
Ilya Lavrenov 已提交
1997 1998 1999 2000 2001
}

double cv::norm( InputArray _src, int normType, InputArray _mask )
{
    normType &= NORM_TYPE_MASK;
2002 2003
    CV_Assert( normType == NORM_INF || normType == NORM_L1 ||
               normType == NORM_L2 || normType == NORM_L2SQR ||
I
Ilya Lavrenov 已提交
2004 2005
               ((normType == NORM_HAMMING || normType == NORM_HAMMING2) && _src.type() == CV_8U) );

I
Ilya Lavrenov 已提交
2006
#ifdef HAVE_OPENCL
I
Ilya Lavrenov 已提交
2007
    double _result = 0;
2008 2009 2010
    CV_OCL_RUN_(_src.isUMat() && _src.dims() <= 2,
                ocl_norm(_src, normType, _mask, _result),
                _result)
I
Ilya Lavrenov 已提交
2011
#endif
I
Ilya Lavrenov 已提交
2012 2013 2014

    Mat src = _src.getMat(), mask = _mask.getMat();
    int depth = src.depth(), cn = src.channels();
2015

2016 2017 2018
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
    size_t total_size = src.total();
    int rows = src.size[0], cols = (int)(total_size/rows);
2019 2020 2021 2022
    if( (src.dims == 2 || (src.isContinuous() && mask.isContinuous()))
        && cols > 0 && (size_t)rows*cols == total_size
        && (normType == NORM_INF || normType == NORM_L1 ||
            normType == NORM_L2 || normType == NORM_L2SQR) )
2023 2024 2025 2026 2027
    {
        IppiSize sz = { cols, rows };
        int type = src.type();
        if( !mask.empty() )
        {
2028 2029
            typedef IppStatus (CV_STDCALL* ippiMaskNormFuncC1)(const void *, int, const void *, int, IppiSize, Ipp64f *);
            ippiMaskNormFuncC1 ippFuncC1 =
2030
                normType == NORM_INF ?
2031 2032 2033 2034
                (type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_32f_C1MR :
2035 2036
                0) :
            normType == NORM_L1 ?
2037 2038 2039 2040
                (type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_32f_C1MR :
2041 2042
                0) :
            normType == NORM_L2 || normType == NORM_L2SQR ?
2043 2044 2045 2046
                (type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_32f_C1MR :
2047 2048 2049 2050 2051 2052 2053 2054 2055
                0) : 0;
            if( ippFuncC1 )
            {
                Ipp64f norm;
                if( ippFuncC1(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, &norm) >= 0 )
                {
                    return normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm;
                }
            }
2056 2057
            typedef IppStatus (CV_STDCALL* ippiMaskNormFuncC3)(const void *, int, const void *, int, IppiSize, int, Ipp64f *);
            ippiMaskNormFuncC3 ippFuncC3 =
2058
                normType == NORM_INF ?
2059 2060 2061 2062
                (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_32f_C3CMR :
2063 2064
                0) :
            normType == NORM_L1 ?
2065 2066 2067 2068
                (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_32f_C3CMR :
2069 2070
                0) :
            normType == NORM_L2 || normType == NORM_L2SQR ?
2071 2072 2073 2074
                (type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_32f_C3CMR :
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
                0) : 0;
            if( ippFuncC3 )
            {
                Ipp64f norm1, norm2, norm3;
                if( ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 1, &norm1) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 2, &norm2) >= 0 &&
                    ippFuncC3(src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 3, &norm3) >= 0)
                {
                    Ipp64f norm =
                        normType == NORM_INF ? std::max(std::max(norm1, norm2), norm3) :
                        normType == NORM_L1 ? norm1 + norm2 + norm3 :
                        normType == NORM_L2 || normType == NORM_L2SQR ? std::sqrt(norm1 * norm1 + norm2 * norm2 + norm3 * norm3) :
                        0;
                    return normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm;
                }
            }
        }
        else
        {
2094 2095 2096
            typedef IppStatus (CV_STDCALL* ippiNormFuncHint)(const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
            typedef IppStatus (CV_STDCALL* ippiNormFuncNoHint)(const void *, int, IppiSize, Ipp64f *);
            ippiNormFuncHint ippFuncHint =
2097
                normType == NORM_L1 ?
2098 2099 2100
                (type == CV_32FC1 ? (ippiNormFuncHint)ippiNorm_L1_32f_C1R :
                type == CV_32FC3 ? (ippiNormFuncHint)ippiNorm_L1_32f_C3R :
                type == CV_32FC4 ? (ippiNormFuncHint)ippiNorm_L1_32f_C4R :
2101 2102
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2103 2104 2105
                (type == CV_32FC1 ? (ippiNormFuncHint)ippiNorm_L2_32f_C1R :
                type == CV_32FC3 ? (ippiNormFuncHint)ippiNorm_L2_32f_C3R :
                type == CV_32FC4 ? (ippiNormFuncHint)ippiNorm_L2_32f_C4R :
2106
                0) : 0;
2107
            ippiNormFuncNoHint ippFuncNoHint =
2108
                normType == NORM_INF ?
2109 2110 2111 2112 2113 2114 2115
                (type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_8u_C1R :
                type == CV_8UC3 ? (ippiNormFuncNoHint)ippiNorm_Inf_8u_C3R :
                type == CV_8UC4 ? (ippiNormFuncNoHint)ippiNorm_Inf_8u_C4R :
                type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_16u_C1R :
                type == CV_16UC3 ? (ippiNormFuncNoHint)ippiNorm_Inf_16u_C3R :
                type == CV_16UC4 ? (ippiNormFuncNoHint)ippiNorm_Inf_16u_C4R :
                type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_16s_C1R :
2116
#if ((IPP_VERSION_MAJOR >= 8) && (IPP_VERSION_MINOR >= 1)) || (IPP_VERSION_MAJOR > 8)
2117 2118
                type == CV_16SC3 ? (ippiNormFuncNoHint)ippiNorm_Inf_16s_C3R : //Aug 2013: problem in IPP 7.1, 8.0 : -32768
                type == CV_16SC4 ? (ippiNormFuncNoHint)ippiNorm_Inf_16s_C4R : //Aug 2013: problem in IPP 7.1, 8.0 : -32768
2119
#endif
2120 2121 2122
                type == CV_32FC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_32f_C1R :
                type == CV_32FC3 ? (ippiNormFuncNoHint)ippiNorm_Inf_32f_C3R :
                type == CV_32FC4 ? (ippiNormFuncNoHint)ippiNorm_Inf_32f_C4R :
2123 2124
                0) :
                normType == NORM_L1 ?
2125 2126 2127 2128 2129 2130 2131 2132 2133
                (type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_L1_8u_C1R :
                type == CV_8UC3 ? (ippiNormFuncNoHint)ippiNorm_L1_8u_C3R :
                type == CV_8UC4 ? (ippiNormFuncNoHint)ippiNorm_L1_8u_C4R :
                type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_L1_16u_C1R :
                type == CV_16UC3 ? (ippiNormFuncNoHint)ippiNorm_L1_16u_C3R :
                type == CV_16UC4 ? (ippiNormFuncNoHint)ippiNorm_L1_16u_C4R :
                type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_L1_16s_C1R :
                type == CV_16SC3 ? (ippiNormFuncNoHint)ippiNorm_L1_16s_C3R :
                type == CV_16SC4 ? (ippiNormFuncNoHint)ippiNorm_L1_16s_C4R :
2134 2135
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2136 2137 2138 2139 2140 2141 2142 2143 2144
                (type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_L2_8u_C1R :
                type == CV_8UC3 ? (ippiNormFuncNoHint)ippiNorm_L2_8u_C3R :
                type == CV_8UC4 ? (ippiNormFuncNoHint)ippiNorm_L2_8u_C4R :
                type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_L2_16u_C1R :
                type == CV_16UC3 ? (ippiNormFuncNoHint)ippiNorm_L2_16u_C3R :
                type == CV_16UC4 ? (ippiNormFuncNoHint)ippiNorm_L2_16u_C4R :
                type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_L2_16s_C1R :
                type == CV_16SC3 ? (ippiNormFuncNoHint)ippiNorm_L2_16s_C3R :
                type == CV_16SC4 ? (ippiNormFuncNoHint)ippiNorm_L2_16s_C4R :
2145
                0) : 0;
2146 2147 2148
            // Make sure only zero or one version of the function pointer is valid
            CV_Assert(!ippFuncHint || !ippFuncNoHint);
            if( ippFuncHint || ippFuncNoHint )
2149 2150
            {
                Ipp64f norm_array[4];
2151 2152 2153
                IppStatus ret = ippFuncHint ? ippFuncHint(src.data, (int)src.step[0], sz, norm_array, ippAlgHintAccurate) :
                                ippFuncNoHint(src.data, (int)src.step[0], sz, norm_array);
                if( ret >= 0 )
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
                {
                    Ipp64f norm = (normType == NORM_L2 || normType == NORM_L2SQR) ? norm_array[0] * norm_array[0] : norm_array[0];
                    for( int i = 1; i < cn; i++ )
                    {
                        norm =
                            normType == NORM_INF ? std::max(norm, norm_array[i]) :
                            normType == NORM_L1 ? norm + norm_array[i] :
                            normType == NORM_L2 || normType == NORM_L2SQR ? norm + norm_array[i] * norm_array[i] :
                            0;
                    }
                    return normType == NORM_L2 ? (double)std::sqrt(norm) : (double)norm;
                }
            }
        }
    }
#endif

V
Vadim Pisarevsky 已提交
2171
    if( src.isContinuous() && mask.empty() )
V
Vadim Pisarevsky 已提交
2172
    {
2173 2174
        size_t len = src.total()*cn;
        if( len == (size_t)(int)len )
V
Vadim Pisarevsky 已提交
2175
        {
V
Vadim Pisarevsky 已提交
2176
            if( depth == CV_32F )
2177
            {
V
Vadim Pisarevsky 已提交
2178
                const float* data = src.ptr<float>();
2179

V
Vadim Pisarevsky 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
                if( normType == NORM_L2 )
                {
                    double result = 0;
                    GET_OPTIMIZED(normL2_32f)(data, 0, &result, (int)len, 1);
                    return std::sqrt(result);
                }
                if( normType == NORM_L2SQR )
                {
                    double result = 0;
                    GET_OPTIMIZED(normL2_32f)(data, 0, &result, (int)len, 1);
                    return result;
                }
                if( normType == NORM_L1 )
                {
                    double result = 0;
                    GET_OPTIMIZED(normL1_32f)(data, 0, &result, (int)len, 1);
                    return result;
                }
                if( normType == NORM_INF )
                {
                    float result = 0;
                    GET_OPTIMIZED(normInf_32f)(data, 0, &result, (int)len, 1);
                    return result;
                }
2204
            }
V
Vadim Pisarevsky 已提交
2205
            if( depth == CV_8U )
2206
            {
V
Vadim Pisarevsky 已提交
2207
                const uchar* data = src.ptr<uchar>();
2208

V
Vadim Pisarevsky 已提交
2209 2210
                if( normType == NORM_HAMMING )
                    return normHamming(data, (int)len);
2211

V
Vadim Pisarevsky 已提交
2212 2213
                if( normType == NORM_HAMMING2 )
                    return normHamming(data, (int)len, 2);
2214
            }
V
Vadim Pisarevsky 已提交
2215 2216
        }
    }
2217

2218
    CV_Assert( mask.empty() || mask.type() == CV_8U );
2219

V
Vadim Pisarevsky 已提交
2220 2221 2222 2223 2224 2225 2226 2227 2228
    if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
    {
        if( !mask.empty() )
        {
            Mat temp;
            bitwise_and(src, mask, temp);
            return norm(temp, normType);
        }
        int cellSize = normType == NORM_HAMMING ? 1 : 2;
2229

V
Vadim Pisarevsky 已提交
2230 2231 2232 2233 2234
        const Mat* arrays[] = {&src, 0};
        uchar* ptrs[1];
        NAryMatIterator it(arrays, ptrs);
        int total = (int)it.size;
        int result = 0;
2235

V
Vadim Pisarevsky 已提交
2236 2237
        for( size_t i = 0; i < it.nplanes; i++, ++it )
            result += normHamming(ptrs[0], total, cellSize);
2238

V
Vadim Pisarevsky 已提交
2239 2240
        return result;
    }
2241

2242
    NormFunc func = getNormFunc(normType >> 1, depth);
2243
    CV_Assert( func != 0 );
2244

2245 2246
    const Mat* arrays[] = {&src, &mask, 0};
    uchar* ptrs[2];
2247 2248 2249 2250 2251 2252 2253 2254
    union
    {
        double d;
        int i;
        float f;
    }
    result;
    result.d = 0;
2255 2256 2257
    NAryMatIterator it(arrays, ptrs);
    int j, total = (int)it.size, blockSize = total, intSumBlockSize = 0, count = 0;
    bool blockSum = (normType == NORM_L1 && depth <= CV_16S) ||
V
Vadim Pisarevsky 已提交
2258
            ((normType == NORM_L2 || normType == NORM_L2SQR) && depth <= CV_8S);
2259
    int isum = 0;
2260
    int *ibuf = &result.i;
2261
    size_t esz = 0;
2262

2263
    if( blockSum )
2264
    {
2265 2266 2267 2268 2269
        intSumBlockSize = (normType == NORM_L1 && depth <= CV_8S ? (1 << 23) : (1 << 15))/cn;
        blockSize = std::min(blockSize, intSumBlockSize);
        ibuf = &isum;
        esz = src.elemSize();
    }
2270

2271
    for( size_t i = 0; i < it.nplanes; i++, ++it )
V
Vadim Pisarevsky 已提交
2272
    {
2273
        for( j = 0; j < total; j += blockSize )
V
Vadim Pisarevsky 已提交
2274
        {
2275
            int bsz = std::min(total - j, blockSize);
2276 2277
            func( ptrs[0], ptrs[1], (uchar*)ibuf, bsz, cn );
            count += bsz;
2278 2279
            if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) )
            {
2280
                result.d += isum;
2281 2282 2283 2284 2285 2286
                isum = 0;
                count = 0;
            }
            ptrs[0] += bsz*esz;
            if( ptrs[1] )
                ptrs[1] += bsz;
V
Vadim Pisarevsky 已提交
2287 2288
        }
    }
2289

2290
    if( normType == NORM_INF )
V
Vadim Pisarevsky 已提交
2291
    {
2292 2293 2294
        if( depth == CV_64F )
            ;
        else if( depth == CV_32F )
2295
            result.d = result.f;
2296
        else
2297
            result.d = result.i;
V
Vadim Pisarevsky 已提交
2298
    }
2299
    else if( normType == NORM_L2 )
2300
        result.d = std::sqrt(result.d);
2301

2302
    return result.d;
2303 2304
}

I
Ilya Lavrenov 已提交
2305 2306
#ifdef HAVE_OPENCL

I
Ilya Lavrenov 已提交
2307 2308
namespace cv {

I
Ilya Lavrenov 已提交
2309
static bool ocl_norm( InputArray _src1, InputArray _src2, int normType, InputArray _mask, double & result )
I
Ilya Lavrenov 已提交
2310 2311 2312 2313 2314 2315
{
    int type = _src1.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
    bool doubleSupport = ocl::Device::getDefault().doubleFPConfig() > 0;
    bool relative = (normType & NORM_RELATIVE) != 0;
    normType &= ~NORM_RELATIVE;

2316
    if ( !(normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR) ||
I
Ilya Lavrenov 已提交
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
         (!doubleSupport && depth == CV_64F))
        return false;

    int wdepth = std::max(CV_32S, depth);
    char cvt[50];
    ocl::Kernel k("KF", ocl::core::arithm_oclsrc,
                  format("-D BINARY_OP -D OP_ABSDIFF -D dstT=%s -D workT=dstT -D srcT1=%s -D srcT2=srcT1"
                         " -D convertToDT=%s -D convertToWT1=convertToDT -D convertToWT2=convertToDT%s",
                         ocl::typeToStr(wdepth), ocl::typeToStr(depth),
                         ocl::convertTypeStr(depth, wdepth, 1, cvt),
                         doubleSupport ? " -D DOUBLE_SUPPORT" : ""));
    if (k.empty())
        return false;

    UMat src1 = _src1.getUMat(), src2 = _src2.getUMat(), diff(src1.size(), CV_MAKE_TYPE(wdepth, cn));
    k.args(ocl::KernelArg::ReadOnlyNoSize(src1), ocl::KernelArg::ReadOnlyNoSize(src2),
           ocl::KernelArg::WriteOnly(diff, cn));

    size_t globalsize[2] = { diff.cols * cn, diff.rows };
    if (!k.run(2, globalsize, NULL, false))
        return false;

I
Ilya Lavrenov 已提交
2339
    result = cv::norm(diff, normType, _mask);
I
Ilya Lavrenov 已提交
2340
    if (relative)
I
Ilya Lavrenov 已提交
2341
        result /= cv::norm(src2, normType, _mask) + DBL_EPSILON;
I
Ilya Lavrenov 已提交
2342 2343 2344 2345 2346

    return true;
}

}
2347

I
Ilya Lavrenov 已提交
2348 2349
#endif

2350
double cv::norm( InputArray _src1, InputArray _src2, int normType, InputArray _mask )
2351
{
2352
    CV_Assert( _src1.sameSize(_src2) && _src1.type() == _src2.type() );
I
Ilya Lavrenov 已提交
2353

I
Ilya Lavrenov 已提交
2354
#ifdef HAVE_OPENCL
I
Ilya Lavrenov 已提交
2355
    double _result = 0;
I
Ilya Lavrenov 已提交
2356
    CV_OCL_RUN_(_src1.isUMat() && _src2.isUMat() &&
2357
                _src1.dims() <= 2 && _src2.dims() <= 2,
I
Ilya Lavrenov 已提交
2358
                ocl_norm(_src1, _src2, normType, _mask, _result),
2359
                _result)
I
Ilya Lavrenov 已提交
2360
#endif
I
Ilya Lavrenov 已提交
2361

V
Vadim Pisarevsky 已提交
2362
    if( normType & CV_RELATIVE )
2363 2364 2365 2366 2367 2368 2369 2370 2371
    {
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
        Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();

        normType &= 7;
        CV_Assert( normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR ||
                ((normType == NORM_HAMMING || normType == NORM_HAMMING2) && src1.type() == CV_8U) );
        size_t total_size = src1.total();
        int rows = src1.size[0], cols = (int)(total_size/rows);
2372 2373 2374 2375
        if( (src1.dims == 2 || (src1.isContinuous() && src2.isContinuous() && mask.isContinuous()))
            && cols > 0 && (size_t)rows*cols == total_size
            && (normType == NORM_INF || normType == NORM_L1 ||
                normType == NORM_L2 || normType == NORM_L2SQR) )
2376 2377 2378 2379 2380
        {
            IppiSize sz = { cols, rows };
            int type = src1.type();
            if( !mask.empty() )
            {
2381 2382
                typedef IppStatus (CV_STDCALL* ippiMaskNormRelFuncC1)(const void *, int, const void *, int, const void *, int, IppiSize, Ipp64f *);
                ippiMaskNormRelFuncC1 ippFuncC1 =
2383
                    normType == NORM_INF ?
2384 2385 2386 2387
                    (type == CV_8UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_Inf_8u_C1MR :
                    type == CV_8SC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_Inf_8s_C1MR :
                    type == CV_16UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_Inf_16u_C1MR :
                    type == CV_32FC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_Inf_32f_C1MR :
2388 2389
                    0) :
                    normType == NORM_L1 ?
2390 2391 2392 2393
                    (type == CV_8UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L1_8u_C1MR :
                    type == CV_8SC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L1_8s_C1MR :
                    type == CV_16UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L1_16u_C1MR :
                    type == CV_32FC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L1_32f_C1MR :
2394 2395
                    0) :
                    normType == NORM_L2 || normType == NORM_L2SQR ?
2396 2397 2398 2399
                    (type == CV_8UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L2_8u_C1MR :
                    type == CV_8SC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L2_8s_C1MR :
                    type == CV_16UC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L2_16u_C1MR :
                    type == CV_32FC1 ? (ippiMaskNormRelFuncC1)ippiNormRel_L2_32f_C1MR :
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
                    0) : 0;
                if( ippFuncC1 )
                {
                    Ipp64f norm;
                    if( ippFuncC1(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, &norm) >= 0 )
                        return normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm;
                }
            }
            else
            {
2410 2411
                typedef IppStatus (CV_STDCALL* ippiNormRelFunc)(const void *, int, const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
                ippiNormRelFunc ippFunc =
2412
                    normType == NORM_INF ?
2413 2414 2415 2416
                    (type == CV_8UC1 ? (ippiNormRelFunc)ippiNormRel_Inf_8u_C1R :
                    type == CV_16UC1 ? (ippiNormRelFunc)ippiNormRel_Inf_16u_C1R :
                    type == CV_16SC1 ? (ippiNormRelFunc)ippiNormRel_Inf_16s_C1R :
                    type == CV_32FC1 ? (ippiNormRelFunc)ippiNormRel_Inf_32f_C1R :
2417 2418
                    0) :
                    normType == NORM_L1 ?
2419 2420 2421 2422
                    (type == CV_8UC1 ? (ippiNormRelFunc)ippiNormRel_L1_8u_C1R :
                    type == CV_16UC1 ? (ippiNormRelFunc)ippiNormRel_L1_16u_C1R :
                    type == CV_16SC1 ? (ippiNormRelFunc)ippiNormRel_L1_16s_C1R :
                    type == CV_32FC1 ? (ippiNormRelFunc)ippiNormRel_L1_32f_C1R :
2423 2424
                    0) :
                    normType == NORM_L2 || normType == NORM_L2SQR ?
2425 2426 2427 2428
                    (type == CV_8UC1 ? (ippiNormRelFunc)ippiNormRel_L2_8u_C1R :
                    type == CV_16UC1 ? (ippiNormRelFunc)ippiNormRel_L2_16u_C1R :
                    type == CV_16SC1 ? (ippiNormRelFunc)ippiNormRel_L2_16s_C1R :
                    type == CV_32FC1 ? (ippiNormRelFunc)ippiNormRel_L2_32f_C1R :
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
                    0) : 0;
                if( ippFunc )
                {
                    Ipp64f norm;
                    if( ippFunc(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], sz, &norm, ippAlgHintAccurate) >= 0 )
                        return (double)norm;
                }
            }
        }
#endif
V
Vadim Pisarevsky 已提交
2439
        return norm(_src1, _src2, normType & ~CV_RELATIVE, _mask)/(norm(_src2, normType, _mask) + DBL_EPSILON);
2440
    }
2441

2442 2443
    Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();
    int depth = src1.depth(), cn = src1.channels();
2444

2445
    normType &= 7;
2446 2447
    CV_Assert( normType == NORM_INF || normType == NORM_L1 ||
               normType == NORM_L2 || normType == NORM_L2SQR ||
V
Vadim Pisarevsky 已提交
2448
              ((normType == NORM_HAMMING || normType == NORM_HAMMING2) && src1.type() == CV_8U) );
2449

2450 2451 2452
#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
    size_t total_size = src1.total();
    int rows = src1.size[0], cols = (int)(total_size/rows);
2453 2454 2455 2456
    if( (src1.dims == 2 || (src1.isContinuous() && src2.isContinuous() && mask.isContinuous()))
        && cols > 0 && (size_t)rows*cols == total_size
        && (normType == NORM_INF || normType == NORM_L1 ||
            normType == NORM_L2 || normType == NORM_L2SQR) )
2457 2458 2459 2460 2461
    {
        IppiSize sz = { cols, rows };
        int type = src1.type();
        if( !mask.empty() )
        {
2462 2463
            typedef IppStatus (CV_STDCALL* ippiMaskNormDiffFuncC1)(const void *, int, const void *, int, const void *, int, IppiSize, Ipp64f *);
            ippiMaskNormDiffFuncC1 ippFuncC1 =
2464
                normType == NORM_INF ?
2465 2466 2467 2468
                (type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_32f_C1MR :
2469 2470
                0) :
                normType == NORM_L1 ?
2471 2472 2473 2474
                (type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_32f_C1MR :
2475 2476
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2477 2478 2479 2480
                (type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_8u_C1MR :
                type == CV_8SC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_8s_C1MR :
                type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_16u_C1MR :
                type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_32f_C1MR :
2481 2482 2483 2484 2485 2486 2487
                0) : 0;
            if( ippFuncC1 )
            {
                Ipp64f norm;
                if( ippFuncC1(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, &norm) >= 0 )
                    return normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm;
            }
2488 2489
            typedef IppStatus (CV_STDCALL* ippiMaskNormDiffFuncC3)(const void *, int, const void *, int, const void *, int, IppiSize, int, Ipp64f *);
            ippiMaskNormDiffFuncC3 ippFuncC3 =
2490
                normType == NORM_INF ?
2491 2492 2493 2494
                (type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_32f_C3CMR :
2495 2496
                0) :
                normType == NORM_L1 ?
2497 2498 2499 2500
                (type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_32f_C3CMR :
2501 2502
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2503 2504 2505 2506
                (type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_8u_C3CMR :
                type == CV_8SC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_8s_C3CMR :
                type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_16u_C3CMR :
                type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_32f_C3CMR :
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
                0) : 0;
            if( ippFuncC3 )
            {
                Ipp64f norm1, norm2, norm3;
                if( ippFuncC3(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 1, &norm1) >= 0 &&
                    ippFuncC3(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 2, &norm2) >= 0 &&
                    ippFuncC3(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 3, &norm3) >= 0)
                {
                    Ipp64f norm =
                        normType == NORM_INF ? std::max(std::max(norm1, norm2), norm3) :
                        normType == NORM_L1 ? norm1 + norm2 + norm3 :
                        normType == NORM_L2 || normType == NORM_L2SQR ? std::sqrt(norm1 * norm1 + norm2 * norm2 + norm3 * norm3) :
                        0;
                    return normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm;
                }
            }
        }
        else
        {
2526 2527 2528
            typedef IppStatus (CV_STDCALL* ippiNormDiffFuncHint)(const void *, int, const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
            typedef IppStatus (CV_STDCALL* ippiNormDiffFuncNoHint)(const void *, int, const void *, int, IppiSize, Ipp64f *);
            ippiNormDiffFuncHint ippFuncHint =
2529
                normType == NORM_L1 ?
2530 2531 2532
                (type == CV_32FC1 ? (ippiNormDiffFuncHint)ippiNormDiff_L1_32f_C1R :
                type == CV_32FC3 ? (ippiNormDiffFuncHint)ippiNormDiff_L1_32f_C3R :
                type == CV_32FC4 ? (ippiNormDiffFuncHint)ippiNormDiff_L1_32f_C4R :
2533 2534
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2535 2536 2537
                (type == CV_32FC1 ? (ippiNormDiffFuncHint)ippiNormDiff_L2_32f_C1R :
                type == CV_32FC3 ? (ippiNormDiffFuncHint)ippiNormDiff_L2_32f_C3R :
                type == CV_32FC4 ? (ippiNormDiffFuncHint)ippiNormDiff_L2_32f_C4R :
2538
                0) : 0;
2539
            ippiNormDiffFuncNoHint ippFuncNoHint =
2540
                normType == NORM_INF ?
2541 2542 2543 2544 2545 2546 2547
                (type == CV_8UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_8u_C1R :
                type == CV_8UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_8u_C3R :
                type == CV_8UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_8u_C4R :
                type == CV_16UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16u_C1R :
                type == CV_16UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16u_C3R :
                type == CV_16UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16u_C4R :
                type == CV_16SC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16s_C1R :
2548
#if ((IPP_VERSION_MAJOR >= 8) && (IPP_VERSION_MINOR >= 1)) || (IPP_VERSION_MAJOR > 8)
2549 2550
                type == CV_16SC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16s_C3R : //Aug 2013: problem in IPP 7.1, 8.0 : -32768
                type == CV_16SC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16s_C4R : //Aug 2013: problem in IPP 7.1, 8.0 : -32768
2551
#endif
2552 2553 2554
                type == CV_32FC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_32f_C1R :
                type == CV_32FC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_32f_C3R :
                type == CV_32FC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_32f_C4R :
2555 2556
                0) :
                normType == NORM_L1 ?
2557 2558 2559 2560 2561 2562 2563 2564 2565
                (type == CV_8UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_8u_C1R :
                type == CV_8UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_8u_C3R :
                type == CV_8UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_8u_C4R :
                type == CV_16UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16u_C1R :
                type == CV_16UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16u_C3R :
                type == CV_16UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16u_C4R :
                type == CV_16SC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16s_C1R :
                type == CV_16SC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16s_C3R :
                type == CV_16SC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16s_C4R :
2566 2567
                0) :
                normType == NORM_L2 || normType == NORM_L2SQR ?
2568 2569 2570 2571 2572 2573 2574 2575 2576
                (type == CV_8UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_8u_C1R :
                type == CV_8UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_8u_C3R :
                type == CV_8UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_8u_C4R :
                type == CV_16UC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16u_C1R :
                type == CV_16UC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16u_C3R :
                type == CV_16UC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16u_C4R :
                type == CV_16SC1 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16s_C1R :
                type == CV_16SC3 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16s_C3R :
                type == CV_16SC4 ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16s_C4R :
2577
                0) : 0;
2578 2579 2580
            // Make sure only zero or one version of the function pointer is valid
            CV_Assert(!ippFuncHint || !ippFuncNoHint);
            if( ippFuncHint || ippFuncNoHint )
2581 2582
            {
                Ipp64f norm_array[4];
2583 2584 2585
                IppStatus ret = ippFuncHint ? ippFuncHint(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], sz, norm_array, ippAlgHintAccurate) :
                                ippFuncNoHint(src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], sz, norm_array);
                if( ret >= 0 )
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
                {
                    Ipp64f norm = (normType == NORM_L2 || normType == NORM_L2SQR) ? norm_array[0] * norm_array[0] : norm_array[0];
                    for( int i = 1; i < src1.channels(); i++ )
                    {
                        norm =
                            normType == NORM_INF ? std::max(norm, norm_array[i]) :
                            normType == NORM_L1 ? norm + norm_array[i] :
                            normType == NORM_L2 || normType == NORM_L2SQR ? norm + norm_array[i] * norm_array[i] :
                            0;
                    }
                    return normType == NORM_L2 ? (double)std::sqrt(norm) : (double)norm;
                }
            }
        }
    }
#endif

V
Vadim Pisarevsky 已提交
2603
    if( src1.isContinuous() && src2.isContinuous() && mask.empty() )
V
Vadim Pisarevsky 已提交
2604
    {
2605 2606
        size_t len = src1.total()*src1.channels();
        if( len == (size_t)(int)len )
V
Vadim Pisarevsky 已提交
2607
        {
V
Vadim Pisarevsky 已提交
2608
            if( src1.depth() == CV_32F )
2609
            {
V
Vadim Pisarevsky 已提交
2610 2611
                const float* data1 = src1.ptr<float>();
                const float* data2 = src2.ptr<float>();
2612

V
Vadim Pisarevsky 已提交
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
                if( normType == NORM_L2 )
                {
                    double result = 0;
                    GET_OPTIMIZED(normDiffL2_32f)(data1, data2, 0, &result, (int)len, 1);
                    return std::sqrt(result);
                }
                if( normType == NORM_L2SQR )
                {
                    double result = 0;
                    GET_OPTIMIZED(normDiffL2_32f)(data1, data2, 0, &result, (int)len, 1);
                    return result;
                }
                if( normType == NORM_L1 )
                {
                    double result = 0;
                    GET_OPTIMIZED(normDiffL1_32f)(data1, data2, 0, &result, (int)len, 1);
                    return result;
                }
                if( normType == NORM_INF )
                {
                    float result = 0;
                    GET_OPTIMIZED(normDiffInf_32f)(data1, data2, 0, &result, (int)len, 1);
                    return result;
                }
2637
            }
V
Vadim Pisarevsky 已提交
2638 2639
        }
    }
2640

2641
    CV_Assert( mask.empty() || mask.type() == CV_8U );
2642

V
Vadim Pisarevsky 已提交
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
    if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
    {
        if( !mask.empty() )
        {
            Mat temp;
            bitwise_xor(src1, src2, temp);
            bitwise_and(temp, mask, temp);
            return norm(temp, normType);
        }
        int cellSize = normType == NORM_HAMMING ? 1 : 2;
2653

V
Vadim Pisarevsky 已提交
2654 2655 2656 2657 2658
        const Mat* arrays[] = {&src1, &src2, 0};
        uchar* ptrs[2];
        NAryMatIterator it(arrays, ptrs);
        int total = (int)it.size;
        int result = 0;
2659

V
Vadim Pisarevsky 已提交
2660 2661
        for( size_t i = 0; i < it.nplanes; i++, ++it )
            result += normHamming(ptrs[0], ptrs[1], total, cellSize);
2662

V
Vadim Pisarevsky 已提交
2663 2664
        return result;
    }
2665

2666
    NormDiffFunc func = getNormDiffFunc(normType >> 1, depth);
2667
    CV_Assert( func != 0 );
2668

2669 2670
    const Mat* arrays[] = {&src1, &src2, &mask, 0};
    uchar* ptrs[3];
2671 2672 2673 2674 2675 2676 2677 2678 2679
    union
    {
        double d;
        float f;
        int i;
        unsigned u;
    }
    result;
    result.d = 0;
2680 2681 2682
    NAryMatIterator it(arrays, ptrs);
    int j, total = (int)it.size, blockSize = total, intSumBlockSize = 0, count = 0;
    bool blockSum = (normType == NORM_L1 && depth <= CV_16S) ||
V
Vadim Pisarevsky 已提交
2683
            ((normType == NORM_L2 || normType == NORM_L2SQR) && depth <= CV_8S);
2684 2685
    unsigned isum = 0;
    unsigned *ibuf = &result.u;
2686
    size_t esz = 0;
2687

2688
    if( blockSum )
V
Vadim Pisarevsky 已提交
2689
    {
2690 2691 2692 2693
        intSumBlockSize = normType == NORM_L1 && depth <= CV_8S ? (1 << 23) : (1 << 15);
        blockSize = std::min(blockSize, intSumBlockSize);
        ibuf = &isum;
        esz = src1.elemSize();
V
Vadim Pisarevsky 已提交
2694
    }
2695

2696
    for( size_t i = 0; i < it.nplanes; i++, ++it )
V
Vadim Pisarevsky 已提交
2697
    {
2698
        for( j = 0; j < total; j += blockSize )
V
Vadim Pisarevsky 已提交
2699
        {
2700 2701 2702 2703 2704
            int bsz = std::min(total - j, blockSize);
            func( ptrs[0], ptrs[1], ptrs[2], (uchar*)ibuf, bsz, cn );
            count += bsz;
            if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) )
            {
2705
                result.d += isum;
2706 2707 2708 2709 2710 2711 2712
                isum = 0;
                count = 0;
            }
            ptrs[0] += bsz*esz;
            ptrs[1] += bsz*esz;
            if( ptrs[2] )
                ptrs[2] += bsz;
V
Vadim Pisarevsky 已提交
2713 2714
        }
    }
2715

2716
    if( normType == NORM_INF )
V
Vadim Pisarevsky 已提交
2717
    {
2718 2719 2720
        if( depth == CV_64F )
            ;
        else if( depth == CV_32F )
2721
            result.d = result.f;
2722
        else
2723
            result.d = result.u;
V
Vadim Pisarevsky 已提交
2724
    }
2725
    else if( normType == NORM_L2 )
2726
        result.d = std::sqrt(result.d);
2727

2728
    return result.d;
2729 2730 2731
}


2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
///////////////////////////////////// batch distance ///////////////////////////////////////

namespace cv
{

template<typename _Tp, typename _Rt>
void batchDistL1_(const _Tp* src1, const _Tp* src2, size_t step2,
                  int nvecs, int len, _Rt* dist, const uchar* mask)
{
    step2 /= sizeof(src2[0]);
    if( !mask )
    {
        for( int i = 0; i < nvecs; i++ )
            dist[i] = normL1<_Tp, _Rt>(src1, src2 + step2*i, len);
    }
    else
    {
        _Rt val0 = std::numeric_limits<_Rt>::max();
        for( int i = 0; i < nvecs; i++ )
            dist[i] = mask[i] ? normL1<_Tp, _Rt>(src1, src2 + step2*i, len) : val0;
    }
}

template<typename _Tp, typename _Rt>
void batchDistL2Sqr_(const _Tp* src1, const _Tp* src2, size_t step2,
                     int nvecs, int len, _Rt* dist, const uchar* mask)
{
    step2 /= sizeof(src2[0]);
    if( !mask )
    {
        for( int i = 0; i < nvecs; i++ )
            dist[i] = normL2Sqr<_Tp, _Rt>(src1, src2 + step2*i, len);
    }
    else
    {
        _Rt val0 = std::numeric_limits<_Rt>::max();
        for( int i = 0; i < nvecs; i++ )
            dist[i] = mask[i] ? normL2Sqr<_Tp, _Rt>(src1, src2 + step2*i, len) : val0;
    }
}

template<typename _Tp, typename _Rt>
void batchDistL2_(const _Tp* src1, const _Tp* src2, size_t step2,
                  int nvecs, int len, _Rt* dist, const uchar* mask)
{
    step2 /= sizeof(src2[0]);
    if( !mask )
    {
        for( int i = 0; i < nvecs; i++ )
            dist[i] = std::sqrt(normL2Sqr<_Tp, _Rt>(src1, src2 + step2*i, len));
    }
    else
    {
        _Rt val0 = std::numeric_limits<_Rt>::max();
        for( int i = 0; i < nvecs; i++ )
            dist[i] = mask[i] ? std::sqrt(normL2Sqr<_Tp, _Rt>(src1, src2 + step2*i, len)) : val0;
    }
}

static void batchDistHamming(const uchar* src1, const uchar* src2, size_t step2,
                             int nvecs, int len, int* dist, const uchar* mask)
{
    step2 /= sizeof(src2[0]);
    if( !mask )
    {
        for( int i = 0; i < nvecs; i++ )
            dist[i] = normHamming(src1, src2 + step2*i, len);
    }
    else
    {
        int val0 = INT_MAX;
        for( int i = 0; i < nvecs; i++ )
            dist[i] = mask[i] ? normHamming(src1, src2 + step2*i, len) : val0;
    }
}

static void batchDistHamming2(const uchar* src1, const uchar* src2, size_t step2,
                              int nvecs, int len, int* dist, const uchar* mask)
{
    step2 /= sizeof(src2[0]);
    if( !mask )
    {
        for( int i = 0; i < nvecs; i++ )
            dist[i] = normHamming(src1, src2 + step2*i, len, 2);
    }
    else
    {
        int val0 = INT_MAX;
        for( int i = 0; i < nvecs; i++ )
            dist[i] = mask[i] ? normHamming(src1, src2 + step2*i, len, 2) : val0;
    }
}

static void batchDistL1_8u32s(const uchar* src1, const uchar* src2, size_t step2,
                               int nvecs, int len, int* dist, const uchar* mask)
{
    batchDistL1_<uchar, int>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL1_8u32f(const uchar* src1, const uchar* src2, size_t step2,
                               int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL1_<uchar, float>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL2Sqr_8u32s(const uchar* src1, const uchar* src2, size_t step2,
                                  int nvecs, int len, int* dist, const uchar* mask)
{
    batchDistL2Sqr_<uchar, int>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL2Sqr_8u32f(const uchar* src1, const uchar* src2, size_t step2,
                                  int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL2Sqr_<uchar, float>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL2_8u32f(const uchar* src1, const uchar* src2, size_t step2,
                               int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL2_<uchar, float>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL1_32f(const float* src1, const float* src2, size_t step2,
                             int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL1_<float, float>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL2Sqr_32f(const float* src1, const float* src2, size_t step2,
                                int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL2Sqr_<float, float>(src1, src2, step2, nvecs, len, dist, mask);
}

static void batchDistL2_32f(const float* src1, const float* src2, size_t step2,
                             int nvecs, int len, float* dist, const uchar* mask)
{
    batchDistL2_<float, float>(src1, src2, step2, nvecs, len, dist, mask);
}

typedef void (*BatchDistFunc)(const uchar* src1, const uchar* src2, size_t step2,
                              int nvecs, int len, uchar* dist, const uchar* mask);

2876

2877
struct BatchDistInvoker : public ParallelLoopBody
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
{
    BatchDistInvoker( const Mat& _src1, const Mat& _src2,
                      Mat& _dist, Mat& _nidx, int _K,
                      const Mat& _mask, int _update,
                      BatchDistFunc _func)
    {
        src1 = &_src1;
        src2 = &_src2;
        dist = &_dist;
        nidx = &_nidx;
        K = _K;
        mask = &_mask;
        update = _update;
        func = _func;
    }
2893

2894
    void operator()(const Range& range) const
2895 2896 2897
    {
        AutoBuffer<int> buf(src2->rows);
        int* bufptr = buf;
2898

2899
        for( int i = range.start; i < range.end; i++ )
2900 2901 2902
        {
            func(src1->ptr(i), src2->ptr(), src2->step, src2->rows, src2->cols,
                 K > 0 ? (uchar*)bufptr : dist->ptr(i), mask->data ? mask->ptr(i) : 0);
2903

2904 2905 2906 2907 2908 2909
            if( K > 0 )
            {
                int* nidxptr = nidx->ptr<int>(i);
                // since positive float's can be compared just like int's,
                // we handle both CV_32S and CV_32F cases with a single branch
                int* distptr = (int*)dist->ptr(i);
2910

2911
                int j, k;
2912

2913 2914 2915
                for( j = 0; j < src2->rows; j++ )
                {
                    int d = bufptr[j];
2916
                    if( d < distptr[K-1] )
2917
                    {
2918
                        for( k = K-2; k >= 0 && distptr[k] > d; k-- )
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
                        {
                            nidxptr[k+1] = nidxptr[k];
                            distptr[k+1] = distptr[k];
                        }
                        nidxptr[k+1] = j + update;
                        distptr[k+1] = d;
                    }
                }
            }
        }
    }
2930

2931 2932 2933 2934 2935 2936 2937 2938 2939
    const Mat *src1;
    const Mat *src2;
    Mat *dist;
    Mat *nidx;
    const Mat *mask;
    int K;
    int update;
    BatchDistFunc func;
};
2940

2941
}
2942

2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
void cv::batchDistance( InputArray _src1, InputArray _src2,
                        OutputArray _dist, int dtype, OutputArray _nidx,
                        int normType, int K, InputArray _mask,
                        int update, bool crosscheck )
{
    Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();
    int type = src1.type();
    CV_Assert( type == src2.type() && src1.cols == src2.cols &&
               (type == CV_32F || type == CV_8U));
    CV_Assert( _nidx.needed() == (K > 0) );
2953

2954 2955 2956 2957 2958 2959 2960
    if( dtype == -1 )
    {
        dtype = normType == NORM_HAMMING || normType == NORM_HAMMING2 ? CV_32S : CV_32F;
    }
    CV_Assert( (type == CV_8U && dtype == CV_32S) || dtype == CV_32F);

    K = std::min(K, src2.rows);
2961

2962 2963 2964 2965 2966 2967 2968
    _dist.create(src1.rows, (K > 0 ? K : src2.rows), dtype);
    Mat dist = _dist.getMat(), nidx;
    if( _nidx.needed() )
    {
        _nidx.create(dist.size(), CV_32S);
        nidx = _nidx.getMat();
    }
2969

2970 2971 2972 2973 2974
    if( update == 0 && K > 0 )
    {
        dist = Scalar::all(dtype == CV_32S ? (double)INT_MAX : (double)FLT_MAX);
        nidx = Scalar::all(-1);
    }
2975

2976 2977 2978 2979 2980
    if( crosscheck )
    {
        CV_Assert( K == 1 && update == 0 && mask.empty() );
        Mat tdist, tidx;
        batchDistance(src2, src1, tdist, dtype, tidx, normType, K, mask, 0, false);
2981

2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
        // if an idx-th element from src1 appeared to be the nearest to i-th element of src2,
        // we update the minimum mutual distance between idx-th element of src1 and the whole src2 set.
        // As a result, if nidx[idx] = i*, it means that idx-th element of src1 is the nearest
        // to i*-th element of src2 and i*-th element of src2 is the closest to idx-th element of src1.
        // If nidx[idx] = -1, it means that there is no such ideal couple for it in src2.
        // This O(N) procedure is called cross-check and it helps to eliminate some false matches.
        if( dtype == CV_32S )
        {
            for( int i = 0; i < tdist.rows; i++ )
            {
                int idx = tidx.at<int>(i);
                int d = tdist.at<int>(i), d0 = dist.at<int>(idx);
                if( d < d0 )
                {
2996
                    dist.at<int>(idx) = d;
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
                    nidx.at<int>(idx) = i + update;
                }
            }
        }
        else
        {
            for( int i = 0; i < tdist.rows; i++ )
            {
                int idx = tidx.at<int>(i);
                float d = tdist.at<float>(i), d0 = dist.at<float>(idx);
                if( d < d0 )
                {
3009
                    dist.at<float>(idx) = d;
3010 3011 3012 3013 3014 3015
                    nidx.at<int>(idx) = i + update;
                }
            }
        }
        return;
    }
3016

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
    BatchDistFunc func = 0;
    if( type == CV_8U )
    {
        if( normType == NORM_L1 && dtype == CV_32S )
            func = (BatchDistFunc)batchDistL1_8u32s;
        else if( normType == NORM_L1 && dtype == CV_32F )
            func = (BatchDistFunc)batchDistL1_8u32f;
        else if( normType == NORM_L2SQR && dtype == CV_32S )
            func = (BatchDistFunc)batchDistL2Sqr_8u32s;
        else if( normType == NORM_L2SQR && dtype == CV_32F )
            func = (BatchDistFunc)batchDistL2Sqr_8u32f;
        else if( normType == NORM_L2 && dtype == CV_32F )
            func = (BatchDistFunc)batchDistL2_8u32f;
        else if( normType == NORM_HAMMING && dtype == CV_32S )
            func = (BatchDistFunc)batchDistHamming;
        else if( normType == NORM_HAMMING2 && dtype == CV_32S )
            func = (BatchDistFunc)batchDistHamming2;
    }
    else if( type == CV_32F && dtype == CV_32F )
    {
        if( normType == NORM_L1 )
            func = (BatchDistFunc)batchDistL1_32f;
        else if( normType == NORM_L2SQR )
            func = (BatchDistFunc)batchDistL2Sqr_32f;
        else if( normType == NORM_L2 )
            func = (BatchDistFunc)batchDistL2_32f;
    }
3044

3045 3046 3047 3048
    if( func == 0 )
        CV_Error_(CV_StsUnsupportedFormat,
                  ("The combination of type=%d, dtype=%d and normType=%d is not supported",
                   type, dtype, normType));
3049

3050 3051
    parallel_for_(Range(0, src1.rows),
                  BatchDistInvoker(src1, src2, dist, nidx, K, mask, update, func));
3052 3053 3054
}


3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
void cv::findNonZero( InputArray _src, OutputArray _idx )
{
    Mat src = _src.getMat();
    CV_Assert( src.type() == CV_8UC1 );
    int n = countNonZero(src);
    if( _idx.kind() == _InputArray::MAT && !_idx.getMatRef().isContinuous() )
        _idx.release();
    _idx.create(n, 1, CV_32SC2);
    Mat idx = _idx.getMat();
    CV_Assert(idx.isContinuous());
    Point* idx_ptr = (Point*)idx.data;
3066

3067 3068 3069 3070 3071 3072 3073 3074 3075
    for( int i = 0; i < src.rows; i++ )
    {
        const uchar* bin_ptr = src.ptr(i);
        for( int j = 0; j < src.cols; j++ )
            if( bin_ptr[j] )
                *idx_ptr++ = Point(j, i);
    }
}

3076 3077
double cv::PSNR(InputArray _src1, InputArray _src2)
{
3078 3079
    CV_Assert( _src1.depth() == CV_8U );
    double diff = std::sqrt(norm(_src1, _src2, NORM_L2SQR)/(_src1.total()*_src1.channels()));
3080 3081 3082
    return 20*log10(255./(diff+DBL_EPSILON));
}

3083

3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
CV_IMPL CvScalar cvSum( const CvArr* srcarr )
{
    cv::Scalar sum = cv::sum(cv::cvarrToMat(srcarr, false, true, 1));
    if( CV_IS_IMAGE(srcarr) )
    {
        int coi = cvGetImageCOI((IplImage*)srcarr);
        if( coi )
        {
            CV_Assert( 0 < coi && coi <= 4 );
            sum = cv::Scalar(sum[coi-1]);
        }
    }
    return sum;
}

CV_IMPL int cvCountNonZero( const CvArr* imgarr )
{
    cv::Mat img = cv::cvarrToMat(imgarr, false, true, 1);
    if( img.channels() > 1 )
        cv::extractImageCOI(imgarr, img);
    return countNonZero(img);
}


CV_IMPL  CvScalar
cvAvg( const void* imgarr, const void* maskarr )
{
    cv::Mat img = cv::cvarrToMat(imgarr, false, true, 1);
    cv::Scalar mean = !maskarr ? cv::mean(img) : cv::mean(img, cv::cvarrToMat(maskarr));
    if( CV_IS_IMAGE(imgarr) )
    {
        int coi = cvGetImageCOI((IplImage*)imgarr);
        if( coi )
        {
            CV_Assert( 0 < coi && coi <= 4 );
            mean = cv::Scalar(mean[coi-1]);
        }
    }
    return mean;
}


CV_IMPL  void
cvAvgSdv( const CvArr* imgarr, CvScalar* _mean, CvScalar* _sdv, const void* maskarr )
{
    cv::Scalar mean, sdv;

    cv::Mat mask;
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);

    cv::meanStdDev(cv::cvarrToMat(imgarr, false, true, 1), mean, sdv, mask );

    if( CV_IS_IMAGE(imgarr) )
    {
        int coi = cvGetImageCOI((IplImage*)imgarr);
        if( coi )
        {
            CV_Assert( 0 < coi && coi <= 4 );
            mean = cv::Scalar(mean[coi-1]);
            sdv = cv::Scalar(sdv[coi-1]);
        }
    }

    if( _mean )
        *(cv::Scalar*)_mean = mean;
    if( _sdv )
        *(cv::Scalar*)_sdv = sdv;
}


CV_IMPL void
cvMinMaxLoc( const void* imgarr, double* _minVal, double* _maxVal,
             CvPoint* _minLoc, CvPoint* _maxLoc, const void* maskarr )
{
    cv::Mat mask, img = cv::cvarrToMat(imgarr, false, true, 1);
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
    if( img.channels() > 1 )
        cv::extractImageCOI(imgarr, img);

    cv::minMaxLoc( img, _minVal, _maxVal,
3166
                   (cv::Point*)_minLoc, (cv::Point*)_maxLoc, mask );
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
}


CV_IMPL  double
cvNorm( const void* imgA, const void* imgB, int normType, const void* maskarr )
{
    cv::Mat a, mask;
    if( !imgA )
    {
        imgA = imgB;
        imgB = 0;
    }

    a = cv::cvarrToMat(imgA, false, true, 1);
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);

    if( a.channels() > 1 && CV_IS_IMAGE(imgA) && cvGetImageCOI((const IplImage*)imgA) > 0 )
        cv::extractImageCOI(imgA, a);

    if( !imgB )
        return !maskarr ? cv::norm(a, normType) : cv::norm(a, normType, mask);

    cv::Mat b = cv::cvarrToMat(imgB, false, true, 1);
    if( b.channels() > 1 && CV_IS_IMAGE(imgB) && cvGetImageCOI((const IplImage*)imgB) > 0 )
        cv::extractImageCOI(imgB, b);

    return !maskarr ? cv::norm(a, b, normType) : cv::norm(a, b, normType, mask);
3195
}