arithm.cpp 100.5 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 44
// 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*/

/* ////////////////////////////////////////////////////////////////////
//
45
//  Arithmetic and logical operations: +, -, *, /, &, |, ^, ~, abs ...
46 47 48 49 50 51 52 53
//
// */

#include "precomp.hpp"

namespace cv
{

54 55 56 57 58
#if ARITHM_USE_IPP
struct IPPArithmInitializer
{
    IPPArithmInitializer(void)
    {
59
        ippStaticInit();
60 61
    }
};
62

63 64
IPPArithmInitializer ippArithmInitializer;
#endif
65

66
struct NOP {};
67

68 69
template<typename T, class Op, class Op8>
void vBinOp8(const T* src1, size_t step1, const T* src2, size_t step2, T* dst, size_t step, Size sz)
70
{
71
#if CV_SSE2
72
    Op8 op8;
73
#endif
74
    Op op;
75

76 77 78
    for( ; sz.height--; src1 += step1/sizeof(src1[0]),
                        src2 += step2/sizeof(src2[0]),
                        dst += step/sizeof(dst[0]) )
79 80
    {
        int x = 0;
81

82 83
    #if CV_SSE2
        if( USE_SSE2 )
84
        {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
            for( ; x <= sz.width - 32; x += 32 )
            {
                __m128i r0 = _mm_loadu_si128((const __m128i*)(src1 + x));
                __m128i r1 = _mm_loadu_si128((const __m128i*)(src1 + x + 16));
                r0 = op8(r0,_mm_loadu_si128((const __m128i*)(src2 + x)));
                r1 = op8(r1,_mm_loadu_si128((const __m128i*)(src2 + x + 16)));
                _mm_storeu_si128((__m128i*)(dst + x), r0);
                _mm_storeu_si128((__m128i*)(dst + x + 16), r1);
            }
            for( ; x <= sz.width - 8; x += 8 )
            {
                __m128i r0 = _mm_loadl_epi64((const __m128i*)(src1 + x));
                r0 = op8(r0,_mm_loadl_epi64((const __m128i*)(src2 + x)));
                _mm_storel_epi64((__m128i*)(dst + x), r0);
            }
100
        }
101
    #endif
V
Victoria Zhislina 已提交
102
#if CV_ENABLE_UNROLLED
103
        for( ; x <= sz.width - 4; x += 4 )
104
        {
105 106 107 108 109 110
            T v0 = op(src1[x], src2[x]);
            T v1 = op(src1[x+1], src2[x+1]);
            dst[x] = v0; dst[x+1] = v1;
            v0 = op(src1[x+2], src2[x+2]);
            v1 = op(src1[x+3], src2[x+3]);
            dst[x+2] = v0; dst[x+3] = v1;
111
        }
V
Victoria Zhislina 已提交
112
#endif
113 114
        for( ; x < sz.width; x++ )
            dst[x] = op(src1[x], src2[x]);
115
    }
116
}
117

118 119 120
template<typename T, class Op, class Op16>
void vBinOp16(const T* src1, size_t step1, const T* src2, size_t step2,
              T* dst, size_t step, Size sz)
121
{
122
#if CV_SSE2
123
    Op16 op16;
124
#endif
125
    Op op;
126

127 128 129
    for( ; sz.height--; src1 += step1/sizeof(src1[0]),
        src2 += step2/sizeof(src2[0]),
        dst += step/sizeof(dst[0]) )
130 131
    {
        int x = 0;
132

133 134
    #if CV_SSE2
        if( USE_SSE2 )
135
        {
136 137 138 139 140 141 142
            for( ; x <= sz.width - 16; x += 16 )
            {
                __m128i r0 = _mm_loadu_si128((const __m128i*)(src1 + x));
                __m128i r1 = _mm_loadu_si128((const __m128i*)(src1 + x + 8));
                r0 = op16(r0,_mm_loadu_si128((const __m128i*)(src2 + x)));
                r1 = op16(r1,_mm_loadu_si128((const __m128i*)(src2 + x + 8)));
                _mm_storeu_si128((__m128i*)(dst + x), r0);
143
                _mm_storeu_si128((__m128i*)(dst + x + 8), r1);
144 145 146 147 148 149 150
            }
            for( ; x <= sz.width - 4; x += 4 )
            {
                __m128i r0 = _mm_loadl_epi64((const __m128i*)(src1 + x));
                r0 = op16(r0,_mm_loadl_epi64((const __m128i*)(src2 + x)));
                _mm_storel_epi64((__m128i*)(dst + x), r0);
            }
151
        }
152 153
        else
    #endif
154

155
        for( ; x <= sz.width - 4; x += 4 )
156
        {
157 158 159 160 161 162
            T v0 = op(src1[x], src2[x]);
            T v1 = op(src1[x+1], src2[x+1]);
            dst[x] = v0; dst[x+1] = v1;
            v0 = op(src1[x+2], src2[x+2]);
            v1 = op(src1[x+3], src2[x+3]);
            dst[x+2] = v0; dst[x+3] = v1;
163
        }
164

165 166
        for( ; x < sz.width; x++ )
            dst[x] = op(src1[x], src2[x]);
167
    }
168
}
169

170

171 172 173
template<class Op, class Op32>
void vBinOp32s(const int* src1, size_t step1, const int* src2, size_t step2,
               int* dst, size_t step, Size sz)
174
{
175
#if CV_SSE2
176
    Op32 op32;
177
#endif
178
    Op op;
179

180 181 182
    for( ; sz.height--; src1 += step1/sizeof(src1[0]),
        src2 += step2/sizeof(src2[0]),
        dst += step/sizeof(dst[0]) )
183 184
    {
        int x = 0;
185

186 187 188 189 190 191 192 193 194 195 196
#if CV_SSE2
        if( USE_SSE2 )
        {
            if( (((size_t)src1|(size_t)src2|(size_t)dst)&15) == 0 )
                for( ; x <= sz.width - 8; x += 8 )
                {
                    __m128i r0 = _mm_load_si128((const __m128i*)(src1 + x));
                    __m128i r1 = _mm_load_si128((const __m128i*)(src1 + x + 4));
                    r0 = op32(r0,_mm_load_si128((const __m128i*)(src2 + x)));
                    r1 = op32(r1,_mm_load_si128((const __m128i*)(src2 + x + 4)));
                    _mm_store_si128((__m128i*)(dst + x), r0);
197
                    _mm_store_si128((__m128i*)(dst + x + 4), r1);
198 199 200 201 202 203 204 205 206
                }
            else
                for( ; x <= sz.width - 8; x += 8 )
                {
                    __m128i r0 = _mm_loadu_si128((const __m128i*)(src1 + x));
                    __m128i r1 = _mm_loadu_si128((const __m128i*)(src1 + x + 4));
                    r0 = op32(r0,_mm_loadu_si128((const __m128i*)(src2 + x)));
                    r1 = op32(r1,_mm_loadu_si128((const __m128i*)(src2 + x + 4)));
                    _mm_storeu_si128((__m128i*)(dst + x), r0);
207
                    _mm_storeu_si128((__m128i*)(dst + x + 4), r1);
208 209 210
                }
        }
#endif
V
Victoria Zhislina 已提交
211
#if CV_ENABLE_UNROLLED
212 213 214 215 216 217 218 219 220
        for( ; x <= sz.width - 4; x += 4 )
        {
            int v0 = op(src1[x], src2[x]);
            int v1 = op(src1[x+1], src2[x+1]);
            dst[x] = v0; dst[x+1] = v1;
            v0 = op(src1[x+2], src2[x+2]);
            v1 = op(src1[x+3], src2[x+3]);
            dst[x+2] = v0; dst[x+3] = v1;
        }
V
Victoria Zhislina 已提交
221
#endif
222 223 224 225 226
        for( ; x < sz.width; x++ )
            dst[x] = op(src1[x], src2[x]);
    }
}

227

228 229 230 231
template<class Op, class Op32>
void vBinOp32f(const float* src1, size_t step1, const float* src2, size_t step2,
               float* dst, size_t step, Size sz)
{
232
#if CV_SSE2
233
    Op32 op32;
234
#endif
235
    Op op;
236

237 238 239 240 241
    for( ; sz.height--; src1 += step1/sizeof(src1[0]),
        src2 += step2/sizeof(src2[0]),
        dst += step/sizeof(dst[0]) )
    {
        int x = 0;
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    #if CV_SSE2
        if( USE_SSE2 )
        {
            if( (((size_t)src1|(size_t)src2|(size_t)dst)&15) == 0 )
                for( ; x <= sz.width - 8; x += 8 )
                {
                    __m128 r0 = _mm_load_ps(src1 + x);
                    __m128 r1 = _mm_load_ps(src1 + x + 4);
                    r0 = op32(r0,_mm_load_ps(src2 + x));
                    r1 = op32(r1,_mm_load_ps(src2 + x + 4));
                    _mm_store_ps(dst + x, r0);
                    _mm_store_ps(dst + x + 4, r1);
                }
            else
                for( ; x <= sz.width - 8; x += 8 )
                {
                    __m128 r0 = _mm_loadu_ps(src1 + x);
                    __m128 r1 = _mm_loadu_ps(src1 + x + 4);
                    r0 = op32(r0,_mm_loadu_ps(src2 + x));
                    r1 = op32(r1,_mm_loadu_ps(src2 + x + 4));
                    _mm_storeu_ps(dst + x, r0);
                    _mm_storeu_ps(dst + x + 4, r1);
                }
        }
    #endif
V
Victoria Zhislina 已提交
268
#if CV_ENABLE_UNROLLED
269 270 271 272 273 274 275 276 277
        for( ; x <= sz.width - 4; x += 4 )
        {
            float v0 = op(src1[x], src2[x]);
            float v1 = op(src1[x+1], src2[x+1]);
            dst[x] = v0; dst[x+1] = v1;
            v0 = op(src1[x+2], src2[x+2]);
            v1 = op(src1[x+3], src2[x+3]);
            dst[x+2] = v0; dst[x+3] = v1;
        }
V
Victoria Zhislina 已提交
278
#endif
279 280 281 282 283 284 285 286 287
        for( ; x < sz.width; x++ )
            dst[x] = op(src1[x], src2[x]);
    }
}

template<class Op, class Op64>
void vBinOp64f(const double* src1, size_t step1, const double* src2, size_t step2,
               double* dst, size_t step, Size sz)
{
288
#if CV_SSE2
289
    Op64 op64;
290
#endif
291
    Op op;
292

293 294 295 296 297
    for( ; sz.height--; src1 += step1/sizeof(src1[0]),
        src2 += step2/sizeof(src2[0]),
        dst += step/sizeof(dst[0]) )
    {
        int x = 0;
298

299 300 301
    #if CV_SSE2
        if( USE_SSE2 && (((size_t)src1|(size_t)src2|(size_t)dst)&15) == 0 )
            for( ; x <= sz.width - 4; x += 4 )
302
            {
303 304 305 306 307 308
                __m128d r0 = _mm_load_pd(src1 + x);
                __m128d r1 = _mm_load_pd(src1 + x + 2);
                r0 = op64(r0,_mm_load_pd(src2 + x));
                r1 = op64(r1,_mm_load_pd(src2 + x + 2));
                _mm_store_pd(dst + x, r0);
                _mm_store_pd(dst + x + 2, r1);
309 310
            }
        else
311 312 313 314 315 316 317 318 319 320
    #endif
        for( ; x <= sz.width - 4; x += 4 )
        {
            double v0 = op(src1[x], src2[x]);
            double v1 = op(src1[x+1], src2[x+1]);
            dst[x] = v0; dst[x+1] = v1;
            v0 = op(src1[x+2], src2[x+2]);
            v1 = op(src1[x+3], src2[x+3]);
            dst[x+2] = v0; dst[x+3] = v1;
        }
321

322 323
        for( ; x < sz.width; x++ )
            dst[x] = op(src1[x], src2[x]);
324
    }
325
}
326

327
#if CV_SSE2
328

329 330 331 332 333 334 335 336 337
struct _VAdd8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_adds_epu8(a,b); }};
struct _VSub8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_subs_epu8(a,b); }};
struct _VMin8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_min_epu8(a,b); }};
struct _VMax8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_max_epu8(a,b); }};
struct _VAbsDiff8u
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    { return _mm_add_epi8(_mm_subs_epu8(a,b),_mm_subs_epu8(b,a)); }
};
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

struct _VAdd8s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_adds_epi8(a,b); }};
struct _VSub8s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_subs_epi8(a,b); }};
struct _VMin8s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i m = _mm_cmpgt_epi8(a, b);
        return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(a, b), m));
    }
};
struct _VMax8s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i m = _mm_cmpgt_epi8(b, a);
        return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(a, b), m));
    }
};
struct _VAbsDiff8s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i d = _mm_subs_epi8(a, b);
        __m128i m = _mm_cmpgt_epi8(b, a);
        return _mm_subs_epi8(_mm_xor_si128(d, m), m);
    }
};

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
struct _VAdd16u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_adds_epu16(a,b); }};
struct _VSub16u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_subs_epu16(a,b); }};
struct _VMin16u
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    { return _mm_subs_epu16(a,_mm_subs_epu16(a,b)); }
};
struct _VMax16u
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    { return _mm_adds_epu16(_mm_subs_epu16(a,b),b); }
};
struct _VAbsDiff16u
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    { return _mm_add_epi16(_mm_subs_epu16(a,b),_mm_subs_epu16(b,a)); }
};
384

385 386 387 388 389 390 391 392 393 394 395 396
struct _VAdd16s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_adds_epi16(a,b); }};
struct _VSub16s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_subs_epi16(a,b); }};
struct _VMin16s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_min_epi16(a,b); }};
struct _VMax16s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_max_epi16(a,b); }};
struct _VAbsDiff16s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i M = _mm_max_epi16(a,b), m = _mm_min_epi16(a,b);
        return _mm_subs_epi16(M, m);
    }
};
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

struct _VAdd32s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_add_epi32(a,b); }};
struct _VSub32s { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_sub_epi32(a,b); }};
struct _VMin32s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i m = _mm_cmpgt_epi32(a, b);
        return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(a, b), m));
    }
};
struct _VMax32s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i m = _mm_cmpgt_epi32(b, a);
        return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(a, b), m));
    }
};
struct _VAbsDiff32s
{
    __m128i operator()(const __m128i& a, const __m128i& b) const
    {
        __m128i d = _mm_sub_epi32(a, b);
        __m128i m = _mm_cmpgt_epi32(b, a);
        return _mm_sub_epi32(_mm_xor_si128(d, m), m);
    }
424
};
425

426 427 428 429 430 431 432 433 434 435 436 437 438
struct _VAdd32f { __m128 operator()(const __m128& a, const __m128& b) const { return _mm_add_ps(a,b); }};
struct _VSub32f { __m128 operator()(const __m128& a, const __m128& b) const { return _mm_sub_ps(a,b); }};
struct _VMin32f { __m128 operator()(const __m128& a, const __m128& b) const { return _mm_min_ps(a,b); }};
struct _VMax32f { __m128 operator()(const __m128& a, const __m128& b) const { return _mm_max_ps(a,b); }};
static int CV_DECL_ALIGNED(16) v32f_absmask[] = { 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff };
struct _VAbsDiff32f
{
    __m128 operator()(const __m128& a, const __m128& b) const
    {
        return _mm_and_ps(_mm_sub_ps(a,b), *(const __m128*)v32f_absmask);
    }
};

439 440 441 442
struct _VAdd64f { __m128d operator()(const __m128d& a, const __m128d& b) const { return _mm_add_pd(a,b); }};
struct _VSub64f { __m128d operator()(const __m128d& a, const __m128d& b) const { return _mm_sub_pd(a,b); }};
struct _VMin64f { __m128d operator()(const __m128d& a, const __m128d& b) const { return _mm_min_pd(a,b); }};
struct _VMax64f { __m128d operator()(const __m128d& a, const __m128d& b) const { return _mm_max_pd(a,b); }};
443

444 445 446 447 448 449 450
static int CV_DECL_ALIGNED(16) v64f_absmask[] = { 0xffffffff, 0x7fffffff, 0xffffffff, 0x7fffffff };
struct _VAbsDiff64f
{
    __m128d operator()(const __m128d& a, const __m128d& b) const
    {
        return _mm_and_pd(_mm_sub_pd(a,b), *(const __m128d*)v64f_absmask);
    }
451 452
};

453
struct _VAnd8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_and_si128(a,b); }};
454
struct _VOr8u  { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_or_si128(a,b); }};
455
struct _VXor8u { __m128i operator()(const __m128i& a, const __m128i& b) const { return _mm_xor_si128(a,b); }};
456
struct _VNot8u { __m128i operator()(const __m128i& a, const __m128i&) const { return _mm_xor_si128(_mm_set1_epi32(-1),a); }};
457

458
#endif
459

460 461
#if CV_SSE2
#define IF_SIMD(op) op
462
#else
463
#define IF_SIMD(op) NOP
464
#endif
465

466 467 468 469
template<> inline uchar OpAdd<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a + b); }
template<> inline uchar OpSub<uchar>::operator ()(uchar a, uchar b) const
{ return CV_FAST_CAST_8U(a - b); }
470

471
template<typename T> struct OpAbsDiff
472
{
473 474 475 476
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator()(T a, T b) const { return (T)std::abs(a - b); }
477 478
};

479 480
template<> inline short OpAbsDiff<short>::operator ()(short a, short b) const
{ return saturate_cast<short>(std::abs(a - b)); }
481

482 483
template<> inline schar OpAbsDiff<schar>::operator ()(schar a, schar b) const
{ return saturate_cast<schar>(std::abs(a - b)); }
484

485
template<typename T, typename WT=T> struct OpAbsDiffS
486
{
487 488 489 490
    typedef T type1;
    typedef WT type2;
    typedef T rtype;
    T operator()(T a, WT b) const { return saturate_cast<T>(std::abs(a - b)); }
491 492
};

493
template<typename T> struct OpAnd
494
{
495 496 497 498
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator()( T a, T b ) const { return a & b; }
499 500
};

501
template<typename T> struct OpOr
502
{
503 504 505 506
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator()( T a, T b ) const { return a | b; }
507 508
};

509
template<typename T> struct OpXor
510
{
511 512 513 514
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator()( T a, T b ) const { return a ^ b; }
515 516
};

517
template<typename T> struct OpNot
518
{
519 520 521 522
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator()( T a, T ) const { return ~a; }
523
};
524

525 526 527 528 529
static inline void fixSteps(Size sz, size_t elemSize, size_t& step1, size_t& step2, size_t& step)
{
    if( sz.height == 1 )
        step1 = step2 = step = sz.width*elemSize;
}
530

531 532 533 534 535
static void add8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
536
           ippiAdd_8u_C1RSfs(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz, 0),
537 538
           (vBinOp8<uchar, OpAdd<uchar>, IF_SIMD(_VAdd8u)>(src1, step1, src2, step2, dst, step, sz)));
}
539

540 541 542
static void add8s( const schar* src1, size_t step1,
                   const schar* src2, size_t step2,
                   schar* dst, size_t step, Size sz, void* )
543
{
544 545
    vBinOp8<schar, OpAdd<schar>, IF_SIMD(_VAdd8s)>(src1, step1, src2, step2, dst, step, sz);
}
546

547 548 549
static void add16u( const ushort* src1, size_t step1,
                    const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* )
550
{
551
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
552
           ippiAdd_16u_C1RSfs(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz, 0),
553 554
            (vBinOp16<ushort, OpAdd<ushort>, IF_SIMD(_VAdd16u)>(src1, step1, src2, step2, dst, step, sz)));
}
555

556 557 558
static void add16s( const short* src1, size_t step1,
                    const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* )
559
{
560
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
561
           ippiAdd_16s_C1RSfs(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz, 0),
562 563
           (vBinOp16<short, OpAdd<short>, IF_SIMD(_VAdd16s)>(src1, step1, src2, step2, dst, step, sz)));
}
564

565 566 567
static void add32s( const int* src1, size_t step1,
                    const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* )
568
{
569 570
    vBinOp32s<OpAdd<int>, IF_SIMD(_VAdd32s)>(src1, step1, src2, step2, dst, step, sz);
}
571

572 573 574
static void add32f( const float* src1, size_t step1,
                    const float* src2, size_t step2,
                    float* dst, size_t step, Size sz, void* )
575
{
576
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
577
           ippiAdd_32f_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
578 579
           (vBinOp32f<OpAdd<float>, IF_SIMD(_VAdd32f)>(src1, step1, src2, step2, dst, step, sz)));
}
580

581 582 583
static void add64f( const double* src1, size_t step1,
                    const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* )
584
{
585 586
    vBinOp64f<OpAdd<double>, IF_SIMD(_VAdd64f)>(src1, step1, src2, step2, dst, step, sz);
}
587

588 589 590
static void sub8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
591
{
592
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
593
           ippiSub_8u_C1RSfs(src2, (int)step2, src1, (int)step1, dst, (int)step, (IppiSize&)sz, 0),
594 595
           (vBinOp8<uchar, OpSub<uchar>, IF_SIMD(_VSub8u)>(src1, step1, src2, step2, dst, step, sz)));
}
596

597 598 599
static void sub8s( const schar* src1, size_t step1,
                   const schar* src2, size_t step2,
                   schar* dst, size_t step, Size sz, void* )
600
{
601 602
    vBinOp8<schar, OpSub<schar>, IF_SIMD(_VSub8s)>(src1, step1, src2, step2, dst, step, sz);
}
603

604 605 606
static void sub16u( const ushort* src1, size_t step1,
                    const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* )
607
{
608
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
609
           ippiSub_16u_C1RSfs(src2, (int)step2, src1, (int)step1, dst, (int)step, (IppiSize&)sz, 0),
610 611
           (vBinOp16<ushort, OpSub<ushort>, IF_SIMD(_VSub16u)>(src1, step1, src2, step2, dst, step, sz)));
}
612

613 614 615
static void sub16s( const short* src1, size_t step1,
                    const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* )
616
{
617
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
618
           ippiSub_16s_C1RSfs(src2, (int)step2, src1, (int)step1, dst, (int)step, (IppiSize&)sz, 0),
619 620
           (vBinOp16<short, OpSub<short>, IF_SIMD(_VSub16s)>(src1, step1, src2, step2, dst, step, sz)));
}
621

622 623 624
static void sub32s( const int* src1, size_t step1,
                    const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* )
625
{
626 627
    vBinOp32s<OpSub<int>, IF_SIMD(_VSub32s)>(src1, step1, src2, step2, dst, step, sz);
}
628

629 630 631
static void sub32f( const float* src1, size_t step1,
                   const float* src2, size_t step2,
                   float* dst, size_t step, Size sz, void* )
632
{
633
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
634
           ippiSub_32f_C1R(src2, (int)step2, src1, (int)step1, dst, (int)step, (IppiSize&)sz),
635 636
           (vBinOp32f<OpSub<float>, IF_SIMD(_VSub32f)>(src1, step1, src2, step2, dst, step, sz)));
}
637

638 639 640
static void sub64f( const double* src1, size_t step1,
                    const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* )
641
{
642
    vBinOp64f<OpSub<double>, IF_SIMD(_VSub64f)>(src1, step1, src2, step2, dst, step, sz);
643
}
644

645 646
template<> inline uchar OpMin<uchar>::operator ()(uchar a, uchar b) const { return CV_MIN_8U(a, b); }
template<> inline uchar OpMax<uchar>::operator ()(uchar a, uchar b) const { return CV_MAX_8U(a, b); }
647

648 649 650
static void max8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
651
{
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
#if (ARITHM_USE_IPP == 1)
  {
    uchar* s1 = (uchar*)src1;
    uchar* s2 = (uchar*)src2;
    uchar* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMaxEvery_8u(s1, s2, d, sz.width);
      s1 += step1;
      s2 += step2;
      d  += step;
    }
  }
#else
  vBinOp8<uchar, OpMax<uchar>, IF_SIMD(_VMax8u)>(src1, step1, src2, step2, dst, step, sz);
#endif

//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMaxEvery_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp8<uchar, OpMax<uchar>, IF_SIMD(_VMax8u)>(src1, step1, src2, step2, dst, step, sz)));
673
}
674

675 676 677
static void max8s( const schar* src1, size_t step1,
                   const schar* src2, size_t step2,
                   schar* dst, size_t step, Size sz, void* )
678
{
679 680
    vBinOp8<schar, OpMax<schar>, IF_SIMD(_VMax8s)>(src1, step1, src2, step2, dst, step, sz);
}
681

682 683 684
static void max16u( const ushort* src1, size_t step1,
                    const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* )
685
{
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
#if (ARITHM_USE_IPP == 1)
  {
    ushort* s1 = (ushort*)src1;
    ushort* s2 = (ushort*)src2;
    ushort* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMaxEvery_16u(s1, s2, d, sz.width);
      s1 = (ushort*)((uchar*)s1 + step1);
      s2 = (ushort*)((uchar*)s2 + step2);
      d  = (ushort*)((uchar*)d + step);
    }
  }
#else
  vBinOp16<ushort, OpMax<ushort>, IF_SIMD(_VMax16u)>(src1, step1, src2, step2, dst, step, sz);
#endif

//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMaxEvery_16u_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp16<ushort, OpMax<ushort>, IF_SIMD(_VMax16u)>(src1, step1, src2, step2, dst, step, sz)));
707
}
708

709 710 711
static void max16s( const short* src1, size_t step1,
                    const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* )
712
{
713
    vBinOp16<short, OpMax<short>, IF_SIMD(_VMax16s)>(src1, step1, src2, step2, dst, step, sz);
714
}
715

716 717 718
static void max32s( const int* src1, size_t step1,
                    const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* )
719
{
720 721
    vBinOp32s<OpMax<int>, IF_SIMD(_VMax32s)>(src1, step1, src2, step2, dst, step, sz);
}
722

723 724 725
static void max32f( const float* src1, size_t step1,
                    const float* src2, size_t step2,
                    float* dst, size_t step, Size sz, void* )
726
{
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
#if (ARITHM_USE_IPP == 1)
  {
    float* s1 = (float*)src1;
    float* s2 = (float*)src2;
    float* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMaxEvery_32f(s1, s2, d, sz.width);
      s1 = (float*)((uchar*)s1 + step1);
      s2 = (float*)((uchar*)s2 + step2);
      d  = (float*)((uchar*)d + step);
    }
  }
#else
  vBinOp32f<OpMax<float>, IF_SIMD(_VMax32f)>(src1, step1, src2, step2, dst, step, sz);
#endif
//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMaxEvery_32f_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp32f<OpMax<float>, IF_SIMD(_VMax32f)>(src1, step1, src2, step2, dst, step, sz)));
747
}
748

749 750 751
static void max64f( const double* src1, size_t step1,
                    const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* )
752
{
753 754
    vBinOp64f<OpMax<double>, IF_SIMD(_VMax64f)>(src1, step1, src2, step2, dst, step, sz);
}
755

756 757 758
static void min8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
759
{
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
#if (ARITHM_USE_IPP == 1)
  {
    uchar* s1 = (uchar*)src1;
    uchar* s2 = (uchar*)src2;
    uchar* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMinEvery_8u(s1, s2, d, sz.width);
      s1 += step1;
      s2 += step2;
      d  += step;
    }
  }
#else
  vBinOp8<uchar, OpMin<uchar>, IF_SIMD(_VMin8u)>(src1, step1, src2, step2, dst, step, sz);
#endif

//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMinEvery_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp8<uchar, OpMin<uchar>, IF_SIMD(_VMin8u)>(src1, step1, src2, step2, dst, step, sz)));
781
}
782

783 784 785 786 787 788
static void min8s( const schar* src1, size_t step1,
                   const schar* src2, size_t step2,
                   schar* dst, size_t step, Size sz, void* )
{
    vBinOp8<schar, OpMin<schar>, IF_SIMD(_VMin8s)>(src1, step1, src2, step2, dst, step, sz);
}
789

790 791 792 793
static void min16u( const ushort* src1, size_t step1,
                    const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* )
{
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
#if (ARITHM_USE_IPP == 1)
  {
    ushort* s1 = (ushort*)src1;
    ushort* s2 = (ushort*)src2;
    ushort* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMinEvery_16u(s1, s2, d, sz.width);
      s1 = (ushort*)((uchar*)s1 + step1);
      s2 = (ushort*)((uchar*)s2 + step2);
      d  = (ushort*)((uchar*)d + step);
    }
  }
#else
  vBinOp16<ushort, OpMin<ushort>, IF_SIMD(_VMin16u)>(src1, step1, src2, step2, dst, step, sz);
#endif

//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMinEvery_16u_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp16<ushort, OpMin<ushort>, IF_SIMD(_VMin16u)>(src1, step1, src2, step2, dst, step, sz)));
815
}
816

817 818 819 820
static void min16s( const short* src1, size_t step1,
                    const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* )
{
821
    vBinOp16<short, OpMin<short>, IF_SIMD(_VMin16s)>(src1, step1, src2, step2, dst, step, sz);
822
}
823

824 825 826
static void min32s( const int* src1, size_t step1,
                    const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* )
827
{
828 829
    vBinOp32s<OpMin<int>, IF_SIMD(_VMin32s)>(src1, step1, src2, step2, dst, step, sz);
}
830

831 832 833
static void min32f( const float* src1, size_t step1,
                    const float* src2, size_t step2,
                    float* dst, size_t step, Size sz, void* )
834
{
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
#if (ARITHM_USE_IPP == 1)
  {
    float* s1 = (float*)src1;
    float* s2 = (float*)src2;
    float* d  = dst;
    fixSteps(sz, sizeof(dst[0]), step1, step2, step);
    for(int i = 0; i < sz.height; i++)
    {
      ippsMinEvery_32f(s1, s2, d, sz.width);
      s1 = (float*)((uchar*)s1 + step1);
      s2 = (float*)((uchar*)s2 + step2);
      d  = (float*)((uchar*)d + step);
    }
  }
#else
  vBinOp32f<OpMin<float>, IF_SIMD(_VMin32f)>(src1, step1, src2, step2, dst, step, sz);
#endif
//    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
//           ippiMinEvery_32f_C1R(src1, (int)step1, src2, (int)step2, dst, (IppiSize&)sz),
//           (vBinOp32f<OpMin<float>, IF_SIMD(_VMin32f)>(src1, step1, src2, step2, dst, step, sz)));
855
}
856

857 858 859
static void min64f( const double* src1, size_t step1,
                    const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* )
860
{
861
    vBinOp64f<OpMin<double>, IF_SIMD(_VMin64f)>(src1, step1, src2, step2, dst, step, sz);
862
}
863

864 865 866
static void absdiff8u( const uchar* src1, size_t step1,
                       const uchar* src2, size_t step2,
                       uchar* dst, size_t step, Size sz, void* )
867
{
868
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
869
           ippiAbsDiff_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
870 871
           (vBinOp8<uchar, OpAbsDiff<uchar>, IF_SIMD(_VAbsDiff8u)>(src1, step1, src2, step2, dst, step, sz)));
}
872

873 874 875 876 877 878
static void absdiff8s( const schar* src1, size_t step1,
                       const schar* src2, size_t step2,
                       schar* dst, size_t step, Size sz, void* )
{
    vBinOp8<schar, OpAbsDiff<schar>, IF_SIMD(_VAbsDiff8s)>(src1, step1, src2, step2, dst, step, sz);
}
879

880 881 882 883 884
static void absdiff16u( const ushort* src1, size_t step1,
                        const ushort* src2, size_t step2,
                        ushort* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
885
           ippiAbsDiff_16u_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
886 887
           (vBinOp16<ushort, OpAbsDiff<ushort>, IF_SIMD(_VAbsDiff16u)>(src1, step1, src2, step2, dst, step, sz)));
}
888

889 890 891 892
static void absdiff16s( const short* src1, size_t step1,
                        const short* src2, size_t step2,
                        short* dst, size_t step, Size sz, void* )
{
893
    vBinOp16<short, OpAbsDiff<short>, IF_SIMD(_VAbsDiff16s)>(src1, step1, src2, step2, dst, step, sz);
894
}
895

896 897 898 899 900 901
static void absdiff32s( const int* src1, size_t step1,
                        const int* src2, size_t step2,
                        int* dst, size_t step, Size sz, void* )
{
    vBinOp32s<OpAbsDiff<int>, IF_SIMD(_VAbsDiff32s)>(src1, step1, src2, step2, dst, step, sz);
}
902

903 904 905 906 907
static void absdiff32f( const float* src1, size_t step1,
                        const float* src2, size_t step2,
                        float* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
908
           ippiAbsDiff_32f_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
909 910
           (vBinOp32f<OpAbsDiff<float>, IF_SIMD(_VAbsDiff32f)>(src1, step1, src2, step2, dst, step, sz)));
}
911

912 913 914 915 916
static void absdiff64f( const double* src1, size_t step1,
                        const double* src2, size_t step2,
                        double* dst, size_t step, Size sz, void* )
{
    vBinOp64f<OpAbsDiff<double>, IF_SIMD(_VAbsDiff64f)>(src1, step1, src2, step2, dst, step, sz);
917 918
}

919

920 921 922 923 924
static void and8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
925
           ippiAnd_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
926 927 928 929 930 931 932 933
           (vBinOp8<uchar, OpAnd<uchar>, IF_SIMD(_VAnd8u)>(src1, step1, src2, step2, dst, step, sz)));
}

static void or8u( const uchar* src1, size_t step1,
                  const uchar* src2, size_t step2,
                  uchar* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
934
           ippiOr_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
935 936 937 938 939 940 941 942
           (vBinOp8<uchar, OpOr<uchar>, IF_SIMD(_VOr8u)>(src1, step1, src2, step2, dst, step, sz)));
}

static void xor8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
943
           ippiXor_8u_C1R(src1, (int)step1, src2, (int)step2, dst, (int)step, (IppiSize&)sz),
944
           (vBinOp8<uchar, OpXor<uchar>, IF_SIMD(_VXor8u)>(src1, step1, src2, step2, dst, step, sz)));
945
}
946 947 948 949 950 951

static void not8u( const uchar* src1, size_t step1,
                   const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* )
{
    IF_IPP(fixSteps(sz, sizeof(dst[0]), step1, step2, step);
952
           ippiNot_8u_C1R(src1, (int)step1, dst, (int)step, (IppiSize&)sz),
953 954
           (vBinOp8<uchar, OpNot<uchar>, IF_SIMD(_VNot8u)>(src1, step1, src2, step2, dst, step, sz)));
}
955

956 957 958
/****************************************************************************************\
*                                   logical operations                                   *
\****************************************************************************************/
959

960
void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize )
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
{
    int scn = (int)sc.total(), cn = CV_MAT_CN(buftype);
    size_t esz = CV_ELEM_SIZE(buftype);
    getConvertFunc(sc.depth(), buftype)(sc.data, 0, 0, 0, scbuf, 0, Size(std::min(cn, scn), 1), 0);
    // unroll the scalar
    if( scn < cn )
    {
        CV_Assert( scn == 1 );
        size_t esz1 = CV_ELEM_SIZE1(buftype);
        for( size_t i = esz1; i < esz; i++ )
            scbuf[i] = scbuf[i - esz1];
    }
    for( size_t i = esz; i < blocksize*esz; i++ )
        scbuf[i] = scbuf[i - esz];
}
976

977
static void binary_op(InputArray _src1, InputArray _src2, OutputArray _dst,
978
               InputArray _mask, const BinaryFunc* tab, bool bitwise)
979 980 981 982 983 984
{
    int kind1 = _src1.kind(), kind2 = _src2.kind();
    Mat src1 = _src1.getMat(), src2 = _src2.getMat();
    bool haveMask = !_mask.empty(), haveScalar = false;
    BinaryFunc func;
    int c;
985

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    if( src1.dims <= 2 && src2.dims <= 2 && kind1 == kind2 &&
        src1.size() == src2.size() && src1.type() == src2.type() && !haveMask )
    {
        _dst.create(src1.size(), src1.type());
        Mat dst = _dst.getMat();
        if( bitwise )
        {
            func = *tab;
            c = (int)src1.elemSize();
        }
        else
        {
            func = tab[src1.depth()];
            c = src1.channels();
        }
1001

1002 1003 1004 1005 1006 1007 1008 1009
        Size sz = getContinuousSize(src1, src2, dst);
        size_t len = sz.width*(size_t)c;
        if( len == (size_t)(int)len )
        {
            sz.width = (int)len;
            func(src1.data, src1.step, src2.data, src2.step, dst.data, dst.step, sz, 0);
            return;
        }
1010
    }
1011

1012
    if( (kind1 == _InputArray::MATX) + (kind2 == _InputArray::MATX) == 1 ||
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
        src1.size != src2.size || src1.type() != src2.type() )
    {
        if( checkScalar(src1, src2.type(), kind1, kind2) )
            // src1 is a scalar; swap it with src2
            swap(src1, src2);
        else if( !checkScalar(src2, src1.type(), kind2, kind1) )
            CV_Error( CV_StsUnmatchedSizes,
                      "The operation is neither 'array op array' (where arrays have the same size and type), "
                      "nor 'array op scalar', nor 'scalar op array'" );
        haveScalar = true;
    }
1024

1025 1026 1027 1028 1029
    size_t esz = src1.elemSize();
    size_t blocksize0 = (BLOCK_SIZE + esz-1)/esz;
    int cn = src1.channels();
    BinaryFunc copymask = 0;
    Mat mask;
1030
    bool reallocate = false;
1031

1032 1033 1034 1035 1036 1037
    if( haveMask )
    {
        mask = _mask.getMat();
        CV_Assert( (mask.type() == CV_8UC1 || mask.type() == CV_8SC1) );
        CV_Assert( mask.size == src1.size );
        copymask = getCopyMaskFunc(esz);
1038 1039
        Mat tdst = _dst.getMat();
        reallocate = tdst.size != src1.size || tdst.type() != src1.type();
1040
    }
1041

1042 1043
    AutoBuffer<uchar> _buf;
    uchar *scbuf = 0, *maskbuf = 0;
1044

1045 1046
    _dst.create(src1.dims, src1.size, src1.type());
    Mat dst = _dst.getMat();
1047 1048 1049 1050 1051
    
    // if this is mask operation and dst has been reallocated,
    // we have to 
    if( haveMask && reallocate )
        dst = Scalar::all(0);
1052

1053 1054 1055 1056 1057 1058 1059 1060 1061
    if( bitwise )
    {
        func = *tab;
        c = (int)esz;
    }
    else
    {
        func = tab[src1.depth()];
        c = cn;
1062
    }
1063

1064
    if( !haveScalar )
1065
    {
1066 1067
        const Mat* arrays[] = { &src1, &src2, &dst, &mask, 0 };
        uchar* ptrs[4];
1068

1069 1070
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size, blocksize = total;
1071

1072 1073 1074
        if( blocksize*c > INT_MAX )
            blocksize = INT_MAX/c;
        
1075 1076 1077 1078 1079 1080
        if( haveMask )
        {
            blocksize = std::min(blocksize, blocksize0);
            _buf.allocate(blocksize*esz);
            maskbuf = _buf;
        }
1081

1082
        for( size_t i = 0; i < it.nplanes; i++, ++it )
1083
        {
1084
            for( size_t j = 0; j < total; j += blocksize )
1085
            {
1086
                int bsz = (int)MIN(total - j, blocksize);
1087 1088

                func( ptrs[0], 0, ptrs[1], 0, haveMask ? maskbuf : ptrs[2], 0, Size(bsz*c, 1), 0 );
1089
                if( haveMask )
1090
                {
1091 1092
                    copymask( maskbuf, 0, ptrs[3], 0, ptrs[2], 0, Size(bsz, 1), &esz );
                    ptrs[3] += bsz;
1093
                }
1094

1095 1096
                bsz *= (int)esz;
                ptrs[0] += bsz; ptrs[1] += bsz; ptrs[2] += bsz;
1097 1098
            }
        }
1099 1100 1101 1102 1103
    }
    else
    {
        const Mat* arrays[] = { &src1, &dst, &mask, 0 };
        uchar* ptrs[3];
1104

1105 1106
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size, blocksize = std::min(total, blocksize0);
1107

1108 1109 1110
        _buf.allocate(blocksize*(haveMask ? 2 : 1)*esz + 32);
        scbuf = _buf;
        maskbuf = alignPtr(scbuf + blocksize*esz, 16);
1111

1112
        convertAndUnrollScalar( src2, src1.type(), scbuf, blocksize);
1113

1114
        for( size_t i = 0; i < it.nplanes; i++, ++it )
1115
        {
1116
            for( size_t j = 0; j < total; j += blocksize )
1117
            {
1118
                int bsz = (int)MIN(total - j, blocksize);
1119

1120 1121
                func( ptrs[0], 0, scbuf, 0, haveMask ? maskbuf : ptrs[1], 0, Size(bsz*c, 1), 0 );
                if( haveMask )
1122
                {
1123 1124
                    copymask( maskbuf, 0, ptrs[2], 0, ptrs[1], 0, Size(bsz, 1), &esz );
                    ptrs[2] += bsz;
1125
                }
1126

1127 1128
                bsz *= (int)esz;
                ptrs[0] += bsz; ptrs[1] += bsz;
1129 1130 1131 1132
            }
        }
    }
}
1133

1134
static BinaryFunc maxTab[] =
V
Vadim Pisarevsky 已提交
1135
{
A
Andrey Kamaev 已提交
1136 1137 1138 1139 1140
    (BinaryFunc)GET_OPTIMIZED(max8u), (BinaryFunc)GET_OPTIMIZED(max8s),
    (BinaryFunc)GET_OPTIMIZED(max16u), (BinaryFunc)GET_OPTIMIZED(max16s),
    (BinaryFunc)GET_OPTIMIZED(max32s),
    (BinaryFunc)GET_OPTIMIZED(max32f), (BinaryFunc)max64f,
    0
1141
};
1142

1143 1144
static BinaryFunc minTab[] =
{
A
Andrey Kamaev 已提交
1145 1146 1147 1148 1149
    (BinaryFunc)GET_OPTIMIZED(min8u), (BinaryFunc)GET_OPTIMIZED(min8s),
    (BinaryFunc)GET_OPTIMIZED(min16u), (BinaryFunc)GET_OPTIMIZED(min16s),
    (BinaryFunc)GET_OPTIMIZED(min32s),
    (BinaryFunc)GET_OPTIMIZED(min32f), (BinaryFunc)min64f,
    0
1150
};
1151

V
Vadim Pisarevsky 已提交
1152
}
1153

1154
void cv::bitwise_and(InputArray a, InputArray b, OutputArray c, InputArray mask)
1155
{
A
Andrey Kamaev 已提交
1156
    BinaryFunc f = (BinaryFunc)GET_OPTIMIZED(and8u);
1157
    binary_op(a, b, c, mask, &f, true);
1158 1159
}

1160
void cv::bitwise_or(InputArray a, InputArray b, OutputArray c, InputArray mask)
1161
{
A
Andrey Kamaev 已提交
1162
    BinaryFunc f = (BinaryFunc)GET_OPTIMIZED(or8u);
1163
    binary_op(a, b, c, mask, &f, true);
1164 1165
}

1166
void cv::bitwise_xor(InputArray a, InputArray b, OutputArray c, InputArray mask)
1167
{
A
Andrey Kamaev 已提交
1168
    BinaryFunc f = (BinaryFunc)GET_OPTIMIZED(xor8u);
1169
    binary_op(a, b, c, mask, &f, true);
1170 1171
}

1172
void cv::bitwise_not(InputArray a, OutputArray c, InputArray mask)
1173
{
A
Andrey Kamaev 已提交
1174
    BinaryFunc f = (BinaryFunc)GET_OPTIMIZED(not8u);
1175
    binary_op(a, a, c, mask, &f, true);
1176 1177
}

1178
void cv::max( InputArray src1, InputArray src2, OutputArray dst )
1179
{
1180
    binary_op(src1, src2, dst, noArray(), maxTab, false );
1181 1182
}

1183
void cv::min( InputArray src1, InputArray src2, OutputArray dst )
1184
{
1185
    binary_op(src1, src2, dst, noArray(), minTab, false );
1186 1187
}

1188
void cv::max(const Mat& src1, const Mat& src2, Mat& dst)
1189
{
1190
    OutputArray _dst(dst);
1191
    binary_op(src1, src2, _dst, noArray(), maxTab, false );
1192 1193
}

1194 1195 1196
void cv::min(const Mat& src1, const Mat& src2, Mat& dst)
{
    OutputArray _dst(dst);
1197
    binary_op(src1, src2, _dst, noArray(), minTab, false );
1198
}
1199

1200 1201 1202
void cv::max(const Mat& src1, double src2, Mat& dst)
{
    OutputArray _dst(dst);
1203
    binary_op(src1, src2, _dst, noArray(), maxTab, false );
1204
}
1205

1206
void cv::min(const Mat& src1, double src2, Mat& dst)
1207
{
1208
    OutputArray _dst(dst);
1209
    binary_op(src1, src2, _dst, noArray(), minTab, false );
1210
}
1211

1212 1213 1214
/****************************************************************************************\
*                                      add/subtract                                      *
\****************************************************************************************/
1215

1216 1217
namespace cv
{
1218

1219
static int actualScalarDepth(const Mat& src)
1220
{
V
Vadim Pisarevsky 已提交
1221 1222 1223 1224 1225 1226 1227
    const double* data = (const double*)src.data;
    double minval = MIN(data[0], data[1]);
    minval = MIN(minval, data[2]);
    minval = MIN(minval, data[3]);
    double maxval = MAX(data[0], data[1]);
    maxval = MAX(maxval, data[2]);
    maxval = MAX(maxval, data[3]);
1228
    int depth = CV_64F;
V
Vadim Pisarevsky 已提交
1229
    if(minval >= 0 && maxval <= UCHAR_MAX)
1230
        depth = CV_8U;
V
Vadim Pisarevsky 已提交
1231
    else if(minval >= SCHAR_MIN && maxval <= SCHAR_MAX)
1232
        depth = CV_8S;
V
Vadim Pisarevsky 已提交
1233
    else if(minval >= 0 && maxval <= USHRT_MAX)
1234
        depth = CV_16U;
V
Vadim Pisarevsky 已提交
1235
    else if(minval >= SHRT_MIN && maxval <= SHRT_MAX)
1236
        depth = CV_16S;
V
Vadim Pisarevsky 已提交
1237
    else if(minval >= INT_MIN && maxval <= INT_MAX)
1238 1239 1240 1241
        depth = CV_32S;
    return depth;
}

1242
static void arithm_op(InputArray _src1, InputArray _src2, OutputArray _dst,
1243
               InputArray _mask, int dtype, BinaryFunc* tab, bool muldiv=false, void* usrdata=0)
1244
{
1245 1246 1247
    int kind1 = _src1.kind(), kind2 = _src2.kind();
    Mat src1 = _src1.getMat(), src2 = _src2.getMat();
    bool haveMask = !_mask.empty();
1248
    bool reallocate = false;
1249

1250
    if( (kind1 == kind2 || src1.channels() == 1) && src1.dims <= 2 && src2.dims <= 2 &&
1251 1252 1253
        src1.size() == src2.size() && src1.type() == src2.type() &&
        !haveMask && ((!_dst.fixedType() && (dtype < 0 || CV_MAT_DEPTH(dtype) == src1.depth())) ||
                       (_dst.fixedType() && _dst.type() == _src1.type())) )
V
Vadim Pisarevsky 已提交
1254
    {
1255 1256 1257 1258
        _dst.create(src1.size(), src1.type());
        Mat dst = _dst.getMat();
        Size sz = getContinuousSize(src1, src2, dst, src1.channels());
        tab[src1.depth()](src1.data, src1.step, src2.data, src2.step, dst.data, dst.step, sz, usrdata);
V
Vadim Pisarevsky 已提交
1259 1260
        return;
    }
1261

1262
    bool haveScalar = false, swapped12 = false;
1263
    int depth2 = src2.depth();
1264
    if( src1.size != src2.size || src1.channels() != src2.channels() )
1265
    {
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        if( checkScalar(src1, src2.type(), kind1, kind2) )
        {
            // src1 is a scalar; swap it with src2
            swap(src1, src2);
            swapped12 = true;
        }
        else if( !checkScalar(src2, src1.type(), kind2, kind1) )
            CV_Error( CV_StsUnmatchedSizes,
                     "The operation is neither 'array op array' (where arrays have the same size and the same number of channels), "
                     "nor 'array op scalar', nor 'scalar op array'" );
        haveScalar = true;
V
Vadim Pisarevsky 已提交
1277
        CV_Assert(src2.type() == CV_64F && (src2.rows == 4 || src2.rows == 1));
1278
        depth2 = actualScalarDepth(src2);
1279
    }
1280

1281
    int cn = src1.channels(), depth1 = src1.depth(), wtype;
1282
    BinaryFunc cvtsrc1 = 0, cvtsrc2 = 0, cvtdst = 0;
1283

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    if( dtype < 0 )
    {
        if( _dst.fixedType() )
            dtype = _dst.type();
        else
        {
            if( !haveScalar && src1.type() != src2.type() )
                CV_Error(CV_StsBadArg,
                     "When the input arrays in add/subtract/multiply/divide functions have different types, "
                     "the output array type must be explicitly specified");
            dtype = src1.type();
        }
    }
    dtype = CV_MAT_DEPTH(dtype);
1298

1299 1300 1301 1302 1303 1304 1305
    if( depth1 == depth2 && dtype == depth1 )
        wtype = dtype;
    else if( !muldiv )
    {
        wtype = depth1 <= CV_8S && depth2 <= CV_8S ? CV_16S :
                depth1 <= CV_32S && depth2 <= CV_32S ? CV_32S : std::max(depth1, depth2);
        wtype = std::max(wtype, dtype);
1306

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        // when the result of addition should be converted to an integer type,
        // and just one of the input arrays is floating-point, it makes sense to convert that input to integer type before the operation,
        // instead of converting the other input to floating-point and then converting the operation result back to integers.
        if( dtype < CV_32F && (depth1 < CV_32F || depth2 < CV_32F) )
            wtype = CV_32S;
    }
    else
    {
        wtype = std::max(depth1, std::max(depth2, CV_32F));
        wtype = std::max(wtype, dtype);
    }
1318

1319 1320 1321
    cvtsrc1 = depth1 == wtype ? 0 : getConvertFunc(depth1, wtype);
    cvtsrc2 = depth2 == depth1 ? cvtsrc1 : depth2 == wtype ? 0 : getConvertFunc(depth2, wtype);
    cvtdst = dtype == wtype ? 0 : getConvertFunc(wtype, dtype);
1322

1323 1324
    dtype = CV_MAKETYPE(dtype, cn);
    wtype = CV_MAKETYPE(wtype, cn);
1325

1326 1327 1328 1329 1330
    size_t esz1 = src1.elemSize(), esz2 = src2.elemSize();
    size_t dsz = CV_ELEM_SIZE(dtype), wsz = CV_ELEM_SIZE(wtype);
    size_t blocksize0 = (size_t)(BLOCK_SIZE + wsz-1)/wsz;
    BinaryFunc copymask = 0;
    Mat mask;
1331

1332 1333 1334 1335 1336 1337
    if( haveMask )
    {
        mask = _mask.getMat();
        CV_Assert( (mask.type() == CV_8UC1 || mask.type() == CV_8SC1) );
        CV_Assert( mask.size == src1.size );
        copymask = getCopyMaskFunc(dsz);
1338 1339
        Mat tdst = _dst.getMat();
        reallocate = tdst.size != src1.size || tdst.type() != dtype;
1340
    }
1341

1342 1343 1344
    AutoBuffer<uchar> _buf;
    uchar *buf, *maskbuf = 0, *buf1 = 0, *buf2 = 0, *wbuf = 0;
    size_t bufesz = (cvtsrc1 ? wsz : 0) + (cvtsrc2 || haveScalar ? wsz : 0) + (cvtdst ? wsz : 0) + (haveMask ? dsz : 0);
1345

1346
    _dst.create(src1.dims, src1.size, dtype);
1347
    Mat dst = _dst.getMat();
1348 1349 1350 1351
    
    if( haveMask && reallocate )
        dst = Scalar::all(0);
    
1352
    BinaryFunc func = tab[CV_MAT_DEPTH(wtype)];
1353

1354 1355 1356 1357
    if( !haveScalar )
    {
        const Mat* arrays[] = { &src1, &src2, &dst, &mask, 0 };
        uchar* ptrs[4];
1358

1359 1360
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size, blocksize = total;
1361

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
        if( haveMask || cvtsrc1 || cvtsrc2 || cvtdst )
            blocksize = std::min(blocksize, blocksize0);

        _buf.allocate(bufesz*blocksize + 64);
        buf = _buf;
        if( cvtsrc1 )
            buf1 = buf, buf = alignPtr(buf + blocksize*wsz, 16);
        if( cvtsrc2 )
            buf2 = buf, buf = alignPtr(buf + blocksize*wsz, 16);
        wbuf = maskbuf = buf;
        if( cvtdst )
            buf = alignPtr(buf + blocksize*wsz, 16);
        if( haveMask )
            maskbuf = buf;
1376

1377
        for( size_t i = 0; i < it.nplanes; i++, ++it )
1378
        {
1379
            for( size_t j = 0; j < total; j += blocksize )
1380
            {
1381
                int bsz = (int)MIN(total - j, blocksize);
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
                Size bszn(bsz*cn, 1);
                const uchar *sptr1 = ptrs[0], *sptr2 = ptrs[1];
                uchar* dptr = ptrs[2];
                if( cvtsrc1 )
                {
                    cvtsrc1( sptr1, 0, 0, 0, buf1, 0, bszn, 0 );
                    sptr1 = buf1;
                }
                if( ptrs[0] == ptrs[1] )
                    sptr2 = sptr1;
                else if( cvtsrc2 )
                {
                    cvtsrc2( sptr2, 0, 0, 0, buf2, 0, bszn, 0 );
                    sptr2 = buf2;
                }
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
                if( !haveMask && !cvtdst )
                    func( sptr1, 0, sptr2, 0, dptr, 0, bszn, usrdata );
                else
                {
                    func( sptr1, 0, sptr2, 0, wbuf, 0, bszn, usrdata );
                    if( !haveMask )
                        cvtdst( wbuf, 0, 0, 0, dptr, 0, bszn, 0 );
                    else if( !cvtdst )
                    {
                        copymask( wbuf, 0, ptrs[3], 0, dptr, 0, Size(bsz, 1), &dsz );
                        ptrs[3] += bsz;
                    }
                    else
                    {
                        cvtdst( wbuf, 0, 0, 0, maskbuf, 0, bszn, 0 );
                        copymask( maskbuf, 0, ptrs[3], 0, dptr, 0, Size(bsz, 1), &dsz );
                        ptrs[3] += bsz;
                    }
                }
                ptrs[0] += bsz*esz1; ptrs[1] += bsz*esz2; ptrs[2] += bsz*dsz;
1418 1419
            }
        }
1420 1421 1422 1423 1424
    }
    else
    {
        const Mat* arrays[] = { &src1, &dst, &mask, 0 };
        uchar* ptrs[3];
1425

1426 1427
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size, blocksize = std::min(total, blocksize0);
1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
        _buf.allocate(bufesz*blocksize + 64);
        buf = _buf;
        if( cvtsrc1 )
            buf1 = buf, buf = alignPtr(buf + blocksize*wsz, 16);
        buf2 = buf; buf = alignPtr(buf + blocksize*wsz, 16);
        wbuf = maskbuf = buf;
        if( cvtdst )
            buf = alignPtr(buf + blocksize*wsz, 16);
        if( haveMask )
            maskbuf = buf;
1439

1440
        convertAndUnrollScalar( src2, wtype, buf2, blocksize);
1441

1442
        for( size_t i = 0; i < it.nplanes; i++, ++it )
1443
        {
1444 1445
            for( size_t j = 0; j < total; j += blocksize )
            {
1446
                int bsz = (int)MIN(total - j, blocksize);
1447 1448 1449 1450
                Size bszn(bsz*cn, 1);
                const uchar *sptr1 = ptrs[0];
                const uchar* sptr2 = buf2;
                uchar* dptr = ptrs[1];
1451

1452 1453 1454 1455 1456
                if( cvtsrc1 )
                {
                    cvtsrc1( sptr1, 0, 0, 0, buf1, 0, bszn, 0 );
                    sptr1 = buf1;
                }
1457

1458 1459
                if( swapped12 )
                    std::swap(sptr1, sptr2);
1460

1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
                if( !haveMask && !cvtdst )
                    func( sptr1, 0, sptr2, 0, dptr, 0, bszn, usrdata );
                else
                {
                    func( sptr1, 0, sptr2, 0, wbuf, 0, bszn, usrdata );
                    if( !haveMask )
                        cvtdst( wbuf, 0, 0, 0, dptr, 0, bszn, 0 );
                    else if( !cvtdst )
                    {
                        copymask( wbuf, 0, ptrs[2], 0, dptr, 0, Size(bsz, 1), &dsz );
                        ptrs[2] += bsz;
                    }
                    else
                    {
                        cvtdst( wbuf, 0, 0, 0, maskbuf, 0, bszn, 0 );
                        copymask( maskbuf, 0, ptrs[2], 0, dptr, 0, Size(bsz, 1), &dsz );
                        ptrs[2] += bsz;
                    }
                }
                ptrs[0] += bsz*esz1; ptrs[1] += bsz*dsz;
            }
1482 1483 1484
        }
    }
}
1485

1486 1487
static BinaryFunc addTab[] =
{
A
Andrey Kamaev 已提交
1488 1489 1490 1491 1492
    (BinaryFunc)GET_OPTIMIZED(add8u), (BinaryFunc)GET_OPTIMIZED(add8s),
    (BinaryFunc)GET_OPTIMIZED(add16u), (BinaryFunc)GET_OPTIMIZED(add16s),
    (BinaryFunc)GET_OPTIMIZED(add32s),
    (BinaryFunc)GET_OPTIMIZED(add32f), (BinaryFunc)add64f,
    0
1493
};
1494

1495 1496
static BinaryFunc subTab[] =
{
A
Andrey Kamaev 已提交
1497 1498 1499 1500 1501
    (BinaryFunc)GET_OPTIMIZED(sub8u), (BinaryFunc)GET_OPTIMIZED(sub8s),
    (BinaryFunc)GET_OPTIMIZED(sub16u), (BinaryFunc)GET_OPTIMIZED(sub16s),
    (BinaryFunc)GET_OPTIMIZED(sub32s),
    (BinaryFunc)GET_OPTIMIZED(sub32f), (BinaryFunc)sub64f,
    0
1502 1503
};

1504
static BinaryFunc absdiffTab[] =
1505
{
A
Andrey Kamaev 已提交
1506 1507 1508 1509 1510
    (BinaryFunc)GET_OPTIMIZED(absdiff8u), (BinaryFunc)GET_OPTIMIZED(absdiff8s),
    (BinaryFunc)GET_OPTIMIZED(absdiff16u), (BinaryFunc)GET_OPTIMIZED(absdiff16s),
    (BinaryFunc)GET_OPTIMIZED(absdiff32s),
    (BinaryFunc)GET_OPTIMIZED(absdiff32f), (BinaryFunc)absdiff64f,
    0
1511
};
1512 1513

}
1514

1515 1516
void cv::add( InputArray src1, InputArray src2, OutputArray dst,
          InputArray mask, int dtype )
1517
{
1518
    arithm_op(src1, src2, dst, mask, dtype, addTab );
1519 1520
}

1521 1522
void cv::subtract( InputArray src1, InputArray src2, OutputArray dst,
               InputArray mask, int dtype )
1523
{
A
Andrey Kamaev 已提交
1524 1525 1526 1527 1528 1529 1530
#ifdef HAVE_TEGRA_OPTIMIZATION
    if(mask.empty() && src1.depth() == CV_8U && src2.depth() == CV_8U && (dtype == CV_16S || (dtype == -1 && dst.fixedType() && dst.depth() == CV_16S)))
    {
        Mat _dst = dst.getMat();
        if(tegra::subtract_8u8u16s(src1.getMat(), src2.getMat(), _dst))
            return;
    }
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    if(mask.empty() && src1.depth() == CV_8U && src2.depth() == CV_8U && dst.depth() == CV_32F)
    {
        Mat _dst = dst.getMat();
        if(tegra::subtract_8u8u32f(src1.getMat(), src2.getMat(), _dst))
            return;
    }
    if(mask.empty() && src1.depth() == CV_8U && src2.depth() == CV_8U && dst.depth() == CV_8S)
    {
        Mat _dst = dst.getMat();
        if(tegra::subtract_8u8u8s(src1.getMat(), src2.getMat(), _dst))
            return;
    }
A
Andrey Kamaev 已提交
1543
#endif
1544
    arithm_op(src1, src2, dst, mask, dtype, subTab );
1545 1546
}

1547
void cv::absdiff( InputArray src1, InputArray src2, OutputArray dst )
1548
{
1549
    arithm_op(src1, src2, dst, noArray(), -1, absdiffTab);
1550
}
1551 1552 1553 1554 1555

/****************************************************************************************\
*                                    multiply/divide                                     *
\****************************************************************************************/

1556 1557 1558
namespace cv
{

1559
template<typename T, typename WT> static void
1560 1561
mul_( const T* src1, size_t step1, const T* src2, size_t step2,
      T* dst, size_t step, Size size, WT scale )
1562
{
1563 1564 1565
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    step /= sizeof(dst[0]);
1566

1567
    if( scale == (WT)1. )
1568
    {
1569
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
1570
        {
V
Victoria Zhislina 已提交
1571 1572 1573
            int i=0;
			#if CV_ENABLE_UNROLLED
            for(; i <= size.width - 4; i += 4 )
1574
            {
1575 1576 1577 1578 1579 1580
                T t0;
                T t1;
                t0 = saturate_cast<T>(src1[i  ] * src2[i  ]);
                t1 = saturate_cast<T>(src1[i+1] * src2[i+1]);
                dst[i  ] = t0;
                dst[i+1] = t1;
1581 1582 1583

                t0 = saturate_cast<T>(src1[i+2] * src2[i+2]);
                t1 = saturate_cast<T>(src1[i+3] * src2[i+3]);
1584 1585
                dst[i+2] = t0;
                dst[i+3] = t1;
1586
            }
V
Victoria Zhislina 已提交
1587
            #endif
1588 1589 1590 1591 1592 1593
            for( ; i < size.width; i++ )
                dst[i] = saturate_cast<T>(src1[i] * src2[i]);
        }
    }
    else
    {
1594
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
1595
        {
V
Victoria Zhislina 已提交
1596 1597 1598
            int i = 0;
			#if CV_ENABLE_UNROLLED
            for(; i <= size.width - 4; i += 4 )
1599 1600 1601 1602 1603 1604 1605 1606 1607
            {
                T t0 = saturate_cast<T>(scale*(WT)src1[i]*src2[i]);
                T t1 = saturate_cast<T>(scale*(WT)src1[i+1]*src2[i+1]);
                dst[i] = t0; dst[i+1] = t1;

                t0 = saturate_cast<T>(scale*(WT)src1[i+2]*src2[i+2]);
                t1 = saturate_cast<T>(scale*(WT)src1[i+3]*src2[i+3]);
                dst[i+2] = t0; dst[i+3] = t1;
            }
V
Victoria Zhislina 已提交
1608
            #endif
1609 1610 1611 1612 1613 1614 1615
            for( ; i < size.width; i++ )
                dst[i] = saturate_cast<T>(scale*(WT)src1[i]*src2[i]);
        }
    }
}

template<typename T> static void
1616 1617
div_( const T* src1, size_t step1, const T* src2, size_t step2,
      T* dst, size_t step, Size size, double scale )
1618
{
1619 1620 1621
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    step /= sizeof(dst[0]);
1622

1623
    for( ; size.height--; src1 += step1, src2 += step2, dst += step )
1624 1625
    {
        int i = 0;
V
Victoria Zhislina 已提交
1626
		#if CV_ENABLE_UNROLLED
1627 1628 1629 1630 1631 1632 1633 1634 1635
        for( ; i <= size.width - 4; i += 4 )
        {
            if( src2[i] != 0 && src2[i+1] != 0 && src2[i+2] != 0 && src2[i+3] != 0 )
            {
                double a = (double)src2[i] * src2[i+1];
                double b = (double)src2[i+2] * src2[i+3];
                double d = scale/(a * b);
                b *= d;
                a *= d;
1636

1637 1638 1639 1640
                T z0 = saturate_cast<T>(src2[i+1] * ((double)src1[i] * b));
                T z1 = saturate_cast<T>(src2[i] * ((double)src1[i+1] * b));
                T z2 = saturate_cast<T>(src2[i+3] * ((double)src1[i+2] * a));
                T z3 = saturate_cast<T>(src2[i+2] * ((double)src1[i+3] * a));
1641

1642 1643 1644 1645 1646 1647 1648 1649 1650
                dst[i] = z0; dst[i+1] = z1;
                dst[i+2] = z2; dst[i+3] = z3;
            }
            else
            {
                T z0 = src2[i] != 0 ? saturate_cast<T>(src1[i]*scale/src2[i]) : 0;
                T z1 = src2[i+1] != 0 ? saturate_cast<T>(src1[i+1]*scale/src2[i+1]) : 0;
                T z2 = src2[i+2] != 0 ? saturate_cast<T>(src1[i+2]*scale/src2[i+2]) : 0;
                T z3 = src2[i+3] != 0 ? saturate_cast<T>(src1[i+3]*scale/src2[i+3]) : 0;
1651

1652 1653 1654 1655
                dst[i] = z0; dst[i+1] = z1;
                dst[i+2] = z2; dst[i+3] = z3;
            }
        }
V
Victoria Zhislina 已提交
1656
        #endif
1657 1658 1659 1660 1661 1662
        for( ; i < size.width; i++ )
            dst[i] = src2[i] != 0 ? saturate_cast<T>(src1[i]*scale/src2[i]) : 0;
    }
}

template<typename T> static void
1663 1664
recip_( const T*, size_t, const T* src2, size_t step2,
        T* dst, size_t step, Size size, double scale )
1665
{
1666 1667
    step2 /= sizeof(src2[0]);
    step /= sizeof(dst[0]);
1668

1669
    for( ; size.height--; src2 += step2, dst += step )
1670 1671
    {
        int i = 0;
V
Victoria Zhislina 已提交
1672
		#if CV_ENABLE_UNROLLED
1673 1674 1675 1676 1677 1678 1679 1680 1681
        for( ; i <= size.width - 4; i += 4 )
        {
            if( src2[i] != 0 && src2[i+1] != 0 && src2[i+2] != 0 && src2[i+3] != 0 )
            {
                double a = (double)src2[i] * src2[i+1];
                double b = (double)src2[i+2] * src2[i+3];
                double d = scale/(a * b);
                b *= d;
                a *= d;
1682

1683 1684 1685 1686
                T z0 = saturate_cast<T>(src2[i+1] * b);
                T z1 = saturate_cast<T>(src2[i] * b);
                T z2 = saturate_cast<T>(src2[i+3] * a);
                T z3 = saturate_cast<T>(src2[i+2] * a);
1687

1688 1689 1690 1691 1692 1693 1694 1695 1696
                dst[i] = z0; dst[i+1] = z1;
                dst[i+2] = z2; dst[i+3] = z3;
            }
            else
            {
                T z0 = src2[i] != 0 ? saturate_cast<T>(scale/src2[i]) : 0;
                T z1 = src2[i+1] != 0 ? saturate_cast<T>(scale/src2[i+1]) : 0;
                T z2 = src2[i+2] != 0 ? saturate_cast<T>(scale/src2[i+2]) : 0;
                T z3 = src2[i+3] != 0 ? saturate_cast<T>(scale/src2[i+3]) : 0;
1697
                
1698 1699 1700 1701
                dst[i] = z0; dst[i+1] = z1;
                dst[i+2] = z2; dst[i+3] = z3;
            }
        }
V
Victoria Zhislina 已提交
1702
        #endif
1703 1704 1705 1706
        for( ; i < size.width; i++ )
            dst[i] = src2[i] != 0 ? saturate_cast<T>(scale/src2[i]) : 0;
    }
}
1707 1708


1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
static void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, (float)*(const double*)scale);
}

static void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2,
                   schar* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, (float)*(const double*)scale);
}

static void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, (float)*(const double*)scale);
}

static void mul16s( const short* src1, size_t step1, const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, (float)*(const double*)scale);
}

static void mul32s( const int* src1, size_t step1, const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}
1738

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
static void mul32f( const float* src1, size_t step1, const float* src2, size_t step2,
                    float* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, (float)*(const double*)scale);
}
    
static void mul64f( const double* src1, size_t step1, const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* scale)
{
    mul_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}
1750

1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
static void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                   uchar* dst, size_t step, Size sz, void* scale)
{
    if( src1 )
        div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
    else
        recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2,
                  schar* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                    ushort* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div16s( const short* src1, size_t step1, const short* src2, size_t step2,
                    short* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div32s( const int* src1, size_t step1, const int* src2, size_t step2,
                    int* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div32f( const float* src1, size_t step1, const float* src2, size_t step2,
                    float* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void div64f( const double* src1, size_t step1, const double* src2, size_t step2,
                    double* dst, size_t step, Size sz, void* scale)
{
    div_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                  uchar* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip8s( const schar* src1, size_t step1, const schar* src2, size_t step2,
                  schar* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                   ushort* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip16s( const short* src1, size_t step1, const short* src2, size_t step2,
                   short* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
static void recip32s( const int* src1, size_t step1, const int* src2, size_t step2,
                   int* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip32f( const float* src1, size_t step1, const float* src2, size_t step2,
                   float* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}

static void recip64f( const double* src1, size_t step1, const double* src2, size_t step2,
                   double* dst, size_t step, Size sz, void* scale)
{
    recip_(src1, step1, src2, step2, dst, step, sz, *(const double*)scale);
}
1837 1838


1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
static BinaryFunc mulTab[] =
{
    (BinaryFunc)mul8u, (BinaryFunc)mul8s, (BinaryFunc)mul16u,
    (BinaryFunc)mul16s, (BinaryFunc)mul32s, (BinaryFunc)mul32f,
    (BinaryFunc)mul64f, 0
};

static BinaryFunc divTab[] =
{
    (BinaryFunc)div8u, (BinaryFunc)div8s, (BinaryFunc)div16u,
    (BinaryFunc)div16s, (BinaryFunc)div32s, (BinaryFunc)div32f,
    (BinaryFunc)div64f, 0
};

static BinaryFunc recipTab[] =
{
    (BinaryFunc)recip8u, (BinaryFunc)recip8s, (BinaryFunc)recip16u,
    (BinaryFunc)recip16s, (BinaryFunc)recip32s, (BinaryFunc)recip32f,
    (BinaryFunc)recip64f, 0
};
1859

1860

1861
}
1862

1863
void cv::multiply(InputArray src1, InputArray src2,
1864
                  OutputArray dst, double scale, int dtype)
1865
{
1866
    arithm_op(src1, src2, dst, noArray(), dtype, mulTab, true, &scale);
1867
}
1868

1869
void cv::divide(InputArray src1, InputArray src2,
1870 1871
                OutputArray dst, double scale, int dtype)
{
1872
    arithm_op(src1, src2, dst, noArray(), dtype, divTab, true, &scale);
1873 1874
}

1875
void cv::divide(double scale, InputArray src2,
1876 1877
                OutputArray dst, int dtype)
{
1878
    arithm_op(src2, src2, dst, noArray(), dtype, recipTab, true, &scale);
1879 1880
}

1881 1882 1883 1884
/****************************************************************************************\
*                                      addWeighted                                       *
\****************************************************************************************/

1885 1886 1887
namespace cv
{

1888
template<typename T, typename WT> static void
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
addWeighted_( const T* src1, size_t step1, const T* src2, size_t step2,
              T* dst, size_t step, Size size, void* _scalars )
{
    const double* scalars = (const double*)_scalars;
    WT alpha = (WT)scalars[0], beta = (WT)scalars[1], gamma = (WT)scalars[2];
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    step /= sizeof(dst[0]);

    for( ; size.height--; src1 += step1, src2 += step2, dst += step )
1899
    {
1900
        int x = 0;
V
Victoria Zhislina 已提交
1901
		#if CV_ENABLE_UNROLLED
1902
        for( ; x <= size.width - 4; x += 4 )
1903
        {
1904 1905 1906
            T t0 = saturate_cast<T>(src1[x]*alpha + src2[x]*beta + gamma);
            T t1 = saturate_cast<T>(src1[x+1]*alpha + src2[x+1]*beta + gamma);
            dst[x] = t0; dst[x+1] = t1;
1907

1908 1909 1910
            t0 = saturate_cast<T>(src1[x+2]*alpha + src2[x+2]*beta + gamma);
            t1 = saturate_cast<T>(src1[x+3]*alpha + src2[x+3]*beta + gamma);
            dst[x+2] = t0; dst[x+3] = t1;
1911
        }
V
Victoria Zhislina 已提交
1912
        #endif
1913 1914
        for( ; x < size.width; x++ )
            dst[x] = saturate_cast<T>(src1[x]*alpha + src2[x]*beta + gamma);
1915 1916 1917 1918 1919
    }
}


static void
1920 1921 1922 1923 1924 1925 1926
addWeighted8u( const uchar* src1, size_t step1,
               const uchar* src2, size_t step2,
               uchar* dst, size_t step, Size size,
               void* _scalars )
{
    const double* scalars = (const double*)_scalars;
    float alpha = (float)scalars[0], beta = (float)scalars[1], gamma = (float)scalars[2];
1927

1928
    for( ; size.height--; src1 += step1, src2 += step2, dst += step )
1929
    {
1930
        int x = 0;
1931

1932 1933
#if CV_SSE2
        if( USE_SSE2 )
1934
        {
1935 1936
            __m128 a4 = _mm_set1_ps(alpha), b4 = _mm_set1_ps(beta), g4 = _mm_set1_ps(gamma);
            __m128i z = _mm_setzero_si128();
1937

1938
            for( ; x <= size.width - 8; x += 8 )
1939
            {
1940 1941
                __m128i u = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)(src1 + x)), z);
                __m128i v = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)(src2 + x)), z);
1942

1943 1944 1945 1946
                __m128 u0 = _mm_cvtepi32_ps(_mm_unpacklo_epi16(u, z));
                __m128 u1 = _mm_cvtepi32_ps(_mm_unpackhi_epi16(u, z));
                __m128 v0 = _mm_cvtepi32_ps(_mm_unpacklo_epi16(v, z));
                __m128 v1 = _mm_cvtepi32_ps(_mm_unpackhi_epi16(v, z));
1947

1948 1949 1950
                u0 = _mm_add_ps(_mm_mul_ps(u0, a4), _mm_mul_ps(v0, b4));
                u1 = _mm_add_ps(_mm_mul_ps(u1, a4), _mm_mul_ps(v1, b4));
                u0 = _mm_add_ps(u0, g4); u1 = _mm_add_ps(u1, g4);
1951

1952 1953
                u = _mm_packs_epi32(_mm_cvtps_epi32(u0), _mm_cvtps_epi32(u1));
                u = _mm_packus_epi16(u, u);
1954

1955
                _mm_storel_epi64((__m128i*)(dst + x), u);
1956 1957
            }
        }
1958
#endif
V
Victoria Zhislina 已提交
1959
		#if CV_ENABLE_UNROLLED
1960
        for( ; x <= size.width - 4; x += 4 )
1961
        {
1962 1963 1964
            float t0, t1;
            t0 = CV_8TO32F(src1[x])*alpha + CV_8TO32F(src2[x])*beta + gamma;
            t1 = CV_8TO32F(src1[x+1])*alpha + CV_8TO32F(src2[x+1])*beta + gamma;
1965

1966 1967
            dst[x] = saturate_cast<uchar>(t0);
            dst[x+1] = saturate_cast<uchar>(t1);
1968

1969 1970
            t0 = CV_8TO32F(src1[x+2])*alpha + CV_8TO32F(src2[x+2])*beta + gamma;
            t1 = CV_8TO32F(src1[x+3])*alpha + CV_8TO32F(src2[x+3])*beta + gamma;
1971

1972 1973 1974
            dst[x+2] = saturate_cast<uchar>(t0);
            dst[x+3] = saturate_cast<uchar>(t1);
        }
V
Victoria Zhislina 已提交
1975
        #endif
1976

1977 1978 1979 1980
        for( ; x < size.width; x++ )
        {
            float t0 = CV_8TO32F(src1[x])*alpha + CV_8TO32F(src2[x])*beta + gamma;
            dst[x] = saturate_cast<uchar>(t0);
1981 1982 1983 1984
        }
    }
}

1985 1986
static void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2,
                           schar* dst, size_t step, Size sz, void* scalars )
1987
{
1988
    addWeighted_<schar, float>(src1, step1, src2, step2, dst, step, sz, scalars);
1989 1990
}

1991 1992
static void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                            ushort* dst, size_t step, Size sz, void* scalars )
1993
{
1994 1995
    addWeighted_<ushort, float>(src1, step1, src2, step2, dst, step, sz, scalars);
}
1996

1997 1998
static void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2,
                            short* dst, size_t step, Size sz, void* scalars )
1999
{
2000 2001
    addWeighted_<short, float>(src1, step1, src2, step2, dst, step, sz, scalars);
}
2002

2003 2004
static void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2,
                            int* dst, size_t step, Size sz, void* scalars )
2005
{
2006
    addWeighted_<int, double>(src1, step1, src2, step2, dst, step, sz, scalars);
2007 2008
}

2009 2010
static void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2,
                            float* dst, size_t step, Size sz, void* scalars )
2011
{
2012 2013
    addWeighted_<float, double>(src1, step1, src2, step2, dst, step, sz, scalars);
}
2014

2015 2016 2017 2018 2019
static void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2,
                            double* dst, size_t step, Size sz, void* scalars )
{
    addWeighted_<double, double>(src1, step1, src2, step2, dst, step, sz, scalars);
}
V
Vadim Pisarevsky 已提交
2020

2021 2022
static BinaryFunc addWeightedTab[] =
{
2023 2024
    (BinaryFunc)GET_OPTIMIZED(addWeighted8u), (BinaryFunc)GET_OPTIMIZED(addWeighted8s), (BinaryFunc)GET_OPTIMIZED(addWeighted16u),
    (BinaryFunc)GET_OPTIMIZED(addWeighted16s), (BinaryFunc)GET_OPTIMIZED(addWeighted32s), (BinaryFunc)addWeighted32f,
2025 2026
    (BinaryFunc)addWeighted64f, 0
};
2027

2028
}
2029

2030
void cv::addWeighted( InputArray src1, double alpha, InputArray src2,
2031 2032 2033
                      double beta, double gamma, OutputArray dst, int dtype )
{
    double scalars[] = {alpha, beta, gamma};
2034
    arithm_op(src1, src2, dst, noArray(), dtype, addWeightedTab, true, scalars);
2035 2036
}

2037

2038
/****************************************************************************************\
2039
*                                          compare                                       *
2040 2041
\****************************************************************************************/

2042
namespace cv
2043 2044
{

2045 2046 2047
template<typename T> static void
cmp_(const T* src1, size_t step1, const T* src2, size_t step2,
     uchar* dst, size_t step, Size size, int code)
2048
{
2049 2050 2051
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    if( code == CMP_GE || code == CMP_LT )
2052
    {
2053 2054 2055
        std::swap(src1, src2);
        std::swap(step1, step2);
        code = code == CMP_GE ? CMP_LE : CMP_GT;
2056
    }
2057

2058
    if( code == CMP_GT || code == CMP_LE )
2059
    {
2060 2061 2062 2063
        int m = code == CMP_GT ? 0 : 255;
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x = 0;
V
Victoria Zhislina 已提交
2064
			#if CV_ENABLE_UNROLLED
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
            for( ; x <= size.width - 4; x += 4 )
            {
                int t0, t1;
                t0 = -(src1[x] > src2[x]) ^ m;
                t1 = -(src1[x+1] > src2[x+1]) ^ m;
                dst[x] = (uchar)t0; dst[x+1] = (uchar)t1;
                t0 = -(src1[x+2] > src2[x+2]) ^ m;
                t1 = -(src1[x+3] > src2[x+3]) ^ m;
                dst[x+2] = (uchar)t0; dst[x+3] = (uchar)t1;
            }
V
Victoria Zhislina 已提交
2075
            #endif
2076 2077
            for( ; x < size.width; x++ )
                dst[x] = (uchar)(-(src1[x] > src2[x]) ^ m);
2078
			   }
2079
    }
2080
    else if( code == CMP_EQ || code == CMP_NE )
2081
    {
2082 2083 2084 2085
        int m = code == CMP_EQ ? 0 : 255;
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x = 0;
V
Victoria Zhislina 已提交
2086
			#if CV_ENABLE_UNROLLED
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
            for( ; x <= size.width - 4; x += 4 )
            {
                int t0, t1;
                t0 = -(src1[x] == src2[x]) ^ m;
                t1 = -(src1[x+1] == src2[x+1]) ^ m;
                dst[x] = (uchar)t0; dst[x+1] = (uchar)t1;
                t0 = -(src1[x+2] == src2[x+2]) ^ m;
                t1 = -(src1[x+3] == src2[x+3]) ^ m;
                dst[x+2] = (uchar)t0; dst[x+3] = (uchar)t1;
            }
V
Victoria Zhislina 已提交
2097
            #endif
2098 2099 2100
            for( ; x < size.width; x++ )
                dst[x] = (uchar)(-(src1[x] == src2[x]) ^ m);
        }
2101
    }
2102
}
2103 2104


2105 2106
static void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2107
{
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
  //vz optimized  cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
	int code = *(int*)_cmpop;
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    if( code == CMP_GE || code == CMP_LT )
    {
        std::swap(src1, src2);
        std::swap(step1, step2);
        code = code == CMP_GE ? CMP_LE : CMP_GT;
    }

    if( code == CMP_GT || code == CMP_LE )
    {
        int m = code == CMP_GT ? 0 : 255;
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x =0;
		    #if CV_SSE2
		    if( USE_SSE2 ){
2127 2128
                __m128i m128 = code == CMP_GT ? _mm_setzero_si128() : _mm_set1_epi8 (-1);
                __m128i c128 = _mm_set1_epi8 (-128);
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
				for( ; x <= size.width - 16; x += 16 )
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					// no simd for 8u comparison, that's why we need the trick
					r00 = _mm_sub_epi8(r00,c128);
					r10 = _mm_sub_epi8(r10,c128);

					r00 =_mm_xor_si128(_mm_cmpgt_epi8(r00, r10), m128);
					_mm_storeu_si128((__m128i*)(dst + x),r00);
				
				} 
			}
           #endif

			for( ; x < size.width; x++ ){
                dst[x] = (uchar)(-(src1[x] > src2[x]) ^ m);
			}
        }
    }
    else if( code == CMP_EQ || code == CMP_NE )
    {
        int m = code == CMP_EQ ? 0 : 255;
		for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x = 0;
		    #if CV_SSE2
		    if( USE_SSE2 ){
2157
                __m128i m128 =  code == CMP_EQ ? _mm_setzero_si128() : _mm_set1_epi8 (-1);
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
				for( ; x <= size.width - 16; x += 16 )
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					r00 = _mm_xor_si128 ( _mm_cmpeq_epi8 (r00, r10), m128);
					_mm_storeu_si128((__m128i*)(dst + x), r00);
				} 
			}
           #endif
           for( ; x < size.width; x++ )
                dst[x] = (uchar)(-(src1[x] == src2[x]) ^ m);
        }
    }
2171 2172
}

2173 2174
static void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2175
{
2176
    cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
2177 2178
}

2179 2180
static void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2181
{
2182
    cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
2183 2184
}

2185 2186
static void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2187
{
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
   //vz optimized cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);

	int code = *(int*)_cmpop;
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    if( code == CMP_GE || code == CMP_LT )
    {
        std::swap(src1, src2);
        std::swap(step1, step2);
        code = code == CMP_GE ? CMP_LE : CMP_GT;
    }

    if( code == CMP_GT || code == CMP_LE )
    {
        int m = code == CMP_GT ? 0 : 255;
        for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x =0;
		    #if CV_SSE2
		    if( USE_SSE2){//
2208
                __m128i m128 =  code == CMP_GT ? _mm_setzero_si128() : _mm_set1_epi16 (-1);
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
				for( ; x <= size.width - 16; x += 16 )
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					r00 = _mm_xor_si128 ( _mm_cmpgt_epi16 (r00, r10), m128);
					__m128i r01 = _mm_loadu_si128((const __m128i*)(src1 + x + 8));
					__m128i r11 = _mm_loadu_si128((const __m128i*)(src2 + x + 8));
					r01 = _mm_xor_si128 ( _mm_cmpgt_epi16 (r01, r11), m128);
					r11 = _mm_packs_epi16(r00, r01);
					_mm_storeu_si128((__m128i*)(dst + x), r11);
				} 
				if( x <= size.width-8) 
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					r00 = _mm_xor_si128 ( _mm_cmpgt_epi16 (r00, r10), m128);
					r10 = _mm_packs_epi16(r00, r00);
					_mm_storel_epi64((__m128i*)(dst + x), r10);

					x += 8;
				}
			}
           #endif

			for( ; x < size.width; x++ ){
                 dst[x] = (uchar)(-(src1[x] > src2[x]) ^ m);
			}
        }
    }
    else if( code == CMP_EQ || code == CMP_NE )
    {
        int m = code == CMP_EQ ? 0 : 255;
		for( ; size.height--; src1 += step1, src2 += step2, dst += step )
        {
            int x = 0;
		    #if CV_SSE2
		    if( USE_SSE2 ){
2246
                __m128i m128 =  code == CMP_EQ ? _mm_setzero_si128() : _mm_set1_epi16 (-1);
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
				for( ; x <= size.width - 16; x += 16 )
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					r00 = _mm_xor_si128 ( _mm_cmpeq_epi16 (r00, r10), m128);
					__m128i r01 = _mm_loadu_si128((const __m128i*)(src1 + x + 8));
					__m128i r11 = _mm_loadu_si128((const __m128i*)(src2 + x + 8));
					r01 = _mm_xor_si128 ( _mm_cmpeq_epi16 (r01, r11), m128);
					r11 = _mm_packs_epi16(r00, r01);
					_mm_storeu_si128((__m128i*)(dst + x), r11);
				} 
				if( x <= size.width - 8) 
				{
					__m128i r00 = _mm_loadu_si128((const __m128i*)(src1 + x));
					__m128i r10 = _mm_loadu_si128((const __m128i*)(src2 + x));
					r00 = _mm_xor_si128 ( _mm_cmpeq_epi16 (r00, r10), m128);
					r10 = _mm_packs_epi16(r00, r00);
					_mm_storel_epi64((__m128i*)(dst + x), r10);

					x += 8;
				}
			}
           #endif
           for( ; x < size.width; x++ )
                dst[x] = (uchar)(-(src1[x] == src2[x]) ^ m);
        }
    }
2274 2275
}

2276 2277 2278 2279 2280
static void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2,
                   uchar* dst, size_t step, Size size, void* _cmpop)
{
    cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
}
2281

2282 2283
static void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2284
{
2285 2286
    cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
}
2287

2288 2289
static void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2,
                  uchar* dst, size_t step, Size size, void* _cmpop)
2290
{
2291
    cmp_(src1, step1, src2, step2, dst, step, size, *(int*)_cmpop);
2292 2293
}

2294 2295
static BinaryFunc cmpTab[] =
{
A
Andrey Kamaev 已提交
2296 2297 2298 2299 2300
    (BinaryFunc)GET_OPTIMIZED(cmp8u), (BinaryFunc)GET_OPTIMIZED(cmp8s),
    (BinaryFunc)GET_OPTIMIZED(cmp16u), (BinaryFunc)GET_OPTIMIZED(cmp16s),
    (BinaryFunc)GET_OPTIMIZED(cmp32s),
    (BinaryFunc)GET_OPTIMIZED(cmp32f), (BinaryFunc)cmp64f,
    0
2301 2302
};

2303

2304
static double getMinVal(int depth)
2305
{
2306 2307 2308
    static const double tab[] = {0, -128, 0, -32768, INT_MIN, -FLT_MAX, -DBL_MAX, 0};
    return tab[depth];
}
2309

2310
static double getMaxVal(int depth)
2311
{
2312 2313 2314
    static const double tab[] = {255, 127, 65535, 32767, INT_MAX, FLT_MAX, DBL_MAX, 0};
    return tab[depth];
}
2315 2316 2317

}

2318
void cv::compare(InputArray _src1, InputArray _src2, OutputArray _dst, int op)
2319 2320 2321
{
    CV_Assert( op == CMP_LT || op == CMP_LE || op == CMP_EQ ||
               op == CMP_NE || op == CMP_GE || op == CMP_GT );
2322

2323 2324
    int kind1 = _src1.kind(), kind2 = _src2.kind();
    Mat src1 = _src1.getMat(), src2 = _src2.getMat();
2325

2326
    if( kind1 == kind2 && src1.dims <= 2 && src2.dims <= 2 && src1.size() == src2.size() && src1.type() == src2.type() )
2327
    {
2328 2329
        int cn = src1.channels();
        _dst.create(src1.size(), CV_8UC(cn));
2330 2331 2332 2333 2334
        Mat dst = _dst.getMat();
        Size sz = getContinuousSize(src1, src2, dst, src1.channels());
        cmpTab[src1.depth()](src1.data, src1.step, src2.data, src2.step, dst.data, dst.step, sz, &op);
        return;
    }
2335

2336
    bool haveScalar = false;
2337

2338
    if( (kind1 == _InputArray::MATX) + (kind2 == _InputArray::MATX) == 1 ||
2339 2340 2341
        src1.size != src2.size || src1.type() != src2.type() )
    {
        if( checkScalar(src1, src2.type(), kind1, kind2) )
2342
        {
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
            // src1 is a scalar; swap it with src2
            swap(src1, src2);
            op = op == CMP_LT ? CMP_GT : op == CMP_LE ? CMP_GE :
                op == CMP_GE ? CMP_LE : op == CMP_GT ? CMP_LT : op;
        }
        else if( !checkScalar(src2, src1.type(), kind2, kind1) )
            CV_Error( CV_StsUnmatchedSizes,
                     "The operation is neither 'array op array' (where arrays have the same size and the same type), "
                     "nor 'array op scalar', nor 'scalar op array'" );
        haveScalar = true;
    }
2354

2355
    
2356
    int cn = src1.channels(), depth1 = src1.depth(), depth2 = src2.depth();
2357

2358 2359 2360 2361
    _dst.create(src1.dims, src1.size, CV_8UC(cn));
    src1 = src1.reshape(1); src2 = src2.reshape(1);
    Mat dst = _dst.getMat().reshape(1);
    
2362 2363 2364
    size_t esz = src1.elemSize();
    size_t blocksize0 = (size_t)(BLOCK_SIZE + esz-1)/esz;
    BinaryFunc func = cmpTab[depth1];
2365

2366
    if( !haveScalar )
2367
    {
2368 2369
        const Mat* arrays[] = { &src1, &src2, &dst, 0 };
        uchar* ptrs[3];
2370

2371 2372
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size;
2373

2374 2375
        for( size_t i = 0; i < it.nplanes; i++, ++it )
            func( ptrs[0], 0, ptrs[1], 0, ptrs[2], 0, Size((int)total, 1), &op );
2376
    }
2377
    else
2378
    {
2379 2380
        const Mat* arrays[] = { &src1, &dst, 0 };
        uchar* ptrs[2];
2381

2382 2383
        NAryMatIterator it(arrays, ptrs);
        size_t total = it.size, blocksize = std::min(total, blocksize0);
2384

2385 2386 2387 2388 2389 2390
        AutoBuffer<uchar> _buf(blocksize*esz);
        uchar *buf = _buf;

        if( depth1 > CV_32S )
            convertAndUnrollScalar( src2, depth1, buf, blocksize );
        else
2391
        {
2392 2393 2394 2395 2396 2397 2398
            double fval=0;
            getConvertFunc(depth2, CV_64F)(src2.data, 0, 0, 0, (uchar*)&fval, 0, Size(1,1), 0);
            if( fval < getMinVal(depth1) )
            {
                dst = Scalar::all(op == CMP_GT || op == CMP_GE || op == CMP_NE ? 255 : 0);
                return;
            }
2399

2400 2401 2402 2403 2404
            if( fval > getMaxVal(depth1) )
            {
                dst = Scalar::all(op == CMP_LT || op == CMP_LE || op == CMP_NE ? 255 : 0);
                return;
            }
2405

2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
            int ival = cvRound(fval);
            if( fval != ival )
            {
                if( op == CMP_LT || op == CMP_GE )
                    ival = cvCeil(fval);
                else if( op == CMP_LE || op == CMP_GT )
                    ival = cvFloor(fval);
                else
                {
                    dst = Scalar::all(op == CMP_NE ? 255 : 0);
                    return;
                }
            }
            convertAndUnrollScalar(Mat(1, 1, CV_32S, &ival), depth1, buf, blocksize);
        }
2421

2422
        for( size_t i = 0; i < it.nplanes; i++, ++it )
2423
        {
2424 2425
            for( size_t j = 0; j < total; j += blocksize )
            {
2426
                int bsz = (int)MIN(total - j, blocksize);
2427 2428 2429 2430 2431
                func( ptrs[0], 0, buf, 0, ptrs[1], 0, Size(bsz, 1), &op);
                ptrs[0] += bsz*esz;
                ptrs[1] += bsz;
            }
        }
2432
    }
2433
}
2434

2435 2436 2437
/****************************************************************************************\
*                                        inRange                                         *
\****************************************************************************************/
2438

2439 2440
namespace cv
{
2441

2442 2443 2444 2445 2446 2447 2448 2449
template<typename T> static void
inRange_(const T* src1, size_t step1, const T* src2, size_t step2,
         const T* src3, size_t step3, uchar* dst, size_t step,
         Size size)
{
    step1 /= sizeof(src1[0]);
    step2 /= sizeof(src2[0]);
    step3 /= sizeof(src3[0]);
2450

2451
    for( ; size.height--; src1 += step1, src2 += step2, src3 += step3, dst += step )
V
Vadim Pisarevsky 已提交
2452
    {
2453
        int x = 0;
V
Victoria Zhislina 已提交
2454
		#if CV_ENABLE_UNROLLED
2455
        for( ; x <= size.width - 4; x += 4 )
V
Vadim Pisarevsky 已提交
2456
        {
2457 2458 2459 2460 2461 2462 2463
            int t0, t1;
            t0 = src2[x] <= src1[x] && src1[x] <= src3[x];
            t1 = src2[x+1] <= src1[x+1] && src1[x+1] <= src3[x+1];
            dst[x] = (uchar)-t0; dst[x+1] = (uchar)-t1;
            t0 = src2[x+2] <= src1[x+2] && src1[x+2] <= src3[x+2];
            t1 = src2[x+3] <= src1[x+3] && src1[x+3] <= src3[x+3];
            dst[x+2] = (uchar)-t0; dst[x+3] = (uchar)-t1;
V
Vadim Pisarevsky 已提交
2464
        }
V
Victoria Zhislina 已提交
2465
        #endif
2466 2467
        for( ; x < size.width; x++ )
            dst[x] = (uchar)-(src2[x] <= src1[x] && src1[x] <= src3[x]);
V
Vadim Pisarevsky 已提交
2468
    }
2469 2470
}

2471

2472 2473
static void inRange8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                      const uchar* src3, size_t step3, uchar* dst, size_t step, Size size)
2474
{
2475 2476
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
}
2477

2478 2479
static void inRange8s(const schar* src1, size_t step1, const schar* src2, size_t step2,
                      const schar* src3, size_t step3, uchar* dst, size_t step, Size size)
2480
{
2481 2482
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
}
2483

2484 2485
static void inRange16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2,
                       const ushort* src3, size_t step3, uchar* dst, size_t step, Size size)
2486
{
2487 2488
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
}
2489

2490 2491 2492 2493
static void inRange16s(const short* src1, size_t step1, const short* src2, size_t step2,
                       const short* src3, size_t step3, uchar* dst, size_t step, Size size)
{
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
2494 2495
}

2496 2497
static void inRange32s(const int* src1, size_t step1, const int* src2, size_t step2,
                       const int* src3, size_t step3, uchar* dst, size_t step, Size size)
2498
{
2499 2500
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
}
2501

2502 2503 2504 2505
static void inRange32f(const float* src1, size_t step1, const float* src2, size_t step2,
                       const float* src3, size_t step3, uchar* dst, size_t step, Size size)
{
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
2506 2507
}

2508 2509
static void inRange64f(const double* src1, size_t step1, const double* src2, size_t step2,
                       const double* src3, size_t step3, uchar* dst, size_t step, Size size)
2510
{
2511
    inRange_(src1, step1, src2, step2, src3, step3, dst, step, size);
2512
}
2513

2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
static void inRangeReduce(const uchar* src, uchar* dst, size_t len, int cn)
{
    int k = cn % 4 ? cn % 4 : 4;
    size_t i, j;
    if( k == 1 )
        for( i = j = 0; i < len; i++, j += cn )
            dst[i] = src[j];
    else if( k == 2 )
        for( i = j = 0; i < len; i++, j += cn )
            dst[i] = src[j] & src[j+1];
    else if( k == 3 )
        for( i = j = 0; i < len; i++, j += cn )
            dst[i] = src[j] & src[j+1] & src[j+2];
    else
        for( i = j = 0; i < len; i++, j += cn )
            dst[i] = src[j] & src[j+1] & src[j+2] & src[j+3];
2530

2531 2532 2533 2534
    for( ; k < cn; k += 4 )
    {
        for( i = 0, j = k; i < len; i++, j += cn )
            dst[i] &= src[j] & src[j+1] & src[j+2] & src[j+3];
V
Vadim Pisarevsky 已提交
2535
    }
2536
}
2537

2538 2539
typedef void (*InRangeFunc)( const uchar* src1, size_t step1, const uchar* src2, size_t step2,
                             const uchar* src3, size_t step3, uchar* dst, size_t step, Size sz );
2540

2541
static InRangeFunc inRangeTab[] =
2542
{
2543 2544
    (InRangeFunc)GET_OPTIMIZED(inRange8u), (InRangeFunc)GET_OPTIMIZED(inRange8s), (InRangeFunc)GET_OPTIMIZED(inRange16u),
    (InRangeFunc)GET_OPTIMIZED(inRange16s), (InRangeFunc)GET_OPTIMIZED(inRange32s), (InRangeFunc)GET_OPTIMIZED(inRange32f),
2545 2546
    (InRangeFunc)inRange64f, 0
};
2547

2548 2549
}

2550 2551
void cv::inRange(InputArray _src, InputArray _lowerb,
                 InputArray _upperb, OutputArray _dst)
2552 2553 2554
{
    int skind = _src.kind(), lkind = _lowerb.kind(), ukind = _upperb.kind();
    Mat src = _src.getMat(), lb = _lowerb.getMat(), ub = _upperb.getMat();
2555

2556
    bool lbScalar = false, ubScalar = false;
2557

2558
    if( (lkind == _InputArray::MATX && skind != _InputArray::MATX) ||
2559 2560 2561 2562 2563 2564 2565
        src.size != lb.size || src.type() != lb.type() )
    {
        if( !checkScalar(lb, src.type(), lkind, skind) )
            CV_Error( CV_StsUnmatchedSizes,
                     "The lower bounary is neither an array of the same size and same type as src, nor a scalar");
        lbScalar = true;
    }
2566

2567
    if( (ukind == _InputArray::MATX && skind != _InputArray::MATX) ||
2568 2569 2570 2571 2572 2573 2574
        src.size != ub.size || src.type() != ub.type() )
    {
        if( !checkScalar(ub, src.type(), ukind, skind) )
            CV_Error( CV_StsUnmatchedSizes,
                     "The upper bounary is neither an array of the same size and same type as src, nor a scalar");
        ubScalar = true;
    }
2575

2576
    CV_Assert( ((int)lbScalar ^ (int)ubScalar) == 0 );
2577

2578
    int cn = src.channels(), depth = src.depth();
2579

2580 2581
    size_t esz = src.elemSize();
    size_t blocksize0 = (size_t)(BLOCK_SIZE + esz-1)/esz;
2582

2583 2584 2585
    _dst.create(src.dims, src.size, CV_8U);
    Mat dst = _dst.getMat();
    InRangeFunc func = inRangeTab[depth];
2586

2587 2588 2589
    const Mat* arrays_sc[] = { &src, &dst, 0 };
    const Mat* arrays_nosc[] = { &src, &dst, &lb, &ub, 0 };
    uchar* ptrs[4];
2590

2591 2592
    NAryMatIterator it(lbScalar && ubScalar ? arrays_sc : arrays_nosc, ptrs);
    size_t total = it.size, blocksize = std::min(total, blocksize0);
2593

2594 2595 2596
    AutoBuffer<uchar> _buf(blocksize*(((int)lbScalar + (int)ubScalar)*esz + cn) + 2*cn*sizeof(int) + 128);
    uchar *buf = _buf, *mbuf = buf, *lbuf = 0, *ubuf = 0;
    buf = alignPtr(buf + blocksize*cn, 16);
2597

2598 2599 2600 2601
    if( lbScalar && ubScalar )
    {
        lbuf = buf;
        ubuf = buf = alignPtr(buf + blocksize*esz, 16);
2602

2603 2604
        CV_Assert( lb.type() == ub.type() );
        int scdepth = lb.depth();
2605

2606 2607 2608 2609
        if( scdepth != depth && depth < CV_32S )
        {
            int* ilbuf = (int*)alignPtr(buf + blocksize*esz, 16);
            int* iubuf = ilbuf + cn;
2610

2611 2612 2613
            BinaryFunc sccvtfunc = getConvertFunc(scdepth, CV_32S);
            sccvtfunc(lb.data, 0, 0, 0, (uchar*)ilbuf, 0, Size(cn, 1), 0);
            sccvtfunc(ub.data, 0, 0, 0, (uchar*)iubuf, 0, Size(cn, 1), 0);
2614
            int minval = cvRound(getMinVal(depth)), maxval = cvRound(getMaxVal(depth));
2615

2616 2617 2618 2619 2620 2621 2622 2623
            for( int k = 0; k < cn; k++ )
            {
                if( ilbuf[k] > iubuf[k] || ilbuf[k] > maxval || iubuf[k] < minval )
                    ilbuf[k] = minval+1, iubuf[k] = minval;
            }
            lb = Mat(cn, 1, CV_32S, ilbuf);
            ub = Mat(cn, 1, CV_32S, iubuf);
        }
2624

2625 2626 2627
        convertAndUnrollScalar( lb, src.type(), lbuf, blocksize );
        convertAndUnrollScalar( ub, src.type(), ubuf, blocksize );
    }
2628

2629
    for( size_t i = 0; i < it.nplanes; i++, ++it )
V
Vadim Pisarevsky 已提交
2630
    {
2631 2632
        for( size_t j = 0; j < total; j += blocksize )
        {
2633
            int bsz = (int)MIN(total - j, blocksize);
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
            size_t delta = bsz*esz;
            uchar *lptr = lbuf, *uptr = ubuf;
            if( !lbScalar )
            {
                lptr = ptrs[2];
                ptrs[2] += delta;
            }
            if( !ubScalar )
            {
                int idx = !lbScalar ? 3 : 2;
                uptr = ptrs[idx];
                ptrs[idx] += delta;
            }
            func( ptrs[0], 0, lptr, 0, uptr, 0, cn == 1 ? ptrs[1] : mbuf, 0, Size(bsz*cn, 1));
2648
			if( cn > 1 )
2649 2650 2651 2652
                inRangeReduce(mbuf, ptrs[1], bsz, cn);
            ptrs[0] += delta;
            ptrs[1] += bsz;
        }
V
Vadim Pisarevsky 已提交
2653
    }
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
}

/****************************************************************************************\
*                                Earlier API: cvAdd etc.                                 *
\****************************************************************************************/

CV_IMPL void
cvNot( const CvArr* srcarr, CvArr* dstarr )
{
    cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr);
2664
    CV_Assert( src.size == dst.size && src.type() == dst.type() );
2665 2666 2667 2668 2669 2670 2671 2672 2673
    cv::bitwise_not( src, dst );
}


CV_IMPL void
cvAnd( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2674
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2675 2676 2677 2678 2679
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
    cv::bitwise_and( src1, src2, dst, mask );
}

2680

2681 2682 2683 2684 2685
CV_IMPL void
cvOr( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2686
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
    cv::bitwise_or( src1, src2, dst, mask );
}


CV_IMPL void
cvXor( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2698
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
    cv::bitwise_xor( src1, src2, dst, mask );
}


CV_IMPL void
cvAndS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask;
2709
    CV_Assert( src.size == dst.size && src.type() == dst.type() );
2710 2711
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2712
    cv::bitwise_and( src, (const cv::Scalar&)s, dst, mask );
2713 2714 2715 2716 2717 2718 2719
}


CV_IMPL void
cvOrS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask;
2720
    CV_Assert( src.size == dst.size && src.type() == dst.type() );
2721 2722
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2723
    cv::bitwise_or( src, (const cv::Scalar&)s, dst, mask );
2724 2725 2726 2727 2728 2729 2730
}


CV_IMPL void
cvXorS( const CvArr* srcarr, CvScalar s, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr), mask;
2731
    CV_Assert( src.size == dst.size && src.type() == dst.type() );
2732 2733
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2734
    cv::bitwise_xor( src, (const cv::Scalar&)s, dst, mask );
2735 2736
}

2737

2738 2739 2740 2741
CV_IMPL void cvAdd( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2742
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
2743 2744
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2745
    cv::add( src1, src2, dst, mask, dst.type() );
2746 2747
}

2748

2749 2750 2751 2752
CV_IMPL void cvSub( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2753
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
2754 2755
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2756
    cv::subtract( src1, src2, dst, mask, dst.type() );
2757 2758
}

2759

2760 2761 2762 2763
CV_IMPL void cvAddS( const CvArr* srcarr1, CvScalar value, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1),
        dst = cv::cvarrToMat(dstarr), mask;
2764
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
2765 2766
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2767
    cv::add( src1, (const cv::Scalar&)value, dst, mask, dst.type() );
2768 2769
}

2770

2771 2772 2773 2774
CV_IMPL void cvSubRS( const CvArr* srcarr1, CvScalar value, CvArr* dstarr, const CvArr* maskarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1),
        dst = cv::cvarrToMat(dstarr), mask;
2775
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
2776 2777
    if( maskarr )
        mask = cv::cvarrToMat(maskarr);
2778
    cv::subtract( (const cv::Scalar&)value, src1, dst, mask, dst.type() );
2779 2780
}

2781

2782 2783 2784 2785 2786
CV_IMPL void cvMul( const CvArr* srcarr1, const CvArr* srcarr2,
                    CvArr* dstarr, double scale )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr);
2787 2788
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
    cv::multiply( src1, src2, dst, scale, dst.type() );
2789 2790
}

2791

2792 2793 2794 2795 2796
CV_IMPL void cvDiv( const CvArr* srcarr1, const CvArr* srcarr2,
                    CvArr* dstarr, double scale )
{
    cv::Mat src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr), mask;
2797
    CV_Assert( src2.size == dst.size && src2.channels() == dst.channels() );
2798 2799

    if( srcarr1 )
2800
        cv::divide( cv::cvarrToMat(srcarr1), src2, dst, scale, dst.type() );
2801
    else
2802
        cv::divide( scale, src2, dst, dst.type() );
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
}


CV_IMPL void
cvAddWeighted( const CvArr* srcarr1, double alpha,
               const CvArr* srcarr2, double beta,
               double gamma, CvArr* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), src2 = cv::cvarrToMat(srcarr2),
        dst = cv::cvarrToMat(dstarr);
2813 2814
    CV_Assert( src1.size == dst.size && src1.channels() == dst.channels() );
    cv::addWeighted( src1, alpha, src2, beta, gamma, dst, dst.type() );
2815 2816 2817 2818 2819 2820 2821
}


CV_IMPL  void
cvAbsDiff( const CvArr* srcarr1, const CvArr* srcarr2, CvArr* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2822
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2823 2824 2825 2826 2827 2828 2829 2830 2831

    cv::absdiff( src1, cv::cvarrToMat(srcarr2), dst );
}


CV_IMPL void
cvAbsDiffS( const CvArr* srcarr1, CvArr* dstarr, CvScalar scalar )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2832
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2833

2834
    cv::absdiff( src1, (const cv::Scalar&)scalar, dst );
2835 2836
}

2837

2838 2839 2840 2841 2842
CV_IMPL void
cvInRange( const void* srcarr1, const void* srcarr2,
           const void* srcarr3, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2843
    CV_Assert( src1.size == dst.size && dst.type() == CV_8U );
2844 2845 2846 2847

    cv::inRange( src1, cv::cvarrToMat(srcarr2), cv::cvarrToMat(srcarr3), dst );
}

2848

2849 2850 2851 2852
CV_IMPL void
cvInRangeS( const void* srcarr1, CvScalar lowerb, CvScalar upperb, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2853
    CV_Assert( src1.size == dst.size && dst.type() == CV_8U );
2854

2855
    cv::inRange( src1, (const cv::Scalar&)lowerb, (const cv::Scalar&)upperb, dst );
2856 2857 2858 2859 2860 2861 2862
}


CV_IMPL void
cvCmp( const void* srcarr1, const void* srcarr2, void* dstarr, int cmp_op )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2863
    CV_Assert( src1.size == dst.size && dst.type() == CV_8U );
2864 2865 2866 2867 2868 2869 2870 2871 2872

    cv::compare( src1, cv::cvarrToMat(srcarr2), dst, cmp_op );
}


CV_IMPL void
cvCmpS( const void* srcarr1, double value, void* dstarr, int cmp_op )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2873
    CV_Assert( src1.size == dst.size && dst.type() == CV_8U );
2874 2875 2876 2877 2878 2879 2880 2881 2882

    cv::compare( src1, value, dst, cmp_op );
}


CV_IMPL void
cvMin( const void* srcarr1, const void* srcarr2, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2883
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2884 2885 2886 2887 2888 2889 2890 2891 2892

    cv::min( src1, cv::cvarrToMat(srcarr2), dst );
}


CV_IMPL void
cvMax( const void* srcarr1, const void* srcarr2, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2893
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2894 2895 2896 2897

    cv::max( src1, cv::cvarrToMat(srcarr2), dst );
}

2898

2899 2900 2901 2902
CV_IMPL void
cvMinS( const void* srcarr1, double value, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2903
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2904 2905 2906 2907 2908 2909 2910 2911 2912

    cv::min( src1, value, dst );
}


CV_IMPL void
cvMaxS( const void* srcarr1, double value, void* dstarr )
{
    cv::Mat src1 = cv::cvarrToMat(srcarr1), dst = cv::cvarrToMat(dstarr);
2913
    CV_Assert( src1.size == dst.size && src1.type() == dst.type() );
2914 2915 2916 2917 2918

    cv::max( src1, value, dst );
}

/* End of file. */