color.cpp 139.2 KB
Newer Older
1 2 3 4 5 6 7 8
/*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.
//
9 10
//
//                           License Agreement
11 12
//                For Open Source Computer Vision Library
//
13 14
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved.
15 16 17 18 19 20 21 22 23 24 25 26
// 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.
//
27
//   * The name of the copyright holders may not be used to endorse or promote products
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
//     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*/

/********************************* COPYRIGHT NOTICE *******************************\
  The function for RGB to Lab conversion is based on the MATLAB script
  RGB2Lab.m translated by Mark Ruzon from C code by Yossi Rubner, 23 September 1997.
  See the page [http://vision.stanford.edu/~ruzon/software/rgblab.html]
\**********************************************************************************/

/********************************* COPYRIGHT NOTICE *******************************\
  Original code for Bayer->BGR/RGB conversion is provided by Dirk Schaefer
  from MD-Mathematische Dienste GmbH. Below is the copyright notice:

    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.

    Contributors License Agreement:

      Copyright (c) 2002,
      MD-Mathematische Dienste GmbH
      Im Defdahl 5-10
      44141 Dortmund
      Germany
      www.md-it.de
A
Andrey Kamaev 已提交
66

67 68
    Redistribution and use in source and binary forms,
    with or without modification, are permitted provided
A
Andrey Kamaev 已提交
69
    that the following conditions are met:
70 71

    Redistributions of source code must retain
A
Andrey Kamaev 已提交
72
    the above copyright notice, this list of conditions and the following disclaimer.
73 74
    Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
A
Andrey Kamaev 已提交
75
    and/or other materials provided with the distribution.
76
    The name of Contributor may not be used to endorse or promote products
A
Andrey Kamaev 已提交
77
    derived from this software without specific prior written permission.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

    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 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.
\**********************************************************************************/

#include "precomp.hpp"
93
#include <limits>
94
#include <iostream>
95

96 97
namespace cv
{
98 99 100 101 102 103 104

// computes cubic spline coefficients for a function: (xi=i, yi=f[i]), i=0..n
template<typename _Tp> static void splineBuild(const _Tp* f, int n, _Tp* tab)
{
    _Tp cn = 0;
    int i;
    tab[0] = tab[1] = (_Tp)0;
A
Andrey Kamaev 已提交
105

106 107 108 109 110 111
    for(i = 1; i < n-1; i++)
    {
        _Tp t = 3*(f[i+1] - 2*f[i] + f[i-1]);
        _Tp l = 1/(4 - tab[(i-1)*4]);
        tab[i*4] = l; tab[i*4+1] = (t - tab[(i-1)*4+1])*l;
    }
A
Andrey Kamaev 已提交
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    for(i = n-1; i >= 0; i--)
    {
        _Tp c = tab[i*4+1] - tab[i*4]*cn;
        _Tp b = f[i+1] - f[i] - (cn + c*2)*(_Tp)0.3333333333333333;
        _Tp d = (cn - c)*(_Tp)0.3333333333333333;
        tab[i*4] = f[i]; tab[i*4+1] = b;
        tab[i*4+2] = c; tab[i*4+3] = d;
        cn = c;
    }
}

// interpolates value of a function at x, 0 <= x <= n using a cubic spline.
template<typename _Tp> static inline _Tp splineInterpolate(_Tp x, const _Tp* tab, int n)
{
    int ix = cvFloor(x);
    ix = std::min(std::max(ix, 0), n-1);
    x -= ix;
    tab += ix*4;
    return ((tab[3]*x + tab[2])*x + tab[1])*x + tab[0];
A
Andrey Kamaev 已提交
132 133
}

134

135 136 137 138
template<typename _Tp> struct ColorChannel
{
    typedef float worktype_f;
    static _Tp max() { return std::numeric_limits<_Tp>::max(); }
A
Andrey Kamaev 已提交
139
    static _Tp half() { return (_Tp)(max()/2 + 1); }
140
};
141

142 143 144 145 146 147
template<> struct ColorChannel<float>
{
    typedef float worktype_f;
    static float max() { return 1.f; }
    static float half() { return 0.5f; }
};
148

149 150 151 152 153 154
/*template<> struct ColorChannel<double>
{
    typedef double worktype_f;
    static double max() { return 1.; }
    static double half() { return 0.5; }
};*/
155

A
Andrey Kamaev 已提交
156

157
///////////////////////////// Top-level template function ////////////////////////////////
158

159 160 161 162 163 164 165
template<class Cvt> void CvtColorLoop(const Mat& srcmat, Mat& dstmat, const Cvt& cvt)
{
    typedef typename Cvt::channel_type _Tp;
    Size sz = srcmat.size();
    const uchar* src = srcmat.data;
    uchar* dst = dstmat.data;
    size_t srcstep = srcmat.step, dststep = dstmat.step;
A
Andrey Kamaev 已提交
166

167 168 169 170
    if( srcmat.isContinuous() && dstmat.isContinuous() )
    {
        sz.width *= sz.height;
        sz.height = 1;
A
Andrey Kamaev 已提交
171 172
    }

173 174
    for( ; sz.height--; src += srcstep, dst += dststep )
        cvt((const _Tp*)src, (_Tp*)dst, sz.width);
175
}
A
Andrey Kamaev 已提交
176 177


178
////////////////// Various 3/4-channel to 3/4-channel RGB transformations /////////////////
A
Andrey Kamaev 已提交
179

180
template<typename _Tp> struct RGB2RGB
181
{
182
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    RGB2RGB(int _srccn, int _dstcn, int _blueIdx) : srccn(_srccn), dstcn(_dstcn), blueIdx(_blueIdx) {}
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn, dcn = dstcn, bidx = blueIdx;
        if( dcn == 3 )
        {
            n *= 3;
            for( int i = 0; i < n; i += 3, src += scn )
            {
                _Tp t0 = src[bidx], t1 = src[1], t2 = src[bidx ^ 2];
                dst[i] = t0; dst[i+1] = t1; dst[i+2] = t2;
            }
        }
        else if( scn == 3 )
        {
            n *= 3;
            _Tp alpha = ColorChannel<_Tp>::max();
            for( int i = 0; i < n; i += 3, dst += 4 )
            {
                _Tp t0 = src[i], t1 = src[i+1], t2 = src[i+2];
                dst[bidx] = t0; dst[1] = t1; dst[bidx^2] = t2; dst[3] = alpha;
            }
        }
        else
        {
            n *= 4;
            for( int i = 0; i < n; i += 4 )
            {
                _Tp t0 = src[i], t1 = src[i+1], t2 = src[i+2], t3 = src[i+3];
                dst[i] = t2; dst[i+1] = t1; dst[i+2] = t0; dst[i+3] = t3;
            }
        }
    }
A
Andrey Kamaev 已提交
217

218 219
    int srccn, dstcn, blueIdx;
};
A
Andrey Kamaev 已提交
220

221
/////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB //////////
222

223 224 225
struct RGB5x52RGB
{
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
226

227
    RGB5x52RGB(int _dstcn, int _blueIdx, int _greenBits)
A
Andrey Kamaev 已提交
228 229
        : dstcn(_dstcn), blueIdx(_blueIdx), greenBits(_greenBits) {}

230
    void operator()(const uchar* src, uchar* dst, int n) const
231
    {
232 233 234
        int dcn = dstcn, bidx = blueIdx;
        if( greenBits == 6 )
            for( int i = 0; i < n; i++, dst += dcn )
235 236
            {
                unsigned t = ((const ushort*)src)[i];
237
                dst[bidx] = (uchar)(t << 3);
238
                dst[1] = (uchar)((t >> 3) & ~3);
239 240 241
                dst[bidx ^ 2] = (uchar)((t >> 8) & ~7);
                if( dcn == 4 )
                    dst[3] = 255;
242 243
            }
        else
244
            for( int i = 0; i < n; i++, dst += dcn )
245 246
            {
                unsigned t = ((const ushort*)src)[i];
247
                dst[bidx] = (uchar)(t << 3);
248
                dst[1] = (uchar)((t >> 2) & ~7);
249 250 251
                dst[bidx ^ 2] = (uchar)((t >> 7) & ~7);
                if( dcn == 4 )
                    dst[3] = t & 0x8000 ? 255 : 0;
252 253
            }
    }
A
Andrey Kamaev 已提交
254

255 256
    int dstcn, blueIdx, greenBits;
};
257

A
Andrey Kamaev 已提交
258

259
struct RGB2RGB5x5
260
{
261
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
262

263
    RGB2RGB5x5(int _srccn, int _blueIdx, int _greenBits)
A
Andrey Kamaev 已提交
264 265
        : srccn(_srccn), blueIdx(_blueIdx), greenBits(_greenBits) {}

266
    void operator()(const uchar* src, uchar* dst, int n) const
267
    {
268 269 270
        int scn = srccn, bidx = blueIdx;
        if( greenBits == 6 )
            for( int i = 0; i < n; i++, src += scn )
271
            {
272 273 274 275 276 277
                ((ushort*)dst)[i] = (ushort)((src[bidx] >> 3)|((src[1]&~3) << 3)|((src[bidx^2]&~7) << 8));
            }
        else if( scn == 3 )
            for( int i = 0; i < n; i++, src += 3 )
            {
                ((ushort*)dst)[i] = (ushort)((src[bidx] >> 3)|((src[1]&~7) << 2)|((src[bidx^2]&~7) << 7));
278 279
            }
        else
280
            for( int i = 0; i < n; i++, src += 4 )
281
            {
282 283
                ((ushort*)dst)[i] = (ushort)((src[bidx] >> 3)|((src[1]&~7) << 2)|
                    ((src[bidx^2]&~7) << 7)|(src[3] ? 0x8000 : 0));
284 285
            }
    }
A
Andrey Kamaev 已提交
286

287 288
    int srccn, blueIdx, greenBits;
};
A
Andrey Kamaev 已提交
289

290
///////////////////////////////// Color to/from Grayscale ////////////////////////////////
291

292 293
template<typename _Tp>
struct Gray2RGB
294
{
295
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
296

297 298
    Gray2RGB(int _dstcn) : dstcn(_dstcn) {}
    void operator()(const _Tp* src, _Tp* dst, int n) const
299
    {
300 301 302 303 304 305
        if( dstcn == 3 )
            for( int i = 0; i < n; i++, dst += 3 )
            {
                dst[0] = dst[1] = dst[2] = src[i];
            }
        else
306
        {
307 308
            _Tp alpha = ColorChannel<_Tp>::max();
            for( int i = 0; i < n; i++, dst += 4 )
309
            {
310 311
                dst[0] = dst[1] = dst[2] = src[i];
                dst[3] = alpha;
312 313 314
            }
        }
    }
A
Andrey Kamaev 已提交
315

316 317
    int dstcn;
};
A
Andrey Kamaev 已提交
318

319

320
struct Gray2RGB5x5
321
{
322
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
323

324 325
    Gray2RGB5x5(int _greenBits) : greenBits(_greenBits) {}
    void operator()(const uchar* src, uchar* dst, int n) const
326
    {
327 328
        if( greenBits == 6 )
            for( int i = 0; i < n; i++ )
329
            {
330 331
                int t = src[i];
                ((ushort*)dst)[i] = (ushort)((t >> 3)|((t & ~3) << 3)|((t & ~7) << 8));
332 333
            }
        else
334
            for( int i = 0; i < n; i++ )
335
            {
336 337
                int t = src[i] >> 3;
                ((ushort*)dst)[i] = (ushort)(t|(t << 5)|(t << 10));
338 339
            }
    }
340 341
    int greenBits;
};
342 343


344 345 346
#undef R2Y
#undef G2Y
#undef B2Y
A
Andrey Kamaev 已提交
347

348
enum
349
{
350 351 352 353 354 355 356 357
    yuv_shift = 14,
    xyz_shift = 12,
    R2Y = 4899,
    G2Y = 9617,
    B2Y = 1868,
    BLOCK_SIZE = 256
};

358

359 360 361
struct RGB5x52Gray
{
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
362

363 364
    RGB5x52Gray(int _greenBits) : greenBits(_greenBits) {}
    void operator()(const uchar* src, uchar* dst, int n) const
365
    {
366 367
        if( greenBits == 6 )
            for( int i = 0; i < n; i++ )
368
            {
369 370 371 372
                int t = ((ushort*)src)[i];
                dst[i] = (uchar)CV_DESCALE(((t << 3) & 0xf8)*B2Y +
                                           ((t >> 3) & 0xfc)*G2Y +
                                           ((t >> 8) & 0xf8)*R2Y, yuv_shift);
373 374
            }
        else
375
            for( int i = 0; i < n; i++ )
376
            {
377 378 379 380
                int t = ((ushort*)src)[i];
                dst[i] = (uchar)CV_DESCALE(((t << 3) & 0xf8)*B2Y +
                                           ((t >> 2) & 0xf8)*G2Y +
                                           ((t >> 7) & 0xf8)*R2Y, yuv_shift);
381 382
            }
    }
383 384
    int greenBits;
};
385 386


387
template<typename _Tp> struct RGB2Gray
388
{
389
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
390

391
    RGB2Gray(int _srccn, int blueIdx, const float* _coeffs) : srccn(_srccn)
392
    {
393 394 395 396 397
        static const float coeffs0[] = { 0.299f, 0.587f, 0.114f };
        memcpy( coeffs, _coeffs ? _coeffs : coeffs0, 3*sizeof(coeffs[0]) );
        if(blueIdx == 0)
            std::swap(coeffs[0], coeffs[2]);
    }
A
Andrey Kamaev 已提交
398

399 400 401 402 403 404 405 406 407 408 409
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn;
        float cb = coeffs[0], cg = coeffs[1], cr = coeffs[2];
        for(int i = 0; i < n; i++, src += scn)
            dst[i] = saturate_cast<_Tp>(src[0]*cb + src[1]*cg + src[2]*cr);
    }
    int srccn;
    float coeffs[3];
};

A
Andrey Kamaev 已提交
410

411 412 413
template<> struct RGB2Gray<uchar>
{
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
414

415 416 417 418
    RGB2Gray<uchar>(int _srccn, int blueIdx, const int* coeffs) : srccn(_srccn)
    {
        const int coeffs0[] = { R2Y, G2Y, B2Y };
        if(!coeffs) coeffs = coeffs0;
A
Andrey Kamaev 已提交
419

420 421
        int b = 0, g = 0, r = (1 << (yuv_shift-1));
        int db = coeffs[blueIdx^2], dg = coeffs[1], dr = coeffs[blueIdx];
A
Andrey Kamaev 已提交
422

423
        for( int i = 0; i < 256; i++, b += db, g += dg, r += dr )
424 425 426 427 428 429
        {
            tab[i] = b;
            tab[i+256] = g;
            tab[i+512] = r;
        }
    }
430
    void operator()(const uchar* src, uchar* dst, int n) const
431
    {
432
        int scn = srccn;
A
Andrey Kamaev 已提交
433
        const int* _tab = tab;
434 435
        for(int i = 0; i < n; i++, src += scn)
            dst[i] = (uchar)((_tab[src[0]] + _tab[src[1]+256] + _tab[src[2]+512]) >> yuv_shift);
436
    }
A
Andrey Kamaev 已提交
437
    int srccn;
438 439
    int tab[256*3];
};
440

A
Andrey Kamaev 已提交
441

442
template<> struct RGB2Gray<ushort>
443
{
444
    typedef ushort channel_type;
A
Andrey Kamaev 已提交
445

446 447 448 449 450 451 452
    RGB2Gray<ushort>(int _srccn, int blueIdx, const int* _coeffs) : srccn(_srccn)
    {
        static const int coeffs0[] = { R2Y, G2Y, B2Y };
        memcpy(coeffs, _coeffs ? _coeffs : coeffs0, 3*sizeof(coeffs[0]));
        if( blueIdx == 0 )
            std::swap(coeffs[0], coeffs[2]);
    }
A
Andrey Kamaev 已提交
453

454 455 456 457 458 459 460 461 462
    void operator()(const ushort* src, ushort* dst, int n) const
    {
        int scn = srccn, cb = coeffs[0], cg = coeffs[1], cr = coeffs[2];
        for(int i = 0; i < n; i++, src += scn)
            dst[i] = (ushort)CV_DESCALE((unsigned)(src[0]*cb + src[1]*cg + src[2]*cr), yuv_shift);
    }
    int srccn;
    int coeffs[3];
};
463

A
Andrey Kamaev 已提交
464

465
///////////////////////////////////// RGB <-> YCrCb //////////////////////////////////////
466

467
template<typename _Tp> struct RGB2YCrCb_f
468
{
469
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
470

471
    RGB2YCrCb_f(int _srccn, int _blueIdx, const float* _coeffs) : srccn(_srccn), blueIdx(_blueIdx)
A
Andrey Kamaev 已提交
472 473 474 475 476 477
    {
        static const float coeffs0[] = {0.299f, 0.587f, 0.114f, 0.713f, 0.564f};
        memcpy(coeffs, _coeffs ? _coeffs : coeffs0, 5*sizeof(coeffs[0]));
        if(blueIdx==0) std::swap(coeffs[0], coeffs[2]);
    }

478 479 480 481
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn, bidx = blueIdx;
        const _Tp delta = ColorChannel<_Tp>::half();
A
Andrey Kamaev 已提交
482
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2], C3 = coeffs[3], C4 = coeffs[4];
483 484 485 486 487 488 489 490 491 492
        n *= 3;
        for(int i = 0; i < n; i += 3, src += scn)
        {
            _Tp Y = saturate_cast<_Tp>(src[0]*C0 + src[1]*C1 + src[2]*C2);
            _Tp Cr = saturate_cast<_Tp>((src[bidx^2] - Y)*C3 + delta);
            _Tp Cb = saturate_cast<_Tp>((src[bidx] - Y)*C4 + delta);
            dst[i] = Y; dst[i+1] = Cr; dst[i+2] = Cb;
        }
    }
    int srccn, blueIdx;
A
Andrey Kamaev 已提交
493
    float coeffs[5];
494
};
495 496


497
template<typename _Tp> struct RGB2YCrCb_i
498
{
499
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
500

501
    RGB2YCrCb_i(int _srccn, int _blueIdx, const int* _coeffs)
A
Andrey Kamaev 已提交
502 503 504 505 506 507
        : srccn(_srccn), blueIdx(_blueIdx)
    {
        static const int coeffs0[] = {R2Y, G2Y, B2Y, 11682, 9241};
        memcpy(coeffs, _coeffs ? _coeffs : coeffs0, 5*sizeof(coeffs[0]));
        if(blueIdx==0) std::swap(coeffs[0], coeffs[2]);
    }
508 509 510
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn, bidx = blueIdx;
A
Andrey Kamaev 已提交
511
        int C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2], C3 = coeffs[3], C4 = coeffs[4];
512 513 514 515 516 517 518 519 520 521 522 523 524
        int delta = ColorChannel<_Tp>::half()*(1 << yuv_shift);
        n *= 3;
        for(int i = 0; i < n; i += 3, src += scn)
        {
            int Y = CV_DESCALE(src[0]*C0 + src[1]*C1 + src[2]*C2, yuv_shift);
            int Cr = CV_DESCALE((src[bidx^2] - Y)*C3 + delta, yuv_shift);
            int Cb = CV_DESCALE((src[bidx] - Y)*C4 + delta, yuv_shift);
            dst[i] = saturate_cast<_Tp>(Y);
            dst[i+1] = saturate_cast<_Tp>(Cr);
            dst[i+2] = saturate_cast<_Tp>(Cb);
        }
    }
    int srccn, blueIdx;
A
Andrey Kamaev 已提交
525 526
    int coeffs[5];
};
527 528


529 530 531
template<typename _Tp> struct YCrCb2RGB_f
{
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
532

533
    YCrCb2RGB_f(int _dstcn, int _blueIdx, const float* _coeffs)
A
Andrey Kamaev 已提交
534 535 536 537 538
        : dstcn(_dstcn), blueIdx(_blueIdx)
    {
        static const float coeffs0[] = {1.403f, -0.714f, -0.344f, 1.773f};
        memcpy(coeffs, _coeffs ? _coeffs : coeffs0, 4*sizeof(coeffs[0]));
    }
539
    void operator()(const _Tp* src, _Tp* dst, int n) const
540
    {
541 542 543 544 545
        int dcn = dstcn, bidx = blueIdx;
        const _Tp delta = ColorChannel<_Tp>::half(), alpha = ColorChannel<_Tp>::max();
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2], C3 = coeffs[3];
        n *= 3;
        for(int i = 0; i < n; i += 3, dst += dcn)
546
        {
547 548 549
            _Tp Y = src[i];
            _Tp Cr = src[i+1];
            _Tp Cb = src[i+2];
A
Andrey Kamaev 已提交
550

551 552 553
            _Tp b = saturate_cast<_Tp>(Y + (Cb - delta)*C3);
            _Tp g = saturate_cast<_Tp>(Y + (Cb - delta)*C2 + (Cr - delta)*C1);
            _Tp r = saturate_cast<_Tp>(Y + (Cr - delta)*C0);
A
Andrey Kamaev 已提交
554

555 556 557
            dst[bidx] = b; dst[1] = g; dst[bidx^2] = r;
            if( dcn == 4 )
                dst[3] = alpha;
558 559
        }
    }
560
    int dstcn, blueIdx;
A
Andrey Kamaev 已提交
561 562
    float coeffs[4];
};
563 564


565
template<typename _Tp> struct YCrCb2RGB_i
566
{
567
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
568

569 570
    YCrCb2RGB_i(int _dstcn, int _blueIdx, const int* _coeffs)
        : dstcn(_dstcn), blueIdx(_blueIdx)
571
    {
A
Andrey Kamaev 已提交
572 573
        static const int coeffs0[] = {22987, -11698, -5636, 29049};
        memcpy(coeffs, _coeffs ? _coeffs : coeffs0, 4*sizeof(coeffs[0]));
574
    }
A
Andrey Kamaev 已提交
575

576 577 578 579 580 581 582
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int dcn = dstcn, bidx = blueIdx;
        const _Tp delta = ColorChannel<_Tp>::half(), alpha = ColorChannel<_Tp>::max();
        int C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2], C3 = coeffs[3];
        n *= 3;
        for(int i = 0; i < n; i += 3, dst += dcn)
583
        {
584 585 586
            _Tp Y = src[i];
            _Tp Cr = src[i+1];
            _Tp Cb = src[i+2];
A
Andrey Kamaev 已提交
587

588 589 590
            int b = Y + CV_DESCALE((Cb - delta)*C3, yuv_shift);
            int g = Y + CV_DESCALE((Cb - delta)*C2 + (Cr - delta)*C1, yuv_shift);
            int r = Y + CV_DESCALE((Cr - delta)*C0, yuv_shift);
A
Andrey Kamaev 已提交
591

592 593 594 595 596
            dst[bidx] = saturate_cast<_Tp>(b);
            dst[1] = saturate_cast<_Tp>(g);
            dst[bidx^2] = saturate_cast<_Tp>(r);
            if( dcn == 4 )
                dst[3] = alpha;
597 598
        }
    }
599 600
    int dstcn, blueIdx;
    int coeffs[4];
A
Andrey Kamaev 已提交
601 602
};

603

604
////////////////////////////////////// RGB <-> XYZ ///////////////////////////////////////
605

606 607 608 609 610 611
static const float sRGB2XYZ_D65[] =
{
    0.412453f, 0.357580f, 0.180423f,
    0.212671f, 0.715160f, 0.072169f,
    0.019334f, 0.119193f, 0.950227f
};
A
Andrey Kamaev 已提交
612

613
static const float XYZ2sRGB_D65[] =
614
{
615 616 617 618
    3.240479f, -1.53715f, -0.498535f,
    -0.969256f, 1.875991f, 0.041556f,
    0.055648f, -0.204043f, 1.057311f
};
A
Andrey Kamaev 已提交
619

620 621 622
template<typename _Tp> struct RGB2XYZ_f
{
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
    RGB2XYZ_f(int _srccn, int blueIdx, const float* _coeffs) : srccn(_srccn)
    {
        memcpy(coeffs, _coeffs ? _coeffs : sRGB2XYZ_D65, 9*sizeof(coeffs[0]));
        if(blueIdx == 0)
        {
            std::swap(coeffs[0], coeffs[2]);
            std::swap(coeffs[3], coeffs[5]);
            std::swap(coeffs[6], coeffs[8]);
        }
    }
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn;
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
A
Andrey Kamaev 已提交
640

641 642 643
        n *= 3;
        for(int i = 0; i < n; i += 3, src += scn)
        {
A
Andrey Kamaev 已提交
644 645 646
            _Tp X = saturate_cast<_Tp>(src[0]*C0 + src[1]*C1 + src[2]*C2);
            _Tp Y = saturate_cast<_Tp>(src[0]*C3 + src[1]*C4 + src[2]*C5);
            _Tp Z = saturate_cast<_Tp>(src[0]*C6 + src[1]*C7 + src[2]*C8);
647 648 649 650 651
            dst[i] = X; dst[i+1] = Y; dst[i+2] = Z;
        }
    }
    int srccn;
    float coeffs[9];
652 653 654
};


655
template<typename _Tp> struct RGB2XYZ_i
656
{
657
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
658

659 660 661 662
    RGB2XYZ_i(int _srccn, int blueIdx, const float* _coeffs) : srccn(_srccn)
    {
        static const int coeffs0[] =
        {
A
Andrey Kamaev 已提交
663 664
            1689,    1465,    739,
            871,     2929,    296,
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            79,      488,     3892
        };
        for( int i = 0; i < 9; i++ )
            coeffs[i] = _coeffs ? cvRound(_coeffs[i]*(1 << xyz_shift)) : coeffs0[i];
        if(blueIdx == 0)
        {
            std::swap(coeffs[0], coeffs[2]);
            std::swap(coeffs[3], coeffs[5]);
            std::swap(coeffs[6], coeffs[8]);
        }
    }
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int scn = srccn;
        int C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
            C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
            C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        n *= 3;
        for(int i = 0; i < n; i += 3, src += scn)
        {
            int X = CV_DESCALE(src[0]*C0 + src[1]*C1 + src[2]*C2, xyz_shift);
            int Y = CV_DESCALE(src[0]*C3 + src[1]*C4 + src[2]*C5, xyz_shift);
            int Z = CV_DESCALE(src[0]*C6 + src[1]*C7 + src[2]*C8, xyz_shift);
            dst[i] = saturate_cast<_Tp>(X); dst[i+1] = saturate_cast<_Tp>(Y);
            dst[i+2] = saturate_cast<_Tp>(Z);
        }
    }
    int srccn;
    int coeffs[9];
};
A
Andrey Kamaev 已提交
695 696


697 698 699
template<typename _Tp> struct XYZ2RGB_f
{
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
700

701 702 703 704 705 706 707 708 709 710 711
    XYZ2RGB_f(int _dstcn, int _blueIdx, const float* _coeffs)
    : dstcn(_dstcn), blueIdx(_blueIdx)
    {
        memcpy(coeffs, _coeffs ? _coeffs : XYZ2sRGB_D65, 9*sizeof(coeffs[0]));
        if(blueIdx == 0)
        {
            std::swap(coeffs[0], coeffs[6]);
            std::swap(coeffs[1], coeffs[7]);
            std::swap(coeffs[2], coeffs[8]);
        }
    }
A
Andrey Kamaev 已提交
712

713 714 715
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int dcn = dstcn;
A
Andrey Kamaev 已提交
716
        _Tp alpha = ColorChannel<_Tp>::max();
717 718 719 720 721 722
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        n *= 3;
        for(int i = 0; i < n; i += 3, dst += dcn)
        {
A
Andrey Kamaev 已提交
723 724 725
            _Tp B = saturate_cast<_Tp>(src[i]*C0 + src[i+1]*C1 + src[i+2]*C2);
            _Tp G = saturate_cast<_Tp>(src[i]*C3 + src[i+1]*C4 + src[i+2]*C5);
            _Tp R = saturate_cast<_Tp>(src[i]*C6 + src[i+1]*C7 + src[i+2]*C8);
726
            dst[0] = B; dst[1] = G; dst[2] = R;
A
Andrey Kamaev 已提交
727 728
            if( dcn == 4 )
                dst[3] = alpha;
729 730 731 732
        }
    }
    int dstcn, blueIdx;
    float coeffs[9];
733 734 735
};


736
template<typename _Tp> struct XYZ2RGB_i
737
{
738
    typedef _Tp channel_type;
A
Andrey Kamaev 已提交
739

740 741
    XYZ2RGB_i(int _dstcn, int _blueIdx, const int* _coeffs)
    : dstcn(_dstcn), blueIdx(_blueIdx)
742
    {
743
        static const int coeffs0[] =
744
        {
A
Andrey Kamaev 已提交
745 746
            13273,  -6296,  -2042,
            -3970,   7684,    170,
747 748 749 750
              228,   -836,   4331
        };
        for(int i = 0; i < 9; i++)
            coeffs[i] = _coeffs ? cvRound(_coeffs[i]*(1 << xyz_shift)) : coeffs0[i];
A
Andrey Kamaev 已提交
751

752 753 754 755 756
        if(blueIdx == 0)
        {
            std::swap(coeffs[0], coeffs[6]);
            std::swap(coeffs[1], coeffs[7]);
            std::swap(coeffs[2], coeffs[8]);
757 758
        }
    }
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        int dcn = dstcn;
        _Tp alpha = ColorChannel<_Tp>::max();
        int C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
            C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
            C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        n *= 3;
        for(int i = 0; i < n; i += 3, dst += dcn)
        {
            int B = CV_DESCALE(src[i]*C0 + src[i+1]*C1 + src[i+2]*C2, xyz_shift);
            int G = CV_DESCALE(src[i]*C3 + src[i+1]*C4 + src[i+2]*C5, xyz_shift);
            int R = CV_DESCALE(src[i]*C6 + src[i+1]*C7 + src[i+2]*C8, xyz_shift);
            dst[0] = saturate_cast<_Tp>(B); dst[1] = saturate_cast<_Tp>(G);
            dst[2] = saturate_cast<_Tp>(R);
            if( dcn == 4 )
A
Andrey Kamaev 已提交
775
                dst[3] = alpha;
776 777 778 779 780
        }
    }
    int dstcn, blueIdx;
    int coeffs[9];
};
A
Andrey Kamaev 已提交
781

782 783 784 785 786 787 788

////////////////////////////////////// RGB <-> HSV ///////////////////////////////////////


struct RGB2HSV_b
{
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
789

790
    RGB2HSV_b(int _srccn, int _blueIdx, int _hrange)
791 792 793 794
    : srccn(_srccn), blueIdx(_blueIdx), hrange(_hrange)
    {
        CV_Assert( hrange == 180 || hrange == 256 );
    }
A
Andrey Kamaev 已提交
795

796
    void operator()(const uchar* src, uchar* dst, int n) const
797
    {
798 799
        int i, bidx = blueIdx, scn = srccn;
        const int hsv_shift = 12;
A
Andrey Kamaev 已提交
800

801 802 803 804
        static int sdiv_table[256];
        static int hdiv_table180[256];
        static int hdiv_table256[256];
        static volatile bool initialized = false;
A
Andrey Kamaev 已提交
805

806 807
        int hr = hrange;
        const int* hdiv_table = hr == 180 ? hdiv_table180 : hdiv_table256;
808
        n *= 3;
A
Andrey Kamaev 已提交
809

810 811 812 813 814 815 816 817 818 819 820
        if( !initialized )
        {
            sdiv_table[0] = hdiv_table180[0] = hdiv_table256[0] = 0;
            for( i = 1; i < 256; i++ )
            {
                sdiv_table[i] = saturate_cast<int>((255 << hsv_shift)/(1.*i));
                hdiv_table180[i] = saturate_cast<int>((180 << hsv_shift)/(6.*i));
                hdiv_table256[i] = saturate_cast<int>((256 << hsv_shift)/(6.*i));
            }
            initialized = true;
        }
A
Andrey Kamaev 已提交
821

822
        for( i = 0; i < n; i += 3, src += scn )
823
        {
824
            int b = src[bidx], g = src[1], r = src[bidx^2];
825 826 827
            int h, s, v = b;
            int vmin = b, diff;
            int vr, vg;
A
Andrey Kamaev 已提交
828

829 830 831 832
            CV_CALC_MAX_8U( v, g );
            CV_CALC_MAX_8U( v, r );
            CV_CALC_MIN_8U( vmin, g );
            CV_CALC_MIN_8U( vmin, r );
A
Andrey Kamaev 已提交
833

834 835 836
            diff = v - vmin;
            vr = v == r ? -1 : 0;
            vg = v == g ? -1 : 0;
A
Andrey Kamaev 已提交
837

838
            s = (diff * sdiv_table[v] + (1 << (hsv_shift-1))) >> hsv_shift;
839 840
            h = (vr & (g - b)) +
                (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff))));
841
            h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift;
842
            h += h < 0 ? hr : 0;
A
Andrey Kamaev 已提交
843

844
            dst[i] = saturate_cast<uchar>(h);
845 846 847 848
            dst[i+1] = (uchar)s;
            dst[i+2] = (uchar)v;
        }
    }
A
Andrey Kamaev 已提交
849

850
    int srccn, blueIdx, hrange;
A
Andrey Kamaev 已提交
851 852
};

853

854
struct RGB2HSV_f
855
{
856
    typedef float channel_type;
A
Andrey Kamaev 已提交
857

858 859
    RGB2HSV_f(int _srccn, int _blueIdx, float _hrange)
    : srccn(_srccn), blueIdx(_blueIdx), hrange(_hrange) {}
A
Andrey Kamaev 已提交
860

861
    void operator()(const float* src, float* dst, int n) const
862
    {
863 864 865
        int i, bidx = blueIdx, scn = srccn;
        float hscale = hrange*(1.f/360.f);
        n *= 3;
A
Andrey Kamaev 已提交
866

867
        for( i = 0; i < n; i += 3, src += scn )
868
        {
869
            float b = src[bidx], g = src[1], r = src[bidx^2];
870
            float h, s, v;
A
Andrey Kamaev 已提交
871

872
            float vmin, diff;
A
Andrey Kamaev 已提交
873

874 875 876 877 878
            v = vmin = r;
            if( v < g ) v = g;
            if( v < b ) v = b;
            if( vmin > g ) vmin = g;
            if( vmin > b ) vmin = b;
A
Andrey Kamaev 已提交
879

880 881 882 883 884 885 886 887 888
            diff = v - vmin;
            s = diff/(float)(fabs(v) + FLT_EPSILON);
            diff = (float)(60./(diff + FLT_EPSILON));
            if( v == r )
                h = (g - b)*diff;
            else if( v == g )
                h = (b - r)*diff + 120.f;
            else
                h = (r - g)*diff + 240.f;
A
Andrey Kamaev 已提交
889

890
            if( h < 0 ) h += 360.f;
A
Andrey Kamaev 已提交
891

892
            dst[i] = h*hscale;
893 894 895 896
            dst[i+1] = s;
            dst[i+2] = v;
        }
    }
A
Andrey Kamaev 已提交
897

898 899 900
    int srccn, blueIdx;
    float hrange;
};
901 902


903
struct HSV2RGB_f
904
{
905
    typedef float channel_type;
A
Andrey Kamaev 已提交
906

907 908
    HSV2RGB_f(int _dstcn, int _blueIdx, float _hrange)
    : dstcn(_dstcn), blueIdx(_blueIdx), hscale(6.f/_hrange) {}
A
Andrey Kamaev 已提交
909

910
    void operator()(const float* src, float* dst, int n) const
911
    {
912 913 914 915
        int i, bidx = blueIdx, dcn = dstcn;
        float _hscale = hscale;
        float alpha = ColorChannel<float>::max();
        n *= 3;
A
Andrey Kamaev 已提交
916

917
        for( i = 0; i < n; i += 3, dst += dcn )
918 919 920 921 922 923 924 925 926 927 928 929
        {
            float h = src[i], s = src[i+1], v = src[i+2];
            float b, g, r;

            if( s == 0 )
                b = g = r = v;
            else
            {
                static const int sector_data[][3]=
                    {{1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0}};
                float tab[4];
                int sector;
930
                h *= _hscale;
931 932 933 934 935 936
                if( h < 0 )
                    do h += 6; while( h < 0 );
                else if( h >= 6 )
                    do h -= 6; while( h >= 6 );
                sector = cvFloor(h);
                h -= sector;
937 938 939 940 941
                if( (unsigned)sector >= 6u )
                {
                    sector = 0;
                    h = 0.f;
                }
942 943 944 945 946

                tab[0] = v;
                tab[1] = v*(1.f - s);
                tab[2] = v*(1.f - s*h);
                tab[3] = v*(1.f - s*(1.f - h));
A
Andrey Kamaev 已提交
947

948 949 950 951 952
                b = tab[sector_data[sector][0]];
                g = tab[sector_data[sector][1]];
                r = tab[sector_data[sector][2]];
            }

953
            dst[bidx] = b;
954
            dst[1] = g;
955 956 957
            dst[bidx^2] = r;
            if( dcn == 4 )
                dst[3] = alpha;
958 959 960
        }
    }

961 962 963
    int dstcn, blueIdx;
    float hscale;
};
A
Andrey Kamaev 已提交
964

965

966
struct HSV2RGB_b
967
{
968
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
969

970
    HSV2RGB_b(int _dstcn, int _blueIdx, int _hrange)
971
    : dstcn(_dstcn), cvt(3, _blueIdx, (float)_hrange)
972
    {}
A
Andrey Kamaev 已提交
973

974
    void operator()(const uchar* src, uchar* dst, int n) const
975
    {
976 977 978
        int i, j, dcn = dstcn;
        uchar alpha = ColorChannel<uchar>::max();
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
979

980
        for( i = 0; i < n; i += BLOCK_SIZE, src += BLOCK_SIZE*3 )
981
        {
982
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
983

984
            for( j = 0; j < dn*3; j += 3 )
985
            {
986 987 988
                buf[j] = src[j];
                buf[j+1] = src[j+1]*(1.f/255.f);
                buf[j+2] = src[j+2]*(1.f/255.f);
989
            }
990
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
991

992
            for( j = 0; j < dn*3; j += 3, dst += dcn )
993
            {
994 995 996 997 998
                dst[0] = saturate_cast<uchar>(buf[j]*255.f);
                dst[1] = saturate_cast<uchar>(buf[j+1]*255.f);
                dst[2] = saturate_cast<uchar>(buf[j+2]*255.f);
                if( dcn == 4 )
                    dst[3] = alpha;
999 1000 1001
            }
        }
    }
A
Andrey Kamaev 已提交
1002

1003 1004 1005
    int dstcn;
    HSV2RGB_f cvt;
};
1006

A
Andrey Kamaev 已提交
1007

1008
///////////////////////////////////// RGB <-> HLS ////////////////////////////////////////
1009

1010
struct RGB2HLS_f
1011
{
1012
    typedef float channel_type;
A
Andrey Kamaev 已提交
1013

1014 1015
    RGB2HLS_f(int _srccn, int _blueIdx, float _hrange)
    : srccn(_srccn), blueIdx(_blueIdx), hrange(_hrange) {}
A
Andrey Kamaev 已提交
1016

1017
    void operator()(const float* src, float* dst, int n) const
1018
    {
1019 1020 1021
        int i, bidx = blueIdx, scn = srccn;
        float hscale = hrange*(1.f/360.f);
        n *= 3;
A
Andrey Kamaev 已提交
1022

1023
        for( i = 0; i < n; i += 3, src += scn )
1024
        {
1025
            float b = src[bidx], g = src[1], r = src[bidx^2];
1026 1027
            float h = 0.f, s = 0.f, l;
            float vmin, vmax, diff;
A
Andrey Kamaev 已提交
1028

1029 1030 1031 1032 1033
            vmax = vmin = r;
            if( vmax < g ) vmax = g;
            if( vmax < b ) vmax = b;
            if( vmin > g ) vmin = g;
            if( vmin > b ) vmin = b;
A
Andrey Kamaev 已提交
1034

1035 1036
            diff = vmax - vmin;
            l = (vmax + vmin)*0.5f;
A
Andrey Kamaev 已提交
1037

1038 1039 1040 1041
            if( diff > FLT_EPSILON )
            {
                s = l < 0.5f ? diff/(vmax + vmin) : diff/(2 - vmax - vmin);
                diff = 60.f/diff;
A
Andrey Kamaev 已提交
1042

1043 1044 1045 1046 1047 1048
                if( vmax == r )
                    h = (g - b)*diff;
                else if( vmax == g )
                    h = (b - r)*diff + 120.f;
                else
                    h = (r - g)*diff + 240.f;
A
Andrey Kamaev 已提交
1049

1050 1051
                if( h < 0.f ) h += 360.f;
            }
A
Andrey Kamaev 已提交
1052

1053
            dst[i] = h*hscale;
1054 1055 1056 1057
            dst[i+1] = l;
            dst[i+2] = s;
        }
    }
A
Andrey Kamaev 已提交
1058

1059 1060 1061
    int srccn, blueIdx;
    float hrange;
};
A
Andrey Kamaev 已提交
1062 1063


1064
struct RGB2HLS_b
1065
{
1066
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1067

1068 1069
    RGB2HLS_b(int _srccn, int _blueIdx, int _hrange)
    : srccn(_srccn), cvt(3, _blueIdx, (float)_hrange) {}
A
Andrey Kamaev 已提交
1070

1071
    void operator()(const uchar* src, uchar* dst, int n) const
1072
    {
1073 1074
        int i, j, scn = srccn;
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
1075

1076
        for( i = 0; i < n; i += BLOCK_SIZE, dst += BLOCK_SIZE*3 )
1077
        {
1078
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
1079

1080
            for( j = 0; j < dn*3; j += 3, src += scn )
1081
            {
1082 1083 1084
                buf[j] = src[0]*(1.f/255.f);
                buf[j+1] = src[1]*(1.f/255.f);
                buf[j+2] = src[2]*(1.f/255.f);
1085
            }
1086
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
1087

1088
            for( j = 0; j < dn*3; j += 3 )
1089
            {
1090 1091 1092
                dst[j] = saturate_cast<uchar>(buf[j]);
                dst[j+1] = saturate_cast<uchar>(buf[j+1]*255.f);
                dst[j+2] = saturate_cast<uchar>(buf[j+2]*255.f);
1093 1094 1095
            }
        }
    }
A
Andrey Kamaev 已提交
1096

1097 1098 1099
    int srccn;
    RGB2HLS_f cvt;
};
A
Andrey Kamaev 已提交
1100

1101

1102 1103 1104
struct HLS2RGB_f
{
    typedef float channel_type;
A
Andrey Kamaev 已提交
1105

1106 1107
    HLS2RGB_f(int _dstcn, int _blueIdx, float _hrange)
    : dstcn(_dstcn), blueIdx(_blueIdx), hscale(6.f/_hrange) {}
A
Andrey Kamaev 已提交
1108

1109
    void operator()(const float* src, float* dst, int n) const
1110
    {
1111 1112 1113 1114
        int i, bidx = blueIdx, dcn = dstcn;
        float _hscale = hscale;
        float alpha = ColorChannel<float>::max();
        n *= 3;
A
Andrey Kamaev 已提交
1115

1116
        for( i = 0; i < n; i += 3, dst += dcn )
1117 1118 1119
        {
            float h = src[i], l = src[i+1], s = src[i+2];
            float b, g, r;
A
Andrey Kamaev 已提交
1120

1121 1122 1123 1124 1125
            if( s == 0 )
                b = g = r = l;
            else
            {
                static const int sector_data[][3]=
1126
                {{1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0}};
1127 1128
                float tab[4];
                int sector;
A
Andrey Kamaev 已提交
1129

1130 1131
                float p2 = l <= 0.5f ? l*(1 + s) : l + s - l*s;
                float p1 = 2*l - p2;
A
Andrey Kamaev 已提交
1132

1133
                h *= _hscale;
1134 1135 1136 1137
                if( h < 0 )
                    do h += 6; while( h < 0 );
                else if( h >= 6 )
                    do h -= 6; while( h >= 6 );
A
Andrey Kamaev 已提交
1138

1139 1140 1141
                assert( 0 <= h && h < 6 );
                sector = cvFloor(h);
                h -= sector;
A
Andrey Kamaev 已提交
1142

1143 1144 1145 1146
                tab[0] = p2;
                tab[1] = p1;
                tab[2] = p1 + (p2 - p1)*(1-h);
                tab[3] = p1 + (p2 - p1)*h;
A
Andrey Kamaev 已提交
1147

1148 1149 1150 1151
                b = tab[sector_data[sector][0]];
                g = tab[sector_data[sector][1]];
                r = tab[sector_data[sector][2]];
            }
A
Andrey Kamaev 已提交
1152

1153
            dst[bidx] = b;
1154
            dst[1] = g;
1155 1156 1157
            dst[bidx^2] = r;
            if( dcn == 4 )
                dst[3] = alpha;
1158 1159
        }
    }
A
Andrey Kamaev 已提交
1160

1161 1162 1163
    int dstcn, blueIdx;
    float hscale;
};
A
Andrey Kamaev 已提交
1164

1165

1166
struct HLS2RGB_b
1167
{
1168
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1169

1170
    HLS2RGB_b(int _dstcn, int _blueIdx, int _hrange)
1171
    : dstcn(_dstcn), cvt(3, _blueIdx, (float)_hrange)
1172
    {}
A
Andrey Kamaev 已提交
1173

1174
    void operator()(const uchar* src, uchar* dst, int n) const
1175
    {
1176 1177 1178
        int i, j, dcn = dstcn;
        uchar alpha = ColorChannel<uchar>::max();
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
1179

1180
        for( i = 0; i < n; i += BLOCK_SIZE, src += BLOCK_SIZE*3 )
1181
        {
1182
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
1183

1184 1185 1186 1187 1188 1189 1190
            for( j = 0; j < dn*3; j += 3 )
            {
                buf[j] = src[j];
                buf[j+1] = src[j+1]*(1.f/255.f);
                buf[j+2] = src[j+2]*(1.f/255.f);
            }
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
1191

1192
            for( j = 0; j < dn*3; j += 3, dst += dcn )
1193
            {
1194 1195 1196 1197 1198
                dst[0] = saturate_cast<uchar>(buf[j]*255.f);
                dst[1] = saturate_cast<uchar>(buf[j+1]*255.f);
                dst[2] = saturate_cast<uchar>(buf[j+2]*255.f);
                if( dcn == 4 )
                    dst[3] = alpha;
1199 1200 1201
            }
        }
    }
A
Andrey Kamaev 已提交
1202

1203 1204 1205
    int dstcn;
    HLS2RGB_f cvt;
};
1206

A
Andrey Kamaev 已提交
1207

1208
///////////////////////////////////// RGB <-> L*a*b* /////////////////////////////////////
1209

1210
static const float D65[] = { 0.950456f, 1.f, 1.088754f };
1211

1212 1213 1214
enum { LAB_CBRT_TAB_SIZE = 1024, GAMMA_TAB_SIZE = 1024 };
static float LabCbrtTab[LAB_CBRT_TAB_SIZE*4];
static const float LabCbrtTabScale = LAB_CBRT_TAB_SIZE/1.5f;
1215

1216 1217
static float sRGBGammaTab[GAMMA_TAB_SIZE*4], sRGBInvGammaTab[GAMMA_TAB_SIZE*4];
static const float GammaTabScale = (float)GAMMA_TAB_SIZE;
A
Andrey Kamaev 已提交
1218 1219

static ushort sRGBGammaTab_b[256], linearGammaTab_b[256];
1220 1221 1222 1223 1224 1225
#undef lab_shift
#define lab_shift xyz_shift
#define gamma_shift 3
#define lab_shift2 (lab_shift + gamma_shift)
#define LAB_CBRT_TAB_SIZE_B (256*3/2*(1<<gamma_shift))
static ushort LabCbrtTab_b[LAB_CBRT_TAB_SIZE_B];
A
Andrey Kamaev 已提交
1226

1227 1228 1229 1230
static void initLabTabs()
{
    static bool initialized = false;
    if(!initialized)
1231
    {
1232
        float f[LAB_CBRT_TAB_SIZE+1], g[GAMMA_TAB_SIZE+1], ig[GAMMA_TAB_SIZE+1], scale = 1.f/LabCbrtTabScale;
1233 1234
        int i;
        for(i = 0; i <= LAB_CBRT_TAB_SIZE; i++)
1235
        {
1236 1237 1238 1239
            float x = i*scale;
            f[i] = x < 0.008856f ? x*7.787f + 0.13793103448275862f : cvCbrt(x);
        }
        splineBuild(f, LAB_CBRT_TAB_SIZE, LabCbrtTab);
A
Andrey Kamaev 已提交
1240

1241 1242 1243 1244 1245 1246 1247 1248 1249
        scale = 1.f/GammaTabScale;
        for(i = 0; i <= GAMMA_TAB_SIZE; i++)
        {
            float x = i*scale;
            g[i] = x <= 0.04045f ? x*(1.f/12.92f) : (float)pow((double)(x + 0.055)*(1./1.055), 2.4);
            ig[i] = x <= 0.0031308 ? x*12.92f : (float)(1.055*pow((double)x, 1./2.4) - 0.055);
        }
        splineBuild(g, GAMMA_TAB_SIZE, sRGBGammaTab);
        splineBuild(ig, GAMMA_TAB_SIZE, sRGBInvGammaTab);
A
Andrey Kamaev 已提交
1250

1251 1252 1253 1254 1255
        for(i = 0; i < 256; i++)
        {
            float x = i*(1.f/255.f);
            sRGBGammaTab_b[i] = saturate_cast<ushort>(255.f*(1 << gamma_shift)*(x <= 0.04045f ? x*(1.f/12.92f) : (float)pow((double)(x + 0.055)*(1./1.055), 2.4)));
            linearGammaTab_b[i] = (ushort)(i*(1 << gamma_shift));
1256
        }
A
Andrey Kamaev 已提交
1257

1258 1259 1260 1261 1262 1263
        for(i = 0; i < LAB_CBRT_TAB_SIZE_B; i++)
        {
            float x = i*(1.f/(255.f*(1 << gamma_shift)));
            LabCbrtTab_b[i] = saturate_cast<ushort>((1 << lab_shift2)*(x < 0.008856f ? x*7.787f + 0.13793103448275862f : cvCbrt(x)));
        }
        initialized = true;
1264 1265 1266
    }
}

1267 1268 1269
struct RGB2Lab_b
{
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1270

1271 1272 1273 1274
    RGB2Lab_b(int _srccn, int blueIdx, const float* _coeffs,
              const float* _whitept, bool _srgb)
    : srccn(_srccn), srgb(_srgb)
    {
1275
        static volatile int _3 = 3;
1276
        initLabTabs();
A
Andrey Kamaev 已提交
1277

1278 1279 1280 1281 1282 1283 1284 1285
        if(!_coeffs) _coeffs = sRGB2XYZ_D65;
        if(!_whitept) _whitept = D65;
        float scale[] =
        {
            (1 << lab_shift)/_whitept[0],
            (float)(1 << lab_shift),
            (1 << lab_shift)/_whitept[2]
        };
A
Andrey Kamaev 已提交
1286

1287
        for( int i = 0; i < _3; i++ )
1288 1289 1290 1291
        {
            coeffs[i*3+(blueIdx^2)] = cvRound(_coeffs[i*3]*scale[i]);
            coeffs[i*3+1] = cvRound(_coeffs[i*3+1]*scale[i]);
            coeffs[i*3+blueIdx] = cvRound(_coeffs[i*3+2]*scale[i]);
A
Andrey Kamaev 已提交
1292

1293 1294
            CV_Assert( coeffs[i] >= 0 && coeffs[i*3+1] >= 0 && coeffs[i*3+2] >= 0 &&
                      coeffs[i*3] + coeffs[i*3+1] + coeffs[i*3+2] < 2*(1 << lab_shift) );
1295 1296
        }
    }
A
Andrey Kamaev 已提交
1297

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    void operator()(const uchar* src, uchar* dst, int n) const
    {
        const int Lscale = (116*255+50)/100;
        const int Lshift = -((16*255*(1 << lab_shift2) + 50)/100);
        const ushort* tab = srgb ? sRGBGammaTab_b : linearGammaTab_b;
        int i, scn = srccn;
        int C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
            C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
            C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        n *= 3;
A
Andrey Kamaev 已提交
1308

1309 1310 1311 1312 1313 1314
        for( i = 0; i < n; i += 3, src += scn )
        {
            int R = tab[src[0]], G = tab[src[1]], B = tab[src[2]];
            int fX = LabCbrtTab_b[CV_DESCALE(R*C0 + G*C1 + B*C2, lab_shift)];
            int fY = LabCbrtTab_b[CV_DESCALE(R*C3 + G*C4 + B*C5, lab_shift)];
            int fZ = LabCbrtTab_b[CV_DESCALE(R*C6 + G*C7 + B*C8, lab_shift)];
A
Andrey Kamaev 已提交
1315

1316 1317 1318
            int L = CV_DESCALE( Lscale*fY + Lshift, lab_shift2 );
            int a = CV_DESCALE( 500*(fX - fY) + 128*(1 << lab_shift2), lab_shift2 );
            int b = CV_DESCALE( 200*(fY - fZ) + 128*(1 << lab_shift2), lab_shift2 );
A
Andrey Kamaev 已提交
1319

1320 1321 1322 1323 1324
            dst[i] = saturate_cast<uchar>(L);
            dst[i+1] = saturate_cast<uchar>(a);
            dst[i+2] = saturate_cast<uchar>(b);
        }
    }
A
Andrey Kamaev 已提交
1325

1326 1327 1328
    int srccn;
    int coeffs[9];
    bool srgb;
1329
};
A
Andrey Kamaev 已提交
1330 1331


1332
struct RGB2Lab_f
1333
{
1334
    typedef float channel_type;
A
Andrey Kamaev 已提交
1335

1336 1337 1338
    RGB2Lab_f(int _srccn, int blueIdx, const float* _coeffs,
              const float* _whitept, bool _srgb)
    : srccn(_srccn), srgb(_srgb)
1339
    {
1340
        volatile int _3 = 3;
1341
        initLabTabs();
A
Andrey Kamaev 已提交
1342

1343 1344 1345
        if(!_coeffs) _coeffs = sRGB2XYZ_D65;
        if(!_whitept) _whitept = D65;
        float scale[] = { LabCbrtTabScale/_whitept[0], LabCbrtTabScale, LabCbrtTabScale/_whitept[2] };
A
Andrey Kamaev 已提交
1346

1347
        for( int i = 0; i < _3; i++ )
1348
        {
1349 1350 1351 1352 1353 1354 1355
            coeffs[i*3+(blueIdx^2)] = _coeffs[i*3]*scale[i];
            coeffs[i*3+1] = _coeffs[i*3+1]*scale[i];
            coeffs[i*3+blueIdx] = _coeffs[i*3+2]*scale[i];
            CV_Assert( coeffs[i*3] >= 0 && coeffs[i*3+1] >= 0 && coeffs[i*3+2] >= 0 &&
                       coeffs[i*3] + coeffs[i*3+1] + coeffs[i*3+2] < 1.5f*LabCbrtTabScale );
        }
    }
A
Andrey Kamaev 已提交
1356

1357 1358 1359 1360 1361 1362 1363 1364 1365
    void operator()(const float* src, float* dst, int n) const
    {
        int i, scn = srccn;
        float gscale = GammaTabScale;
        const float* gammaTab = srgb ? sRGBGammaTab : 0;
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        n *= 3;
A
Andrey Kamaev 已提交
1366

1367 1368 1369 1370
        for( i = 0; i < n; i += 3, src += scn )
        {
            float R = src[0], G = src[1], B = src[2];
            if( gammaTab )
1371
            {
1372 1373 1374
                R = splineInterpolate(R*gscale, gammaTab, GAMMA_TAB_SIZE);
                G = splineInterpolate(G*gscale, gammaTab, GAMMA_TAB_SIZE);
                B = splineInterpolate(B*gscale, gammaTab, GAMMA_TAB_SIZE);
1375
            }
A
Andrey Kamaev 已提交
1376
            float fX = splineInterpolate(R*C0 + G*C1 + B*C2, LabCbrtTab, LAB_CBRT_TAB_SIZE);
1377 1378
            float fY = splineInterpolate(R*C3 + G*C4 + B*C5, LabCbrtTab, LAB_CBRT_TAB_SIZE);
            float fZ = splineInterpolate(R*C6 + G*C7 + B*C8, LabCbrtTab, LAB_CBRT_TAB_SIZE);
A
Andrey Kamaev 已提交
1379

1380 1381 1382
            float L = 116.f*fY - 16.f;
            float a = 500.f*(fX - fY);
            float b = 200.f*(fY - fZ);
A
Andrey Kamaev 已提交
1383

1384 1385 1386
            dst[i] = L; dst[i+1] = a; dst[i+2] = b;
        }
    }
A
Andrey Kamaev 已提交
1387

1388 1389 1390 1391 1392
    int srccn;
    float coeffs[9];
    bool srgb;
};

A
Andrey Kamaev 已提交
1393

1394 1395 1396
struct Lab2RGB_f
{
    typedef float channel_type;
A
Andrey Kamaev 已提交
1397

1398 1399 1400 1401 1402
    Lab2RGB_f( int _dstcn, int blueIdx, const float* _coeffs,
               const float* _whitept, bool _srgb )
    : dstcn(_dstcn), srgb(_srgb)
    {
        initLabTabs();
A
Andrey Kamaev 已提交
1403

1404 1405
        if(!_coeffs) _coeffs = XYZ2sRGB_D65;
        if(!_whitept) _whitept = D65;
A
Andrey Kamaev 已提交
1406

1407 1408 1409 1410 1411 1412 1413
        for( int i = 0; i < 3; i++ )
        {
            coeffs[i+(blueIdx^2)*3] = _coeffs[i]*_whitept[i];
            coeffs[i+3] = _coeffs[i+3]*_whitept[i];
            coeffs[i+blueIdx*3] = _coeffs[i+6]*_whitept[i];
        }
    }
A
Andrey Kamaev 已提交
1414

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
    void operator()(const float* src, float* dst, int n) const
    {
        int i, dcn = dstcn;
        const float* gammaTab = srgb ? sRGBInvGammaTab : 0;
        float gscale = GammaTabScale;
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        float alpha = ColorChannel<float>::max();
        n *= 3;
A
Andrey Kamaev 已提交
1425

1426 1427 1428 1429 1430 1431 1432 1433 1434
        for( i = 0; i < n; i += 3, dst += dcn )
        {
            float L = src[i], a = src[i+1], b = src[i+2];
            float Y = (L + 16.f)*(1.f/116.f);
            float X = (Y + a*0.002f);
            float Z = (Y - b*0.005f);
            Y = Y*Y*Y;
            X = X*X*X;
            Z = Z*Z*Z;
A
Andrey Kamaev 已提交
1435

1436 1437 1438
            float R = X*C0 + Y*C1 + Z*C2;
            float G = X*C3 + Y*C4 + Z*C5;
            float B = X*C6 + Y*C7 + Z*C8;
A
Andrey Kamaev 已提交
1439

1440
            if( gammaTab )
1441
            {
1442 1443 1444
                R = splineInterpolate(R*gscale, gammaTab, GAMMA_TAB_SIZE);
                G = splineInterpolate(G*gscale, gammaTab, GAMMA_TAB_SIZE);
                B = splineInterpolate(B*gscale, gammaTab, GAMMA_TAB_SIZE);
1445
            }
A
Andrey Kamaev 已提交
1446

1447 1448 1449
            dst[0] = R; dst[1] = G; dst[2] = B;
            if( dcn == 4 )
                dst[3] = alpha;
1450 1451
        }
    }
A
Andrey Kamaev 已提交
1452

1453 1454 1455 1456
    int dstcn;
    float coeffs[9];
    bool srgb;
};
1457

A
Andrey Kamaev 已提交
1458

1459
struct Lab2RGB_b
1460
{
1461
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1462

1463 1464 1465
    Lab2RGB_b( int _dstcn, int blueIdx, const float* _coeffs,
               const float* _whitept, bool _srgb )
    : dstcn(_dstcn), cvt(3, blueIdx, _coeffs, _whitept, _srgb ) {}
A
Andrey Kamaev 已提交
1466

1467
    void operator()(const uchar* src, uchar* dst, int n) const
1468
    {
1469 1470 1471
        int i, j, dcn = dstcn;
        uchar alpha = ColorChannel<uchar>::max();
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
1472

1473
        for( i = 0; i < n; i += BLOCK_SIZE, src += BLOCK_SIZE*3 )
1474
        {
1475
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
1476

1477
            for( j = 0; j < dn*3; j += 3 )
1478
            {
1479 1480 1481
                buf[j] = src[j]*(100.f/255.f);
                buf[j+1] = (float)(src[j+1] - 128);
                buf[j+2] = (float)(src[j+2] - 128);
1482
            }
1483
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
1484

1485
            for( j = 0; j < dn*3; j += 3, dst += dcn )
1486
            {
1487 1488 1489 1490 1491
                dst[0] = saturate_cast<uchar>(buf[j]*255.f);
                dst[1] = saturate_cast<uchar>(buf[j+1]*255.f);
                dst[2] = saturate_cast<uchar>(buf[j+2]*255.f);
                if( dcn == 4 )
                    dst[3] = alpha;
1492 1493 1494
            }
        }
    }
A
Andrey Kamaev 已提交
1495

1496 1497 1498
    int dstcn;
    Lab2RGB_f cvt;
};
A
Andrey Kamaev 已提交
1499 1500


1501
///////////////////////////////////// RGB <-> L*u*v* /////////////////////////////////////
1502

1503
struct RGB2Luv_f
1504
{
1505
    typedef float channel_type;
A
Andrey Kamaev 已提交
1506

1507 1508 1509
    RGB2Luv_f( int _srccn, int blueIdx, const float* _coeffs,
               const float* whitept, bool _srgb )
    : srccn(_srccn), srgb(_srgb)
1510
    {
A
Andrey Kamaev 已提交
1511
        volatile int i;
1512
        initLabTabs();
A
Andrey Kamaev 已提交
1513

1514 1515
        if(!_coeffs) _coeffs = sRGB2XYZ_D65;
        if(!whitept) whitept = D65;
A
Andrey Kamaev 已提交
1516

1517
        for( i = 0; i < 3; i++ )
1518
        {
1519
            coeffs[i*3] = _coeffs[i*3];
1520
            coeffs[i*3+1] = _coeffs[i*3+1];
1521 1522 1523
            coeffs[i*3+2] = _coeffs[i*3+2];
            if( blueIdx == 0 )
                std::swap(coeffs[i*3], coeffs[i*3+2]);
1524 1525
            CV_Assert( coeffs[i*3] >= 0 && coeffs[i*3+1] >= 0 && coeffs[i*3+2] >= 0 &&
                      coeffs[i*3] + coeffs[i*3+1] + coeffs[i*3+2] < 1.5f );
1526
        }
A
Andrey Kamaev 已提交
1527

1528 1529 1530
        float d = 1.f/(whitept[0] + whitept[1]*15 + whitept[2]*3);
        un = 4*whitept[0]*d;
        vn = 9*whitept[1]*d;
A
Andrey Kamaev 已提交
1531

1532
        CV_Assert(whitept[1] == 1.f);
1533
    }
A
Andrey Kamaev 已提交
1534

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
    void operator()(const float* src, float* dst, int n) const
    {
        int i, scn = srccn;
        float gscale = GammaTabScale;
        const float* gammaTab = srgb ? sRGBGammaTab : 0;
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        float _un = 13*un, _vn = 13*vn;
        n *= 3;
A
Andrey Kamaev 已提交
1545

1546 1547 1548 1549 1550 1551 1552 1553 1554
        for( i = 0; i < n; i += 3, src += scn )
        {
            float R = src[0], G = src[1], B = src[2];
            if( gammaTab )
            {
                R = splineInterpolate(R*gscale, gammaTab, GAMMA_TAB_SIZE);
                G = splineInterpolate(G*gscale, gammaTab, GAMMA_TAB_SIZE);
                B = splineInterpolate(B*gscale, gammaTab, GAMMA_TAB_SIZE);
            }
A
Andrey Kamaev 已提交
1555

1556 1557 1558
            float X = R*C0 + G*C1 + B*C2;
            float Y = R*C3 + G*C4 + B*C5;
            float Z = R*C6 + G*C7 + B*C8;
A
Andrey Kamaev 已提交
1559

1560 1561
            float L = splineInterpolate(Y*LabCbrtTabScale, LabCbrtTab, LAB_CBRT_TAB_SIZE);
            L = 116.f*L - 16.f;
A
Andrey Kamaev 已提交
1562 1563

            float d = (4*13) / std::max(X + 15 * Y + 3 * Z, FLT_EPSILON);
1564
            float u = L*(X*d - _un);
1565
            float v = L*((9*0.25f)*Y*d - _vn);
A
Andrey Kamaev 已提交
1566

1567 1568 1569
            dst[i] = L; dst[i+1] = u; dst[i+2] = v;
        }
    }
A
Andrey Kamaev 已提交
1570

1571 1572 1573 1574
    int srccn;
    float coeffs[9], un, vn;
    bool srgb;
};
1575

A
Andrey Kamaev 已提交
1576

1577
struct Luv2RGB_f
1578
{
1579
    typedef float channel_type;
A
Andrey Kamaev 已提交
1580

1581 1582 1583
    Luv2RGB_f( int _dstcn, int blueIdx, const float* _coeffs,
              const float* whitept, bool _srgb )
    : dstcn(_dstcn), srgb(_srgb)
1584
    {
1585
        initLabTabs();
A
Andrey Kamaev 已提交
1586

1587 1588
        if(!_coeffs) _coeffs = XYZ2sRGB_D65;
        if(!whitept) whitept = D65;
A
Andrey Kamaev 已提交
1589

1590
        for( int i = 0; i < 3; i++ )
1591
        {
1592 1593 1594 1595
            coeffs[i+(blueIdx^2)*3] = _coeffs[i];
            coeffs[i+3] = _coeffs[i+3];
            coeffs[i+blueIdx*3] = _coeffs[i+6];
        }
A
Andrey Kamaev 已提交
1596

1597 1598 1599
        float d = 1.f/(whitept[0] + whitept[1]*15 + whitept[2]*3);
        un = 4*whitept[0]*d;
        vn = 9*whitept[1]*d;
A
Andrey Kamaev 已提交
1600

1601 1602
        CV_Assert(whitept[1] == 1.f);
    }
A
Andrey Kamaev 已提交
1603

1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    void operator()(const float* src, float* dst, int n) const
    {
        int i, dcn = dstcn;
        const float* gammaTab = srgb ? sRGBInvGammaTab : 0;
        float gscale = GammaTabScale;
        float C0 = coeffs[0], C1 = coeffs[1], C2 = coeffs[2],
              C3 = coeffs[3], C4 = coeffs[4], C5 = coeffs[5],
              C6 = coeffs[6], C7 = coeffs[7], C8 = coeffs[8];
        float alpha = ColorChannel<float>::max();
        float _un = un, _vn = vn;
        n *= 3;
A
Andrey Kamaev 已提交
1615

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
        for( i = 0; i < n; i += 3, dst += dcn )
        {
            float L = src[i], u = src[i+1], v = src[i+2], d, X, Y, Z;
            Y = (L + 16.f) * (1.f/116.f);
            Y = Y*Y*Y;
            d = (1.f/13.f)/L;
            u = u*d + _un;
            v = v*d + _vn;
            float iv = 1.f/v;
            X = 2.25f * u * Y * iv ;
A
Andrey Kamaev 已提交
1626 1627
            Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv;

1628 1629 1630
            float R = X*C0 + Y*C1 + Z*C2;
            float G = X*C3 + Y*C4 + Z*C5;
            float B = X*C6 + Y*C7 + Z*C8;
A
Andrey Kamaev 已提交
1631

1632
            if( gammaTab )
1633
            {
1634 1635 1636
                R = splineInterpolate(R*gscale, gammaTab, GAMMA_TAB_SIZE);
                G = splineInterpolate(G*gscale, gammaTab, GAMMA_TAB_SIZE);
                B = splineInterpolate(B*gscale, gammaTab, GAMMA_TAB_SIZE);
1637
            }
A
Andrey Kamaev 已提交
1638

1639 1640 1641
            dst[0] = R; dst[1] = G; dst[2] = B;
            if( dcn == 4 )
                dst[3] = alpha;
1642 1643
        }
    }
A
Andrey Kamaev 已提交
1644

1645 1646 1647 1648
    int dstcn;
    float coeffs[9], un, vn;
    bool srgb;
};
1649

A
Andrey Kamaev 已提交
1650

1651
struct RGB2Luv_b
1652
{
1653
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1654

1655 1656 1657
    RGB2Luv_b( int _srccn, int blueIdx, const float* _coeffs,
               const float* _whitept, bool _srgb )
    : srccn(_srccn), cvt(3, blueIdx, _coeffs, _whitept, _srgb) {}
A
Andrey Kamaev 已提交
1658

1659
    void operator()(const uchar* src, uchar* dst, int n) const
1660
    {
1661 1662
        int i, j, scn = srccn;
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
1663

1664
        for( i = 0; i < n; i += BLOCK_SIZE, dst += BLOCK_SIZE*3 )
1665
        {
1666
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
1667

1668
            for( j = 0; j < dn*3; j += 3, src += scn )
1669
            {
1670 1671 1672
                buf[j] = src[0]*(1.f/255.f);
                buf[j+1] = (float)(src[1]*(1.f/255.f));
                buf[j+2] = (float)(src[2]*(1.f/255.f));
1673
            }
1674
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
1675

1676
            for( j = 0; j < dn*3; j += 3 )
1677
            {
1678 1679 1680
                dst[j] = saturate_cast<uchar>(buf[j]*2.55f);
                dst[j+1] = saturate_cast<uchar>(buf[j+1]*0.72033898305084743f + 96.525423728813564f);
                dst[j+2] = saturate_cast<uchar>(buf[j+2]*0.99609375f + 139.453125f);
1681 1682 1683
            }
        }
    }
A
Andrey Kamaev 已提交
1684

1685 1686 1687
    int srccn;
    RGB2Luv_f cvt;
};
A
Andrey Kamaev 已提交
1688

1689

1690
struct Luv2RGB_b
1691
{
1692
    typedef uchar channel_type;
A
Andrey Kamaev 已提交
1693

1694 1695 1696
    Luv2RGB_b( int _dstcn, int blueIdx, const float* _coeffs,
               const float* _whitept, bool _srgb )
    : dstcn(_dstcn), cvt(3, blueIdx, _coeffs, _whitept, _srgb ) {}
A
Andrey Kamaev 已提交
1697

1698 1699 1700 1701 1702
    void operator()(const uchar* src, uchar* dst, int n) const
    {
        int i, j, dcn = dstcn;
        uchar alpha = ColorChannel<uchar>::max();
        float buf[3*BLOCK_SIZE];
A
Andrey Kamaev 已提交
1703

1704 1705 1706
        for( i = 0; i < n; i += BLOCK_SIZE, src += BLOCK_SIZE*3 )
        {
            int dn = std::min(n - i, (int)BLOCK_SIZE);
A
Andrey Kamaev 已提交
1707

1708 1709 1710 1711 1712 1713 1714
            for( j = 0; j < dn*3; j += 3 )
            {
                buf[j] = src[j]*(100.f/255.f);
                buf[j+1] = (float)(src[j+1]*1.388235294117647f - 134.f);
                buf[j+2] = (float)(src[j+2]*1.003921568627451f - 140.f);
            }
            cvt(buf, buf, dn);
A
Andrey Kamaev 已提交
1715

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
            for( j = 0; j < dn*3; j += 3, dst += dcn )
            {
                dst[0] = saturate_cast<uchar>(buf[j]*255.f);
                dst[1] = saturate_cast<uchar>(buf[j+1]*255.f);
                dst[2] = saturate_cast<uchar>(buf[j+2]*255.f);
                if( dcn == 4 )
                    dst[3] = alpha;
            }
        }
    }
A
Andrey Kamaev 已提交
1726

1727 1728 1729
    int dstcn;
    Luv2RGB_f cvt;
};
1730

A
Andrey Kamaev 已提交
1731

1732
//////////////////////////// Bayer Pattern -> RGB conversion /////////////////////////////
1733

1734 1735
template<typename T>
class SIMDBayerStubInterpolator_
1736
{
1737 1738 1739 1740 1741
public:
    int bayer2Gray(const T*, int, T*, int, int, int, int) const
    {
        return 0;
    }
A
Andrey Kamaev 已提交
1742

1743 1744 1745 1746
    int bayer2RGB(const T*, int, T*, int, int) const
    {
        return 0;
    }
A
Andrey Kamaev 已提交
1747 1748
};

1749 1750 1751 1752 1753 1754 1755 1756
#if CV_SSE2
class SIMDBayerInterpolator_8u
{
public:
    SIMDBayerInterpolator_8u()
    {
        use_simd = checkHardwareSupport(CV_CPU_SSE2);
    }
A
Andrey Kamaev 已提交
1757

1758 1759 1760 1761 1762
    int bayer2Gray(const uchar* bayer, int bayer_step, uchar* dst,
                   int width, int bcoeff, int gcoeff, int rcoeff) const
    {
        if( !use_simd )
            return 0;
A
Andrey Kamaev 已提交
1763

1764 1765 1766 1767
        __m128i _b2y = _mm_set1_epi16((short)(rcoeff*2));
        __m128i _g2y = _mm_set1_epi16((short)(gcoeff*2));
        __m128i _r2y = _mm_set1_epi16((short)(bcoeff*2));
        const uchar* bayer_end = bayer + width;
A
Andrey Kamaev 已提交
1768

1769 1770 1771 1772 1773
        for( ; bayer <= bayer_end - 18; bayer += 14, dst += 14 )
        {
            __m128i r0 = _mm_loadu_si128((const __m128i*)bayer);
            __m128i r1 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step));
            __m128i r2 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step*2));
A
Andrey Kamaev 已提交
1774

1775 1776
            __m128i b1 = _mm_add_epi16(_mm_srli_epi16(_mm_slli_epi16(r0, 8), 7),
                                       _mm_srli_epi16(_mm_slli_epi16(r2, 8), 7));
1777 1778
            __m128i b0 = _mm_add_epi16(b1, _mm_srli_si128(b1, 2));
            b1 = _mm_slli_epi16(_mm_srli_si128(b1, 2), 1);
A
Andrey Kamaev 已提交
1779

1780 1781
            __m128i g0 = _mm_add_epi16(_mm_srli_epi16(r0, 7), _mm_srli_epi16(r2, 7));
            __m128i g1 = _mm_srli_epi16(_mm_slli_epi16(r1, 8), 7);
1782 1783
            g0 = _mm_add_epi16(g0, _mm_add_epi16(g1, _mm_srli_si128(g1, 2)));
            g1 = _mm_slli_epi16(_mm_srli_si128(g1, 2), 2);
A
Andrey Kamaev 已提交
1784

1785
            r0 = _mm_srli_epi16(r1, 8);
1786 1787 1788
            r1 = _mm_slli_epi16(_mm_add_epi16(r0, _mm_srli_si128(r0, 2)), 2);
            r0 = _mm_slli_epi16(r0, 3);

1789 1790 1791 1792
            g0 = _mm_add_epi16(_mm_mulhi_epi16(b0, _b2y), _mm_mulhi_epi16(g0, _g2y));
            g1 = _mm_add_epi16(_mm_mulhi_epi16(b1, _b2y), _mm_mulhi_epi16(g1, _g2y));
            g0 = _mm_add_epi16(g0, _mm_mulhi_epi16(r0, _r2y));
            g1 = _mm_add_epi16(g1, _mm_mulhi_epi16(r1, _r2y));
1793 1794
            g0 = _mm_srli_epi16(g0, 2);
            g1 = _mm_srli_epi16(g1, 2);
1795 1796 1797 1798 1799
            g0 = _mm_packus_epi16(g0, g0);
            g1 = _mm_packus_epi16(g1, g1);
            g0 = _mm_unpacklo_epi8(g0, g1);
            _mm_storeu_si128((__m128i*)dst, g0);
        }
A
Andrey Kamaev 已提交
1800

1801 1802
        return (int)(bayer - (bayer_end - width));
    }
A
Andrey Kamaev 已提交
1803

1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    int bayer2RGB(const uchar* bayer, int bayer_step, uchar* dst, int width, int blue) const
    {
        if( !use_simd )
            return 0;
        /*
         B G B G | B G B G | B G B G | B G B G
         G R G R | G R G R | G R G R | G R G R
         B G B G | B G B G | B G B G | B G B G
         */
        __m128i delta1 = _mm_set1_epi16(1), delta2 = _mm_set1_epi16(2);
        __m128i mask = _mm_set1_epi16(blue < 0 ? -1 : 0), z = _mm_setzero_si128();
        __m128i masklo = _mm_set1_epi16(0x00ff);
        const uchar* bayer_end = bayer + width;
A
Andrey Kamaev 已提交
1817

1818 1819 1820 1821 1822
        for( ; bayer <= bayer_end - 18; bayer += 14, dst += 42 )
        {
            __m128i r0 = _mm_loadu_si128((const __m128i*)bayer);
            __m128i r1 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step));
            __m128i r2 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step*2));
A
Andrey Kamaev 已提交
1823

1824 1825 1826 1827 1828 1829
            __m128i b1 = _mm_add_epi16(_mm_and_si128(r0, masklo), _mm_and_si128(r2, masklo));
            __m128i b0 = _mm_add_epi16(b1, _mm_srli_si128(b1, 2));
            b1 = _mm_srli_si128(b1, 2);
            b1 = _mm_srli_epi16(_mm_add_epi16(b1, delta1), 1);
            b0 = _mm_srli_epi16(_mm_add_epi16(b0, delta2), 2);
            b0 = _mm_packus_epi16(b0, b1);
A
Andrey Kamaev 已提交
1830

1831 1832 1833 1834 1835 1836
            __m128i g0 = _mm_add_epi16(_mm_srli_epi16(r0, 8), _mm_srli_epi16(r2, 8));
            __m128i g1 = _mm_and_si128(r1, masklo);
            g0 = _mm_add_epi16(g0, _mm_add_epi16(g1, _mm_srli_si128(g1, 2)));
            g1 = _mm_srli_si128(g1, 2);
            g0 = _mm_srli_epi16(_mm_add_epi16(g0, delta2), 2);
            g0 = _mm_packus_epi16(g0, g1);
A
Andrey Kamaev 已提交
1837

1838 1839 1840 1841
            r0 = _mm_srli_epi16(r1, 8);
            r1 = _mm_add_epi16(r0, _mm_srli_si128(r0, 2));
            r1 = _mm_srli_epi16(_mm_add_epi16(r1, delta1), 1);
            r0 = _mm_packus_epi16(r0, r1);
A
Andrey Kamaev 已提交
1842

1843 1844 1845
            b1 = _mm_and_si128(_mm_xor_si128(b0, r0), mask);
            b0 = _mm_xor_si128(b0, b1);
            r0 = _mm_xor_si128(r0, b1);
A
Andrey Kamaev 已提交
1846

1847 1848 1849 1850
            // b1 g1 b1 g1 ...
            b1 = _mm_unpackhi_epi8(b0, g0);
            // b0 g0 b2 g2 b4 g4 ....
            b0 = _mm_unpacklo_epi8(b0, g0);
A
Andrey Kamaev 已提交
1851

1852 1853 1854 1855
            // r1 0 r3 0 ...
            r1 = _mm_unpackhi_epi8(r0, z);
            // r0 0 r2 0 r4 0 ...
            r0 = _mm_unpacklo_epi8(r0, z);
A
Andrey Kamaev 已提交
1856

1857 1858 1859 1860
            // 0 b0 g0 r0 0 b2 g2 r2 0 ...
            g0 = _mm_slli_si128(_mm_unpacklo_epi16(b0, r0), 1);
            // 0 b8 g8 r8 0 b10 g10 r10 0 ...
            g1 = _mm_slli_si128(_mm_unpackhi_epi16(b0, r0), 1);
A
Andrey Kamaev 已提交
1861

1862 1863 1864 1865
            // b1 g1 r1 0 b3 g3 r3 ....
            r0 = _mm_unpacklo_epi16(b1, r1);
            // b9 g9 r9 0 ...
            r1 = _mm_unpackhi_epi16(b1, r1);
A
Andrey Kamaev 已提交
1866

1867 1868
            b0 = _mm_srli_si128(_mm_unpacklo_epi32(g0, r0), 1);
            b1 = _mm_srli_si128(_mm_unpackhi_epi32(g0, r0), 1);
A
Andrey Kamaev 已提交
1869

1870 1871 1872 1873
            _mm_storel_epi64((__m128i*)(dst-1+0), b0);
            _mm_storel_epi64((__m128i*)(dst-1+6*1), _mm_srli_si128(b0, 8));
            _mm_storel_epi64((__m128i*)(dst-1+6*2), b1);
            _mm_storel_epi64((__m128i*)(dst-1+6*3), _mm_srli_si128(b1, 8));
A
Andrey Kamaev 已提交
1874

1875 1876
            g0 = _mm_srli_si128(_mm_unpacklo_epi32(g1, r1), 1);
            g1 = _mm_srli_si128(_mm_unpackhi_epi32(g1, r1), 1);
A
Andrey Kamaev 已提交
1877

1878 1879
            _mm_storel_epi64((__m128i*)(dst-1+6*4), g0);
            _mm_storel_epi64((__m128i*)(dst-1+6*5), _mm_srli_si128(g0, 8));
A
Andrey Kamaev 已提交
1880

1881 1882
            _mm_storel_epi64((__m128i*)(dst-1+6*6), g1);
        }
A
Andrey Kamaev 已提交
1883

1884 1885
        return (int)(bayer - (bayer_end - width));
    }
A
Andrey Kamaev 已提交
1886

1887 1888 1889 1890 1891
    bool use_simd;
};
#else
typedef SIMDBayerStubInterpolator_<uchar> SIMDBayerInterpolator_8u;
#endif
A
Andrey Kamaev 已提交
1892

1893 1894 1895 1896
template<typename T, class SIMDInterpolator>
static void Bayer2Gray_( const Mat& srcmat, Mat& dstmat, int code )
{
    SIMDInterpolator vecOp;
1897 1898 1899 1900
    const int R2Y = 4899;
    const int G2Y = 9617;
    const int B2Y = 1868;
    const int SHIFT = 14;
A
Andrey Kamaev 已提交
1901

1902 1903 1904 1905
    const T* bayer0 = (const T*)srcmat.data;
    int bayer_step = (int)(srcmat.step/sizeof(T));
    T* dst0 = (T*)dstmat.data;
    int dst_step = (int)(dstmat.step/sizeof(T));
1906 1907
    Size size = srcmat.size();
    int bcoeff = B2Y, rcoeff = R2Y;
1908 1909
    int start_with_green = code == CV_BayerGB2GRAY || code == CV_BayerGR2GRAY;
    bool brow = true;
A
Andrey Kamaev 已提交
1910

1911
    if( code != CV_BayerBG2GRAY && code != CV_BayerGB2GRAY )
1912
    {
1913
        brow = false;
1914 1915
        std::swap(bcoeff, rcoeff);
    }
A
Andrey Kamaev 已提交
1916

1917 1918 1919
    dst0 += dst_step + 1;
    size.height -= 2;
    size.width -= 2;
A
Andrey Kamaev 已提交
1920

1921 1922
    for( ; size.height-- > 0; bayer0 += bayer_step, dst0 += dst_step )
    {
1923 1924 1925 1926
        unsigned t0, t1, t2;
        const T* bayer = bayer0;
        T* dst = dst0;
        const T* bayer_end = bayer + size.width;
A
Andrey Kamaev 已提交
1927

1928
        if( size.width <= 0 )
1929 1930
        {
            dst[-1] = dst[size.width] = 0;
1931
            continue;
1932
        }
A
Andrey Kamaev 已提交
1933

1934 1935 1936 1937 1938
        if( start_with_green )
        {
            t0 = (bayer[1] + bayer[bayer_step*2+1])*rcoeff;
            t1 = (bayer[bayer_step] + bayer[bayer_step+2])*bcoeff;
            t2 = bayer[bayer_step+1]*(2*G2Y);
A
Andrey Kamaev 已提交
1939

1940
            dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+1);
1941 1942 1943
            bayer++;
            dst++;
        }
A
Andrey Kamaev 已提交
1944

1945 1946 1947
        int delta = vecOp.bayer2Gray(bayer, bayer_step, dst, size.width, bcoeff, G2Y, rcoeff);
        bayer += delta;
        dst += delta;
A
Andrey Kamaev 已提交
1948

1949 1950 1951 1952 1953
        for( ; bayer <= bayer_end - 2; bayer += 2, dst += 2 )
        {
            t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] + bayer[bayer_step*2+2])*rcoeff;
            t1 = (bayer[1] + bayer[bayer_step] + bayer[bayer_step+2] + bayer[bayer_step*2+1])*G2Y;
            t2 = bayer[bayer_step+1]*(4*bcoeff);
1954
            dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+2);
A
Andrey Kamaev 已提交
1955

1956 1957 1958
            t0 = (bayer[2] + bayer[bayer_step*2+2])*rcoeff;
            t1 = (bayer[bayer_step+1] + bayer[bayer_step+3])*bcoeff;
            t2 = bayer[bayer_step+2]*(2*G2Y);
1959
            dst[1] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+1);
1960
        }
A
Andrey Kamaev 已提交
1961

1962 1963 1964 1965 1966
        if( bayer < bayer_end )
        {
            t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] + bayer[bayer_step*2+2])*rcoeff;
            t1 = (bayer[1] + bayer[bayer_step] + bayer[bayer_step+2] + bayer[bayer_step*2+1])*G2Y;
            t2 = bayer[bayer_step+1]*(4*bcoeff);
1967
            dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+2);
1968 1969 1970
            bayer++;
            dst++;
        }
A
Andrey Kamaev 已提交
1971

1972 1973
        dst0[-1] = dst0[0];
        dst0[size.width] = dst0[size.width-1];
A
Andrey Kamaev 已提交
1974

1975 1976 1977 1978
        brow = !brow;
        std::swap(bcoeff, rcoeff);
        start_with_green = !start_with_green;
    }
A
Andrey Kamaev 已提交
1979

1980
    size = dstmat.size();
1981
    dst0 = (T*)dstmat.data;
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
    if( size.height > 2 )
        for( int i = 0; i < size.width; i++ )
        {
            dst0[i] = dst0[i + dst_step];
            dst0[i + (size.height-1)*dst_step] = dst0[i + (size.height-2)*dst_step];
        }
    else
        for( int i = 0; i < size.width; i++ )
        {
            dst0[i] = dst0[i + (size.height-1)*dst_step] = 0;
        }
1993 1994
}

A
Andrey Kamaev 已提交
1995
template<typename T, class SIMDInterpolator>
1996
static void Bayer2RGB_( const Mat& srcmat, Mat& dstmat, int code )
1997
{
1998 1999 2000 2001 2002
    SIMDInterpolator vecOp;
    const T* bayer0 = (const T*)srcmat.data;
    int bayer_step = (int)(srcmat.step/sizeof(T));
    T* dst0 = (T*)dstmat.data;
    int dst_step = (int)(dstmat.step/sizeof(T));
2003
    Size size = srcmat.size();
2004
    int blue = code == CV_BayerBG2BGR || code == CV_BayerGB2BGR ? -1 : 1;
2005
    int start_with_green = code == CV_BayerGB2BGR || code == CV_BayerGR2BGR;
A
Andrey Kamaev 已提交
2006

2007
    dst0 += dst_step + 3 + 1;
2008 2009
    size.height -= 2;
    size.width -= 2;
A
Andrey Kamaev 已提交
2010

2011 2012
    for( ; size.height-- > 0; bayer0 += bayer_step, dst0 += dst_step )
    {
2013
        int t0, t1;
2014 2015 2016
        const T* bayer = bayer0;
        T* dst = dst0;
        const T* bayer_end = bayer + size.width;
A
Andrey Kamaev 已提交
2017

2018
        if( size.width <= 0 )
2019 2020 2021
        {
            dst[-4] = dst[-3] = dst[-2] = dst[size.width*3-1] =
            dst[size.width*3] = dst[size.width*3+1] = 0;
2022
            continue;
2023
        }
A
Andrey Kamaev 已提交
2024

2025 2026
        if( start_with_green )
        {
2027 2028
            t0 = (bayer[1] + bayer[bayer_step*2+1] + 1) >> 1;
            t1 = (bayer[bayer_step] + bayer[bayer_step+2] + 1) >> 1;
2029
            dst[-blue] = (T)t0;
2030
            dst[0] = bayer[bayer_step+1];
2031
            dst[blue] = (T)t1;
2032 2033 2034
            bayer++;
            dst += 3;
        }
A
Andrey Kamaev 已提交
2035

2036 2037 2038
        int delta = vecOp.bayer2RGB(bayer, bayer_step, dst, size.width, blue);
        bayer += delta;
        dst += delta*3;
A
Andrey Kamaev 已提交
2039

2040
        if( blue > 0 )
2041
        {
2042 2043 2044 2045 2046 2047
            for( ; bayer <= bayer_end - 2; bayer += 2, dst += 6 )
            {
                t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
                      bayer[bayer_step*2+2] + 2) >> 2;
                t1 = (bayer[1] + bayer[bayer_step] +
                      bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
2048 2049
                dst[-1] = (T)t0;
                dst[0] = (T)t1;
2050
                dst[1] = bayer[bayer_step+1];
A
Andrey Kamaev 已提交
2051

2052 2053
                t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
                t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
2054
                dst[2] = (T)t0;
2055
                dst[3] = bayer[bayer_step+2];
2056
                dst[4] = (T)t1;
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
            }
        }
        else
        {
            for( ; bayer <= bayer_end - 2; bayer += 2, dst += 6 )
            {
                t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
                      bayer[bayer_step*2+2] + 2) >> 2;
                t1 = (bayer[1] + bayer[bayer_step] +
                      bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
2067 2068
                dst[1] = (T)t0;
                dst[0] = (T)t1;
2069
                dst[-1] = bayer[bayer_step+1];
A
Andrey Kamaev 已提交
2070

2071 2072
                t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
                t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
2073
                dst[4] = (T)t0;
2074
                dst[3] = bayer[bayer_step+2];
2075
                dst[2] = (T)t1;
2076
            }
2077
        }
A
Andrey Kamaev 已提交
2078

2079 2080
        if( bayer < bayer_end )
        {
2081 2082 2083 2084
            t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
                  bayer[bayer_step*2+2] + 2) >> 2;
            t1 = (bayer[1] + bayer[bayer_step] +
                  bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
2085 2086
            dst[-blue] = (T)t0;
            dst[0] = (T)t1;
2087
            dst[blue] = bayer[bayer_step+1];
2088 2089 2090
            bayer++;
            dst += 3;
        }
A
Andrey Kamaev 已提交
2091

2092 2093 2094 2095 2096 2097
        dst0[-4] = dst0[-1];
        dst0[-3] = dst0[0];
        dst0[-2] = dst0[1];
        dst0[size.width*3-1] = dst0[size.width*3-4];
        dst0[size.width*3] = dst0[size.width*3-3];
        dst0[size.width*3+1] = dst0[size.width*3-2];
A
Andrey Kamaev 已提交
2098

2099
        blue = -blue;
2100 2101
        start_with_green = !start_with_green;
    }
A
Andrey Kamaev 已提交
2102

2103
    size = dstmat.size();
2104
    dst0 = (T*)dstmat.data;
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    if( size.height > 2 )
        for( int i = 0; i < size.width*3; i++ )
        {
            dst0[i] = dst0[i + dst_step];
            dst0[i + (size.height-1)*dst_step] = dst0[i + (size.height-2)*dst_step];
        }
    else
        for( int i = 0; i < size.width*3; i++ )
        {
            dst0[i] = dst0[i + (size.height-1)*dst_step] = 0;
        }
}

A
Andrey Kamaev 已提交
2118

2119
/////////////////// Demosaicing using Variable Number of Gradients ///////////////////////
A
Andrey Kamaev 已提交
2120

2121
static void Bayer2RGB_VNG_8u( const Mat& srcmat, Mat& dstmat, int code )
2122
{
2123 2124 2125 2126 2127
    const uchar* bayer = srcmat.data;
    int bstep = (int)srcmat.step;
    uchar* dst = dstmat.data;
    int dststep = (int)dstmat.step;
    Size size = srcmat.size();
A
Andrey Kamaev 已提交
2128

2129 2130
    int blueIdx = code == CV_BayerBG2BGR_VNG || code == CV_BayerGB2BGR_VNG ? 0 : 2;
    bool greenCell0 = code != CV_BayerBG2BGR_VNG && code != CV_BayerRG2BGR_VNG;
A
Andrey Kamaev 已提交
2131

2132
    // for too small images use the simple interpolation algorithm
2133
    if( MIN(size.width, size.height) < 8 )
2134
    {
2135
        Bayer2RGB_<uchar, SIMDBayerInterpolator_8u>( srcmat, dstmat, code );
2136 2137
        return;
    }
A
Andrey Kamaev 已提交
2138

2139
    const int brows = 3, bcn = 7;
A
Andrey Kamaev 已提交
2140
    int N = size.width, N2 = N*2, N3 = N*3, N4 = N*4, N5 = N*5, N6 = N*6, N7 = N*7;
2141
    int i, bufstep = N7*bcn;
2142 2143
    cv::AutoBuffer<ushort> _buf(bufstep*brows);
    ushort* buf = (ushort*)_buf;
A
Andrey Kamaev 已提交
2144

2145
    bayer += bstep*2;
A
Andrey Kamaev 已提交
2146

2147 2148 2149 2150
#if CV_SSE2
    bool haveSSE = cv::checkHardwareSupport(CV_CPU_SSE2);
    #define _mm_absdiff_epu16(a,b) _mm_adds_epu16(_mm_subs_epu16(a, b), _mm_subs_epu16(b, a))
#endif
A
Andrey Kamaev 已提交
2151

2152
    for( int y = 2; y < size.height - 4; y++ )
2153
    {
2154
        uchar* dstrow = dst + dststep*y + 6;
2155
        const uchar* srow;
A
Andrey Kamaev 已提交
2156

2157 2158
        for( int dy = (y == 2 ? -1 : 1); dy <= 1; dy++ )
        {
2159 2160
            ushort* brow = buf + ((y + dy - 1)%brows)*bufstep + 1;
            srow = bayer + (y+dy)*bstep + 1;
A
Andrey Kamaev 已提交
2161

2162
            for( i = 0; i < bcn; i++ )
2163
                brow[N*i-1] = brow[(N-2) + N*i] = 0;
A
Andrey Kamaev 已提交
2164

2165
            i = 1;
A
Andrey Kamaev 已提交
2166

2167
#if CV_SSE2
2168
            if( haveSSE )
2169
            {
2170 2171
                __m128i z = _mm_setzero_si128();
                for( ; i <= N-9; i += 8, srow += 8, brow += 8 )
2172
                {
2173
                    __m128i s1, s2, s3, s4, s6, s7, s8, s9;
A
Andrey Kamaev 已提交
2174

2175 2176 2177
                    s1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1-bstep)),z);
                    s2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-bstep)),z);
                    s3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1-bstep)),z);
A
Andrey Kamaev 已提交
2178

2179 2180
                    s4 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1)),z);
                    s6 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1)),z);
A
Andrey Kamaev 已提交
2181

2182 2183 2184
                    s7 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1+bstep)),z);
                    s8 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+bstep)),z);
                    s9 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1+bstep)),z);
A
Andrey Kamaev 已提交
2185

2186
                    __m128i b0, b1, b2, b3, b4, b5, b6;
A
Andrey Kamaev 已提交
2187

2188 2189 2190 2191 2192 2193 2194 2195
                    b0 = _mm_adds_epu16(_mm_slli_epi16(_mm_absdiff_epu16(s2,s8),1),
                                        _mm_adds_epu16(_mm_absdiff_epu16(s1, s7),
                                                       _mm_absdiff_epu16(s3, s9)));
                    b1 = _mm_adds_epu16(_mm_slli_epi16(_mm_absdiff_epu16(s4,s6),1),
                                        _mm_adds_epu16(_mm_absdiff_epu16(s1, s3),
                                                       _mm_absdiff_epu16(s7, s9)));
                    b2 = _mm_slli_epi16(_mm_absdiff_epu16(s3,s7),1);
                    b3 = _mm_slli_epi16(_mm_absdiff_epu16(s1,s9),1);
A
Andrey Kamaev 已提交
2196

2197 2198 2199 2200
                    _mm_storeu_si128((__m128i*)brow, b0);
                    _mm_storeu_si128((__m128i*)(brow + N), b1);
                    _mm_storeu_si128((__m128i*)(brow + N2), b2);
                    _mm_storeu_si128((__m128i*)(brow + N3), b3);
A
Andrey Kamaev 已提交
2201

2202 2203 2204 2205 2206 2207
                    b4 = _mm_adds_epu16(b2,_mm_adds_epu16(_mm_absdiff_epu16(s2, s4),
                                                          _mm_absdiff_epu16(s6, s8)));
                    b5 = _mm_adds_epu16(b3,_mm_adds_epu16(_mm_absdiff_epu16(s2, s6),
                                                          _mm_absdiff_epu16(s4, s8)));
                    b6 = _mm_adds_epu16(_mm_adds_epu16(s2, s4), _mm_adds_epu16(s6, s8));
                    b6 = _mm_srli_epi16(b6, 1);
A
Andrey Kamaev 已提交
2208

2209 2210 2211
                    _mm_storeu_si128((__m128i*)(brow + N4), b4);
                    _mm_storeu_si128((__m128i*)(brow + N5), b5);
                    _mm_storeu_si128((__m128i*)(brow + N6), b6);
2212 2213
                }
            }
2214
#endif
A
Andrey Kamaev 已提交
2215

2216 2217
            for( ; i < N-1; i++, srow++, brow++ )
            {
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
                brow[0] = (ushort)(std::abs(srow[-1-bstep] - srow[-1+bstep]) +
                                   std::abs(srow[-bstep] - srow[+bstep])*2 +
                                   std::abs(srow[1-bstep] - srow[1+bstep]));
                brow[N] = (ushort)(std::abs(srow[-1-bstep] - srow[1-bstep]) +
                                   std::abs(srow[-1] - srow[1])*2 +
                                   std::abs(srow[-1+bstep] - srow[1+bstep]));
                brow[N2] = (ushort)(std::abs(srow[+1-bstep] - srow[-1+bstep])*2);
                brow[N3] = (ushort)(std::abs(srow[-1-bstep] - srow[1+bstep])*2);
                brow[N4] = (ushort)(brow[N2] + std::abs(srow[-bstep] - srow[-1]) +
                                    std::abs(srow[+bstep] - srow[1]));
                brow[N5] = (ushort)(brow[N3] + std::abs(srow[-bstep] - srow[1]) +
                                    std::abs(srow[+bstep] - srow[-1]));
2230 2231
                brow[N6] = (ushort)((srow[-bstep] + srow[-1] + srow[1] + srow[+bstep])>>1);
            }
2232
        }
A
Andrey Kamaev 已提交
2233

2234 2235 2236 2237 2238
        const ushort* brow0 = buf + ((y - 2) % brows)*bufstep + 2;
        const ushort* brow1 = buf + ((y - 1) % brows)*bufstep + 2;
        const ushort* brow2 = buf + (y % brows)*bufstep + 2;
        static const float scale[] = { 0.f, 0.5f, 0.25f, 0.1666666666667f, 0.125f, 0.1f, 0.08333333333f, 0.0714286f, 0.0625f };
        srow = bayer + y*bstep + 2;
2239
        bool greenCell = greenCell0;
A
Andrey Kamaev 已提交
2240

2241
        i = 2;
2242
#if CV_SSE2
2243
        int limit = !haveSSE ? N-2 : greenCell ? std::min(3, N-2) : 2;
2244
#else
2245
        int limit = N - 2;
2246
#endif
A
Andrey Kamaev 已提交
2247

2248
        do
2249
        {
2250
            for( ; i < limit; i++, srow++, brow0++, brow1++, brow2++, dstrow += 3 )
2251
            {
2252 2253 2254 2255 2256 2257 2258
                int gradN = brow0[0] + brow1[0];
                int gradS = brow1[0] + brow2[0];
                int gradW = brow1[N-1] + brow1[N];
                int gradE = brow1[N] + brow1[N+1];
                int minGrad = std::min(std::min(std::min(gradN, gradS), gradW), gradE);
                int maxGrad = std::max(std::max(std::max(gradN, gradS), gradW), gradE);
                int R, G, B;
A
Andrey Kamaev 已提交
2259

2260
                if( !greenCell )
2261
                {
2262 2263 2264 2265
                    int gradNE = brow0[N4+1] + brow1[N4];
                    int gradSW = brow1[N4] + brow2[N4-1];
                    int gradNW = brow0[N5-1] + brow1[N5];
                    int gradSE = brow1[N5] + brow2[N5+1];
A
Andrey Kamaev 已提交
2266

2267 2268 2269
                    minGrad = std::min(std::min(std::min(std::min(minGrad, gradNE), gradSW), gradNW), gradSE);
                    maxGrad = std::max(std::max(std::max(std::max(maxGrad, gradNE), gradSW), gradNW), gradSE);
                    int T = minGrad + maxGrad/2;
A
Andrey Kamaev 已提交
2270

2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
                    int Rs = 0, Gs = 0, Bs = 0, ng = 0;
                    if( gradN < T )
                    {
                        Rs += srow[-bstep*2] + srow[0];
                        Gs += srow[-bstep]*2;
                        Bs += srow[-bstep-1] + srow[-bstep+1];
                        ng++;
                    }
                    if( gradS < T )
                    {
                        Rs += srow[bstep*2] + srow[0];
                        Gs += srow[bstep]*2;
                        Bs += srow[bstep-1] + srow[bstep+1];
                        ng++;
                    }
                    if( gradW < T )
                    {
                        Rs += srow[-2] + srow[0];
                        Gs += srow[-1]*2;
                        Bs += srow[-bstep-1] + srow[bstep-1];
                        ng++;
                    }
                    if( gradE < T )
                    {
                        Rs += srow[2] + srow[0];
                        Gs += srow[1]*2;
                        Bs += srow[-bstep+1] + srow[bstep+1];
                        ng++;
                    }
                    if( gradNE < T )
                    {
                        Rs += srow[-bstep*2+2] + srow[0];
                        Gs += brow0[N6+1];
                        Bs += srow[-bstep+1]*2;
                        ng++;
                    }
                    if( gradSW < T )
                    {
                        Rs += srow[bstep*2-2] + srow[0];
                        Gs += brow2[N6-1];
                        Bs += srow[bstep-1]*2;
                        ng++;
                    }
                    if( gradNW < T )
                    {
                        Rs += srow[-bstep*2-2] + srow[0];
                        Gs += brow0[N6-1];
                        Bs += srow[-bstep+1]*2;
                        ng++;
                    }
                    if( gradSE < T )
                    {
                        Rs += srow[bstep*2+2] + srow[0];
                        Gs += brow2[N6+1];
                        Bs += srow[-bstep+1]*2;
                        ng++;
                    }
                    R = srow[0];
                    G = R + cvRound((Gs - Rs)*scale[ng]);
A
Andrey Kamaev 已提交
2330
                    B = R + cvRound((Bs - Rs)*scale[ng]);
2331
                }
2332
                else
2333
                {
2334 2335 2336 2337
                    int gradNE = brow0[N2] + brow0[N2+1] + brow1[N2] + brow1[N2+1];
                    int gradSW = brow1[N2] + brow1[N2-1] + brow2[N2] + brow2[N2-1];
                    int gradNW = brow0[N3] + brow0[N3-1] + brow1[N3] + brow1[N3-1];
                    int gradSE = brow1[N3] + brow1[N3+1] + brow2[N3] + brow2[N3+1];
A
Andrey Kamaev 已提交
2338

2339 2340 2341
                    minGrad = std::min(std::min(std::min(std::min(minGrad, gradNE), gradSW), gradNW), gradSE);
                    maxGrad = std::max(std::max(std::max(std::max(maxGrad, gradNE), gradSW), gradNW), gradSE);
                    int T = minGrad + maxGrad/2;
A
Andrey Kamaev 已提交
2342

2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
                    int Rs = 0, Gs = 0, Bs = 0, ng = 0;
                    if( gradN < T )
                    {
                        Rs += srow[-bstep*2-1] + srow[-bstep*2+1];
                        Gs += srow[-bstep*2] + srow[0];
                        Bs += srow[-bstep]*2;
                        ng++;
                    }
                    if( gradS < T )
                    {
                        Rs += srow[bstep*2-1] + srow[bstep*2+1];
                        Gs += srow[bstep*2] + srow[0];
                        Bs += srow[bstep]*2;
                        ng++;
                    }
                    if( gradW < T )
                    {
                        Rs += srow[-1]*2;
                        Gs += srow[-2] + srow[0];
                        Bs += srow[-bstep-2]+srow[bstep-2];
                        ng++;
                    }
                    if( gradE < T )
                    {
                        Rs += srow[1]*2;
                        Gs += srow[2] + srow[0];
                        Bs += srow[-bstep+2]+srow[bstep+2];
                        ng++;
                    }
                    if( gradNE < T )
                    {
                        Rs += srow[-bstep*2+1] + srow[1];
                        Gs += srow[-bstep+1]*2;
                        Bs += srow[-bstep] + srow[-bstep+2];
                        ng++;
                    }
                    if( gradSW < T )
                    {
                        Rs += srow[bstep*2-1] + srow[-1];
                        Gs += srow[bstep-1]*2;
                        Bs += srow[bstep] + srow[bstep-2];
                        ng++;
                    }
                    if( gradNW < T )
                    {
                        Rs += srow[-bstep*2-1] + srow[-1];
                        Gs += srow[-bstep-1]*2;
                        Bs += srow[-bstep-2]+srow[-bstep];
                        ng++;
                    }
                    if( gradSE < T )
                    {
                        Rs += srow[bstep*2+1] + srow[1];
                        Gs += srow[bstep+1]*2;
                        Bs += srow[bstep+2]+srow[bstep];
                        ng++;
                    }
                    G = srow[0];
                    R = G + cvRound((Rs - Gs)*scale[ng]);
                    B = G + cvRound((Bs - Gs)*scale[ng]);
2403
                }
2404 2405 2406 2407
                dstrow[blueIdx] = CV_CAST_8U(B);
                dstrow[1] = CV_CAST_8U(G);
                dstrow[blueIdx^2] = CV_CAST_8U(R);
                greenCell = !greenCell;
2408
            }
2409

2410
#if CV_SSE2
2411 2412
            if( !haveSSE )
                break;
A
Andrey Kamaev 已提交
2413

2414 2415 2416 2417
            __m128i emask    = _mm_set1_epi32(0x0000ffff),
                    omask    = _mm_set1_epi32(0xffff0000),
                    z        = _mm_setzero_si128();
            __m128 _0_5      = _mm_set1_ps(0.5f);
A
Andrey Kamaev 已提交
2418

2419 2420 2421 2422
            #define _mm_merge_epi16(a, b) _mm_or_si128(_mm_and_si128(a, emask), _mm_and_si128(b, omask)) //(aA_aA_aA_aA) * (bB_bB_bB_bB) => (bA_bA_bA_bA)
            #define _mm_cvtloepi16_ps(a)  _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(a,a), 16))   //(1,2,3,4,5,6,7,8) => (1f,2f,3f,4f)
            #define _mm_cvthiepi16_ps(a)  _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpackhi_epi16(a,a), 16))   //(1,2,3,4,5,6,7,8) => (5f,6f,7f,8f)
            #define _mm_loadl_u8_s16(ptr, offset) _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)((ptr) + (offset))), z) //load 8 uchars to 8 shorts
A
Andrey Kamaev 已提交
2423

2424 2425
            // process 8 pixels at once
            for( ; i <= N - 10; i += 8, srow += 8, brow0 += 8, brow1 += 8, brow2 += 8 )
2426
            {
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
                //int gradN = brow0[0] + brow1[0];
                __m128i gradN = _mm_adds_epi16(_mm_loadu_si128((__m128i*)brow0), _mm_loadu_si128((__m128i*)brow1));

                //int gradS = brow1[0] + brow2[0];
                __m128i gradS = _mm_adds_epi16(_mm_loadu_si128((__m128i*)brow1), _mm_loadu_si128((__m128i*)brow2));

                //int gradW = brow1[N-1] + brow1[N];
                __m128i gradW = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N-1)), _mm_loadu_si128((__m128i*)(brow1+N)));

                //int gradE = brow1[N+1] + brow1[N];
                __m128i gradE = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N+1)), _mm_loadu_si128((__m128i*)(brow1+N)));
A
Andrey Kamaev 已提交
2438

2439 2440 2441 2442
                //int minGrad = std::min(std::min(std::min(gradN, gradS), gradW), gradE);
                //int maxGrad = std::max(std::max(std::max(gradN, gradS), gradW), gradE);
                __m128i minGrad = _mm_min_epi16(_mm_min_epi16(gradN, gradS), _mm_min_epi16(gradW, gradE));
                __m128i maxGrad = _mm_max_epi16(_mm_max_epi16(gradN, gradS), _mm_max_epi16(gradW, gradE));
A
Andrey Kamaev 已提交
2443

2444
                __m128i grad0, grad1;
A
Andrey Kamaev 已提交
2445

2446 2447 2448 2449 2450 2451
                //int gradNE = brow0[N4+1] + brow1[N4];
                //int gradNE = brow0[N2] + brow0[N2+1] + brow1[N2] + brow1[N2+1];
                grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N4+1)), _mm_loadu_si128((__m128i*)(brow1+N4)));
                grad1 = _mm_adds_epi16( _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N2)), _mm_loadu_si128((__m128i*)(brow0+N2+1))),
                                        _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N2)), _mm_loadu_si128((__m128i*)(brow1+N2+1))));
                __m128i gradNE = _mm_merge_epi16(grad0, grad1);
A
Andrey Kamaev 已提交
2452

2453 2454 2455 2456 2457 2458
                //int gradSW = brow1[N4] + brow2[N4-1];
                //int gradSW = brow1[N2] + brow1[N2-1] + brow2[N2] + brow2[N2-1];
                grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N4-1)), _mm_loadu_si128((__m128i*)(brow1+N4)));
                grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N2)), _mm_loadu_si128((__m128i*)(brow2+N2-1))),
                                       _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N2)), _mm_loadu_si128((__m128i*)(brow1+N2-1))));
                __m128i gradSW = _mm_merge_epi16(grad0, grad1);
A
Andrey Kamaev 已提交
2459

2460 2461
                minGrad = _mm_min_epi16(_mm_min_epi16(minGrad, gradNE), gradSW);
                maxGrad = _mm_max_epi16(_mm_max_epi16(maxGrad, gradNE), gradSW);
2462 2463 2464 2465 2466 2467 2468

                //int gradNW = brow0[N5-1] + brow1[N5];
                //int gradNW = brow0[N3] + brow0[N3-1] + brow1[N3] + brow1[N3-1];
                grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N5-1)), _mm_loadu_si128((__m128i*)(brow1+N5)));
                grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N3)), _mm_loadu_si128((__m128i*)(brow0+N3-1))),
                                       _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N3)), _mm_loadu_si128((__m128i*)(brow1+N3-1))));
                __m128i gradNW = _mm_merge_epi16(grad0, grad1);
A
Andrey Kamaev 已提交
2469

2470 2471 2472 2473 2474 2475
                //int gradSE = brow1[N5] + brow2[N5+1];
                //int gradSE = brow1[N3] + brow1[N3+1] + brow2[N3] + brow2[N3+1];
                grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N5+1)), _mm_loadu_si128((__m128i*)(brow1+N5)));
                grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N3)), _mm_loadu_si128((__m128i*)(brow2+N3+1))),
                                       _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N3)), _mm_loadu_si128((__m128i*)(brow1+N3+1))));
                __m128i gradSE = _mm_merge_epi16(grad0, grad1);
A
Andrey Kamaev 已提交
2476

2477 2478
                minGrad = _mm_min_epi16(_mm_min_epi16(minGrad, gradNW), gradSE);
                maxGrad = _mm_max_epi16(_mm_max_epi16(maxGrad, gradNW), gradSE);
A
Andrey Kamaev 已提交
2479

2480 2481 2482 2483
                //int T = minGrad + maxGrad/2;
                __m128i T = _mm_adds_epi16(_mm_srli_epi16(maxGrad, 1), minGrad);

                __m128i RGs = z, GRs = z, Bs = z, ng = z;
A
Andrey Kamaev 已提交
2484

2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
                __m128i x0  = _mm_loadl_u8_s16(srow, +0          );
                __m128i x1  = _mm_loadl_u8_s16(srow, -1 - bstep  );
                __m128i x2  = _mm_loadl_u8_s16(srow, -1 - bstep*2);
                __m128i x3  = _mm_loadl_u8_s16(srow,    - bstep  );
                __m128i x4  = _mm_loadl_u8_s16(srow, +1 - bstep*2);
                __m128i x5  = _mm_loadl_u8_s16(srow, +1 - bstep  );
                __m128i x6  = _mm_loadl_u8_s16(srow, +2 - bstep  );
                __m128i x7  = _mm_loadl_u8_s16(srow, +1          );
                __m128i x8  = _mm_loadl_u8_s16(srow, +2 + bstep  );
                __m128i x9  = _mm_loadl_u8_s16(srow, +1 + bstep  );
                __m128i x10 = _mm_loadl_u8_s16(srow, +1 + bstep*2);
                __m128i x11 = _mm_loadl_u8_s16(srow,    + bstep  );
                __m128i x12 = _mm_loadl_u8_s16(srow, -1 + bstep*2);
                __m128i x13 = _mm_loadl_u8_s16(srow, -1 + bstep  );
                __m128i x14 = _mm_loadl_u8_s16(srow, -2 + bstep  );
                __m128i x15 = _mm_loadl_u8_s16(srow, -1          );
                __m128i x16 = _mm_loadl_u8_s16(srow, -2 - bstep  );

                __m128i t0, t1, mask;
A
Andrey Kamaev 已提交
2504

2505 2506 2507
                // gradN ***********************************************
                mask = _mm_cmpgt_epi16(T, gradN); // mask = T>gradN
                ng = _mm_sub_epi16(ng, mask);     // ng += (T>gradN)
A
Andrey Kamaev 已提交
2508

2509 2510
                t0 = _mm_slli_epi16(x3, 1);                                 // srow[-bstep]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -bstep*2), x0);  // srow[-bstep*2] + srow[0]
A
Andrey Kamaev 已提交
2511

2512 2513 2514 2515 2516 2517
                // RGs += (srow[-bstep*2] + srow[0]) * (T>gradN)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
                // GRs += {srow[-bstep]*2; (srow[-bstep*2-1] + srow[-bstep*2+1])} * (T>gradN)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(t0, _mm_adds_epi16(x2,x4)), mask));
                // Bs  += {(srow[-bstep-1]+srow[-bstep+1]); srow[-bstep]*2 } * (T>gradN)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x1,x5), t0), mask));
A
Andrey Kamaev 已提交
2518

2519 2520 2521 2522 2523 2524
                // gradNE **********************************************
                mask = _mm_cmpgt_epi16(T, gradNE); // mask = T>gradNE
                ng = _mm_sub_epi16(ng, mask);      // ng += (T>gradNE)

                t0 = _mm_slli_epi16(x5, 1);                                    // srow[-bstep+1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -bstep*2+2), x0);   // srow[-bstep*2+2] + srow[0]
A
Andrey Kamaev 已提交
2525

2526 2527 2528 2529 2530 2531
                // RGs += {(srow[-bstep*2+2] + srow[0]); srow[-bstep+1]*2} * (T>gradNE)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
                // GRs += {brow0[N6+1]; (srow[-bstep*2+1] + srow[1])} * (T>gradNE)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow0+N6+1)), _mm_adds_epi16(x4,x7)), mask));
                // Bs  += {srow[-bstep+1]*2; (srow[-bstep] + srow[-bstep+2])}  * (T>gradNE)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(t0,_mm_adds_epi16(x3,x6)), mask));
A
Andrey Kamaev 已提交
2532

2533 2534 2535
                // gradE ***********************************************
                mask = _mm_cmpgt_epi16(T, gradE);  // mask = T>gradE
                ng = _mm_sub_epi16(ng, mask);      // ng += (T>gradE)
A
Andrey Kamaev 已提交
2536

2537 2538 2539 2540 2541 2542 2543 2544 2545
                t0 = _mm_slli_epi16(x7, 1);                         // srow[1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, 2), x0); // srow[2] + srow[0]

                // RGs += (srow[2] + srow[0]) * (T>gradE)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
                // GRs += (srow[1]*2) * (T>gradE)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(t0, mask));
                // Bs  += {(srow[-bstep+1]+srow[bstep+1]); (srow[-bstep+2]+srow[bstep+2])} * (T>gradE)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x5,x9), _mm_adds_epi16(x6,x8)), mask));
A
Andrey Kamaev 已提交
2546

2547 2548 2549
                // gradSE **********************************************
                mask = _mm_cmpgt_epi16(T, gradSE);  // mask = T>gradSE
                ng = _mm_sub_epi16(ng, mask);       // ng += (T>gradSE)
A
Andrey Kamaev 已提交
2550

2551 2552 2553 2554 2555 2556 2557 2558 2559
                t0 = _mm_slli_epi16(x9, 1);                                 // srow[bstep+1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, bstep*2+2), x0); // srow[bstep*2+2] + srow[0]

                // RGs += {(srow[bstep*2+2] + srow[0]); srow[bstep+1]*2} * (T>gradSE)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
                // GRs += {brow2[N6+1]; (srow[1]+srow[bstep*2+1])} * (T>gradSE)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow2+N6+1)), _mm_adds_epi16(x7,x10)), mask));
                // Bs  += {srow[-bstep+1]*2; (srow[bstep+2]+srow[bstep])} * (T>gradSE)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_slli_epi16(x5, 1), _mm_adds_epi16(x8,x11)), mask));
A
Andrey Kamaev 已提交
2560

2561 2562 2563
                // gradS ***********************************************
                mask = _mm_cmpgt_epi16(T, gradS);  // mask = T>gradS
                ng = _mm_sub_epi16(ng, mask);      // ng += (T>gradS)
A
Andrey Kamaev 已提交
2564

2565 2566 2567 2568 2569 2570 2571 2572 2573
                t0 = _mm_slli_epi16(x11, 1);                             // srow[bstep]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow,bstep*2), x0); // srow[bstep*2]+srow[0]

                // RGs += (srow[bstep*2]+srow[0]) * (T>gradS)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
                // GRs += {srow[bstep]*2; (srow[bstep*2+1]+srow[bstep*2-1])} * (T>gradS)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(t0, _mm_adds_epi16(x10,x12)), mask));
                // Bs  += {(srow[bstep+1]+srow[bstep-1]); srow[bstep]*2} * (T>gradS)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x9,x13), t0), mask));
A
Andrey Kamaev 已提交
2574

2575 2576 2577
                // gradSW **********************************************
                mask = _mm_cmpgt_epi16(T, gradSW);  // mask = T>gradSW
                ng = _mm_sub_epi16(ng, mask);       // ng += (T>gradSW)
A
Andrey Kamaev 已提交
2578

2579 2580 2581 2582 2583 2584 2585 2586 2587
                t0 = _mm_slli_epi16(x13, 1);                                // srow[bstep-1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, bstep*2-2), x0); // srow[bstep*2-2]+srow[0]

                // RGs += {(srow[bstep*2-2]+srow[0]); srow[bstep-1]*2} * (T>gradSW)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
                // GRs += {brow2[N6-1]; (srow[bstep*2-1]+srow[-1])} * (T>gradSW)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow2+N6-1)), _mm_adds_epi16(x12,x15)), mask));
                // Bs  += {srow[bstep-1]*2; (srow[bstep]+srow[bstep-2])} * (T>gradSW)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(t0,_mm_adds_epi16(x11,x14)), mask));
A
Andrey Kamaev 已提交
2588

2589 2590 2591
                // gradW ***********************************************
                mask = _mm_cmpgt_epi16(T, gradW);  // mask = T>gradW
                ng = _mm_sub_epi16(ng, mask);      // ng += (T>gradW)
A
Andrey Kamaev 已提交
2592

2593 2594 2595 2596 2597 2598 2599 2600 2601
                t0 = _mm_slli_epi16(x15, 1);                         // srow[-1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -2), x0); // srow[-2]+srow[0]

                // RGs += (srow[-2]+srow[0]) * (T>gradW)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
                // GRs += (srow[-1]*2) * (T>gradW)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(t0, mask));
                // Bs  += {(srow[-bstep-1]+srow[bstep-1]); (srow[bstep-2]+srow[-bstep-2])} * (T>gradW)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x1,x13), _mm_adds_epi16(x14,x16)), mask));
A
Andrey Kamaev 已提交
2602

2603 2604 2605
                // gradNW **********************************************
                mask = _mm_cmpgt_epi16(T, gradNW);  // mask = T>gradNW
                ng = _mm_sub_epi16(ng, mask);       // ng += (T>gradNW)
A
Andrey Kamaev 已提交
2606

2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
                t0 = _mm_slli_epi16(x1, 1);                                 // srow[-bstep-1]*2
                t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow,-bstep*2-2), x0); // srow[-bstep*2-2]+srow[0]

                // RGs += {(srow[-bstep*2-2]+srow[0]); srow[-bstep-1]*2} * (T>gradNW)
                RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
                // GRs += {brow0[N6-1]; (srow[-bstep*2-1]+srow[-1])} * (T>gradNW)
                GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow0+N6-1)), _mm_adds_epi16(x2,x15)), mask));
                // Bs  += {srow[-bstep-1]*2; (srow[-bstep]+srow[-bstep-2])} * (T>gradNW)
                Bs  = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_slli_epi16(x5, 1),_mm_adds_epi16(x3,x16)), mask));

2617 2618 2619
                __m128 ngf0, ngf1;
                ngf0 = _mm_div_ps(_0_5, _mm_cvtloepi16_ps(ng));
                ngf1 = _mm_div_ps(_0_5, _mm_cvthiepi16_ps(ng));
A
Andrey Kamaev 已提交
2620

2621 2622 2623
                // now interpolate r, g & b
                t0 = _mm_sub_epi16(GRs, RGs);
                t1 = _mm_sub_epi16(Bs, RGs);
A
Andrey Kamaev 已提交
2624

2625
                t0 = _mm_add_epi16(x0, _mm_packs_epi32(
2626 2627
                                                       _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtloepi16_ps(t0), ngf0)),
                                                       _mm_cvtps_epi32(_mm_mul_ps(_mm_cvthiepi16_ps(t0), ngf1))));
A
Andrey Kamaev 已提交
2628

2629
                t1 = _mm_add_epi16(x0, _mm_packs_epi32(
2630 2631
                                                       _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtloepi16_ps(t1), ngf0)),
                                                       _mm_cvtps_epi32(_mm_mul_ps(_mm_cvthiepi16_ps(t1), ngf1))));
A
Andrey Kamaev 已提交
2632

2633 2634
                x1 = _mm_merge_epi16(x0, t0);
                x2 = _mm_merge_epi16(t0, x0);
A
Andrey Kamaev 已提交
2635

2636
                uchar R[8], G[8], B[8];
A
Andrey Kamaev 已提交
2637

2638 2639 2640
                _mm_storel_epi64(blueIdx ? (__m128i*)B : (__m128i*)R, _mm_packus_epi16(x1, z));
                _mm_storel_epi64((__m128i*)G, _mm_packus_epi16(x2, z));
                _mm_storel_epi64(blueIdx ? (__m128i*)R : (__m128i*)B, _mm_packus_epi16(t1, z));
A
Andrey Kamaev 已提交
2641

2642
                for( int j = 0; j < 8; j++, dstrow += 3 )
2643
                {
2644
                    dstrow[0] = B[j]; dstrow[1] = G[j]; dstrow[2] = R[j];
2645 2646
                }
            }
2647
#endif
A
Andrey Kamaev 已提交
2648

2649 2650 2651
            limit = N - 2;
        }
        while( i < N - 2 );
A
Andrey Kamaev 已提交
2652

2653 2654 2655 2656
        for( i = 0; i < 6; i++ )
        {
            dst[dststep*y + 5 - i] = dst[dststep*y + 8 - i];
            dst[dststep*y + (N - 2)*3 + i] = dst[dststep*y + (N - 3)*3 + i];
2657
        }
A
Andrey Kamaev 已提交
2658

2659 2660 2661
        greenCell0 = !greenCell0;
        blueIdx ^= 2;
    }
A
Andrey Kamaev 已提交
2662

2663 2664 2665 2666 2667 2668 2669 2670
    for( i = 0; i < size.width*3; i++ )
    {
        dst[i] = dst[i + dststep] = dst[i + dststep*2];
        dst[i + dststep*(size.height-4)] =
        dst[i + dststep*(size.height-3)] =
        dst[i + dststep*(size.height-2)] =
        dst[i + dststep*(size.height-1)] = dst[i + dststep*(size.height-5)];
    }
2671 2672
}

2673
///////////////////////////////////// YUV420 -> RGB /////////////////////////////////////
2674

2675 2676 2677 2678 2679 2680 2681
const int ITUR_BT_601_CY = 1220542;
const int ITUR_BT_601_CUB = 2116026;
const int ITUR_BT_601_CUG = -409993;
const int ITUR_BT_601_CVG = -852492;
const int ITUR_BT_601_CVR = 1673527;
const int ITUR_BT_601_SHIFT = 20;

2682
template<int bIdx, int uIdx>
2683
struct YUV420sp2RGB888Invoker
2684
{
2685
    Mat* dst;
2686
    const uchar* my1, *muv;
2687
    int width, stride;
2688

2689
    YUV420sp2RGB888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _uv)
2690
        : dst(_dst), my1(_y1), muv(_uv), width(_dst->cols), stride(_stride) {}
2691 2692 2693

    void operator()(const BlockedRange& range) const
    {
2694 2695 2696
        int rangeBegin = range.begin() * 2;
        int rangeEnd = range.end() * 2;

2697
        //R = 1.164(Y - 16) + 1.596(V - 128)
2698 2699 2700 2701 2702 2703 2704 2705
        //G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128)
        //B = 1.164(Y - 16)                  + 2.018(U - 128)

        //R = (1220542(Y - 16) + 1673527(V - 128)                  + (1 << 19)) >> 20
        //G = (1220542(Y - 16) - 852492(V - 128) - 409993(U - 128) + (1 << 19)) >> 20
        //B = (1220542(Y - 16)                  + 2116026(U - 128) + (1 << 19)) >> 20

        const uchar* y1 = my1 + rangeBegin * stride, *uv = muv + rangeBegin * stride / 2;
2706

2707 2708 2709 2710 2711 2712
#ifdef HAVE_TEGRA_OPTIMIZATION
        if(tegra::cvtYUV4202RGB(bIdx, uIdx, 3, y1, uv, stride, dst->ptr<uchar>(rangeBegin), dst->step, rangeEnd - rangeBegin, dst->cols))
            return;
#endif

        for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, uv += stride)
2713
        {
2714
            uchar* row1 = dst->ptr<uchar>(j);
2715 2716
            uchar* row2 = dst->ptr<uchar>(j + 1);
            const uchar* y2 = y1 + stride;
2717

2718
            for (int i = 0; i < width; i += 2, row1 += 6, row2 += 6)
2719
            {
2720 2721 2722
                int u = int(uv[i + 0 + uIdx]) - 128;
                int v = int(uv[i + 1 - uIdx]) - 128;

2723 2724 2725
                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;
2726

2727 2728 2729 2730
                int y00 = std::max(0, int(y1[i]) - 16) * ITUR_BT_601_CY;
                row1[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row1[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row1[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);
2731

2732 2733 2734 2735
                int y01 = std::max(0, int(y1[i + 1]) - 16) * ITUR_BT_601_CY;
                row1[5-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row1[4]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row1[3+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
2736

2737 2738 2739 2740
                int y10 = std::max(0, int(y2[i]) - 16) * ITUR_BT_601_CY;
                row2[2-bIdx] = saturate_cast<uchar>((y10 + ruv) >> ITUR_BT_601_SHIFT);
                row2[1]      = saturate_cast<uchar>((y10 + guv) >> ITUR_BT_601_SHIFT);
                row2[bIdx]   = saturate_cast<uchar>((y10 + buv) >> ITUR_BT_601_SHIFT);
2741

2742 2743 2744 2745
                int y11 = std::max(0, int(y2[i + 1]) - 16) * ITUR_BT_601_CY;
                row2[5-bIdx] = saturate_cast<uchar>((y11 + ruv) >> ITUR_BT_601_SHIFT);
                row2[4]      = saturate_cast<uchar>((y11 + guv) >> ITUR_BT_601_SHIFT);
                row2[3+bIdx] = saturate_cast<uchar>((y11 + buv) >> ITUR_BT_601_SHIFT);
2746 2747 2748 2749 2750
            }
        }
    }
};

2751
template<int bIdx, int uIdx>
2752
struct YUV420sp2RGBA8888Invoker
2753
{
2754
    Mat* dst;
2755
    const uchar* my1, *muv;
2756
    int width, stride;
2757

2758
    YUV420sp2RGBA8888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _uv)
2759
        : dst(_dst), my1(_y1), muv(_uv), width(_dst->cols), stride(_stride) {}
2760 2761 2762

    void operator()(const BlockedRange& range) const
    {
2763 2764 2765
        int rangeBegin = range.begin() * 2;
        int rangeEnd = range.end() * 2;

2766
        //R = 1.164(Y - 16) + 1.596(V - 128)
2767 2768 2769 2770 2771 2772
        //G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128)
        //B = 1.164(Y - 16)                  + 2.018(U - 128)

        //R = (1220542(Y - 16) + 1673527(V - 128)                  + (1 << 19)) >> 20
        //G = (1220542(Y - 16) - 852492(V - 128) - 409993(U - 128) + (1 << 19)) >> 20
        //B = (1220542(Y - 16)                  + 2116026(U - 128) + (1 << 19)) >> 20
2773

2774 2775 2776 2777 2778 2779 2780 2781
        const uchar* y1 = my1 + rangeBegin * stride, *uv = muv + rangeBegin * stride / 2;

#ifdef HAVE_TEGRA_OPTIMIZATION
        if(tegra::cvtYUV4202RGB(bIdx, uIdx, 4, y1, uv, stride, dst->ptr<uchar>(rangeBegin), dst->step, rangeEnd - rangeBegin, dst->cols))
            return;
#endif

        for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, uv += stride)
2782
        {
2783
            uchar* row1 = dst->ptr<uchar>(j);
2784 2785
            uchar* row2 = dst->ptr<uchar>(j + 1);
            const uchar* y2 = y1 + stride;
2786

2787
            for (int i = 0; i < width; i += 2, row1 += 8, row2 += 8)
2788
            {
2789 2790 2791
                int u = int(uv[i + 0 + uIdx]) - 128;
                int v = int(uv[i + 1 - uIdx]) - 128;

2792 2793 2794
                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;
2795

2796 2797 2798 2799
                int y00 = std::max(0, int(y1[i]) - 16) * ITUR_BT_601_CY;
                row1[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row1[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row1[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);
2800 2801
                row1[3]      = uchar(0xff);

2802 2803 2804 2805
                int y01 = std::max(0, int(y1[i + 1]) - 16) * ITUR_BT_601_CY;
                row1[6-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row1[5]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row1[4+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
2806 2807
                row1[7]      = uchar(0xff);

2808 2809 2810 2811
                int y10 = std::max(0, int(y2[i]) - 16) * ITUR_BT_601_CY;
                row2[2-bIdx] = saturate_cast<uchar>((y10 + ruv) >> ITUR_BT_601_SHIFT);
                row2[1]      = saturate_cast<uchar>((y10 + guv) >> ITUR_BT_601_SHIFT);
                row2[bIdx]   = saturate_cast<uchar>((y10 + buv) >> ITUR_BT_601_SHIFT);
2812 2813
                row2[3]      = uchar(0xff);

2814 2815 2816 2817
                int y11 = std::max(0, int(y2[i + 1]) - 16) * ITUR_BT_601_CY;
                row2[6-bIdx] = saturate_cast<uchar>((y11 + ruv) >> ITUR_BT_601_SHIFT);
                row2[5]      = saturate_cast<uchar>((y11 + guv) >> ITUR_BT_601_SHIFT);
                row2[4+bIdx] = saturate_cast<uchar>((y11 + buv) >> ITUR_BT_601_SHIFT);
2818
                row2[7]      = uchar(0xff);
2819 2820 2821 2822 2823
            }
        }
    }
};

2824 2825 2826 2827 2828 2829
template<int bIdx>
struct YUV420p2RGB888Invoker
{
    Mat* dst;
    const uchar* my1, *mu, *mv;
    int width, stride;
2830
    int ustepIdx, vstepIdx;
2831

2832 2833
    YUV420p2RGB888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx)
        : dst(_dst), my1(_y1), mu(_u), mv(_v), width(_dst->cols), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {}
2834 2835 2836 2837 2838

    void operator()(const BlockedRange& range) const
    {
        const int rangeBegin = range.begin() * 2;
        const int rangeEnd = range.end() * 2;
A
Andrey Kamaev 已提交
2839

2840 2841
        size_t uvsteps[2] = {width/2, stride - width/2};
        int usIdx = ustepIdx, vsIdx = vstepIdx;
2842 2843

        const uchar* y1 = my1 + rangeBegin * stride;
2844 2845
        const uchar* u1 = mu + (range.begin() / 2) * stride;
        const uchar* v1 = mv + (range.begin() / 2) * stride;
A
Andrey Kamaev 已提交
2846

2847 2848 2849 2850 2851
        if(range.begin() % 2 == 1)
        {
            u1 += uvsteps[(usIdx++) & 1];
            v1 += uvsteps[(vsIdx++) & 1];
        }
2852

2853
        for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, u1 += uvsteps[(usIdx++) & 1], v1 += uvsteps[(vsIdx++) & 1])
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
        {
            uchar* row1 = dst->ptr<uchar>(j);
            uchar* row2 = dst->ptr<uchar>(j + 1);
            const uchar* y2 = y1 + stride;

            for (int i = 0; i < width / 2; i += 1, row1 += 6, row2 += 6)
            {
                int u = int(u1[i]) - 128;
                int v = int(v1[i]) - 128;

2864 2865 2866
                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;
2867

2868 2869 2870 2871
                int y00 = std::max(0, int(y1[2 * i]) - 16) * ITUR_BT_601_CY;
                row1[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row1[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row1[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);
2872

2873 2874 2875 2876
                int y01 = std::max(0, int(y1[2 * i + 1]) - 16) * ITUR_BT_601_CY;
                row1[5-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row1[4]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row1[3+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
2877

2878 2879 2880 2881
                int y10 = std::max(0, int(y2[2 * i]) - 16) * ITUR_BT_601_CY;
                row2[2-bIdx] = saturate_cast<uchar>((y10 + ruv) >> ITUR_BT_601_SHIFT);
                row2[1]      = saturate_cast<uchar>((y10 + guv) >> ITUR_BT_601_SHIFT);
                row2[bIdx]   = saturate_cast<uchar>((y10 + buv) >> ITUR_BT_601_SHIFT);
2882

2883 2884 2885 2886
                int y11 = std::max(0, int(y2[2 * i + 1]) - 16) * ITUR_BT_601_CY;
                row2[5-bIdx] = saturate_cast<uchar>((y11 + ruv) >> ITUR_BT_601_SHIFT);
                row2[4]      = saturate_cast<uchar>((y11 + guv) >> ITUR_BT_601_SHIFT);
                row2[3+bIdx] = saturate_cast<uchar>((y11 + buv) >> ITUR_BT_601_SHIFT);
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
            }
        }
    }
};

template<int bIdx>
struct YUV420p2RGBA8888Invoker
{
    Mat* dst;
    const uchar* my1, *mu, *mv;
    int width, stride;
2898
    int ustepIdx, vstepIdx;
2899

2900 2901
    YUV420p2RGBA8888Invoker(Mat* _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int _ustepIdx, int _vstepIdx)
        : dst(_dst), my1(_y1), mu(_u), mv(_v), width(_dst->cols), stride(_stride), ustepIdx(_ustepIdx), vstepIdx(_vstepIdx) {}
2902 2903 2904 2905 2906 2907

    void operator()(const BlockedRange& range) const
    {
        int rangeBegin = range.begin() * 2;
        int rangeEnd = range.end() * 2;

2908 2909
        size_t uvsteps[2] = {width/2, stride - width/2};
        int usIdx = ustepIdx, vsIdx = vstepIdx;
2910 2911

        const uchar* y1 = my1 + rangeBegin * stride;
2912 2913
        const uchar* u1 = mu + (range.begin() / 2) * stride;
        const uchar* v1 = mv + (range.begin() / 2) * stride;
A
Andrey Kamaev 已提交
2914

2915 2916 2917 2918 2919
        if(range.begin() % 2 == 1)
        {
            u1 += uvsteps[(usIdx++) & 1];
            v1 += uvsteps[(vsIdx++) & 1];
        }
2920

2921
        for (int j = rangeBegin; j < rangeEnd; j += 2, y1 += stride * 2, u1 += uvsteps[(usIdx++) & 1], v1 += uvsteps[(vsIdx++) & 1])
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
        {
            uchar* row1 = dst->ptr<uchar>(j);
            uchar* row2 = dst->ptr<uchar>(j + 1);
            const uchar* y2 = y1 + stride;

            for (int i = 0; i < width / 2; i += 1, row1 += 8, row2 += 8)
            {
                int u = int(u1[i]) - 128;
                int v = int(v1[i]) - 128;

2932 2933 2934
                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;
2935

2936 2937 2938 2939
                int y00 = std::max(0, int(y1[2 * i]) - 16) * ITUR_BT_601_CY;
                row1[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row1[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row1[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);
2940 2941
                row1[3]      = uchar(0xff);

2942 2943 2944 2945
                int y01 = std::max(0, int(y1[2 * i + 1]) - 16) * ITUR_BT_601_CY;
                row1[6-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row1[5]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row1[4+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
2946 2947
                row1[7]      = uchar(0xff);

2948 2949 2950 2951
                int y10 = std::max(0, int(y2[2 * i]) - 16) * ITUR_BT_601_CY;
                row2[2-bIdx] = saturate_cast<uchar>((y10 + ruv) >> ITUR_BT_601_SHIFT);
                row2[1]      = saturate_cast<uchar>((y10 + guv) >> ITUR_BT_601_SHIFT);
                row2[bIdx]   = saturate_cast<uchar>((y10 + buv) >> ITUR_BT_601_SHIFT);
2952 2953
                row2[3]      = uchar(0xff);

2954 2955 2956 2957
                int y11 = std::max(0, int(y2[2 * i + 1]) - 16) * ITUR_BT_601_CY;
                row2[6-bIdx] = saturate_cast<uchar>((y11 + ruv) >> ITUR_BT_601_SHIFT);
                row2[5]      = saturate_cast<uchar>((y11 + guv) >> ITUR_BT_601_SHIFT);
                row2[4+bIdx] = saturate_cast<uchar>((y11 + buv) >> ITUR_BT_601_SHIFT);
2958 2959 2960 2961 2962 2963
                row2[7]      = uchar(0xff);
            }
        }
    }
};

2964
#define MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION (320*240)
2965

2966
template<int bIdx, int uIdx>
2967
inline void cvtYUV420sp2RGB(Mat& _dst, int _stride, const uchar* _y1, const uchar* _uv)
2968
{
2969
    YUV420sp2RGB888Invoker<bIdx, uIdx> converter(&_dst, _stride, _y1,  _uv);
2970 2971 2972 2973 2974 2975 2976 2977 2978
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows/2), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows/2));
}

template<int bIdx, int uIdx>
2979
inline void cvtYUV420sp2RGBA(Mat& _dst, int _stride, const uchar* _y1, const uchar* _uv)
2980
{
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
    YUV420sp2RGBA8888Invoker<bIdx, uIdx> converter(&_dst, _stride, _y1,  _uv);
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows/2), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows/2));
}

template<int bIdx>
2991
inline void cvtYUV420p2RGB(Mat& _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx)
2992
{
2993
    YUV420p2RGB888Invoker<bIdx> converter(&_dst, _stride, _y1,  _u, _v, ustepIdx, vstepIdx);
2994 2995 2996 2997 2998 2999 3000 3001 3002
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows/2), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows/2));
}

template<int bIdx>
3003
inline void cvtYUV420p2RGBA(Mat& _dst, int _stride, const uchar* _y1, const uchar* _u, const uchar* _v, int ustepIdx, int vstepIdx)
3004
{
3005
    YUV420p2RGBA8888Invoker<bIdx> converter(&_dst, _stride, _y1,  _u, _v, ustepIdx, vstepIdx);
3006 3007 3008 3009 3010 3011 3012 3013
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV420_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows/2), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows/2));
}

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
///////////////////////////////////// YUV422 -> RGB /////////////////////////////////////

template<int bIdx, int uIdx, int yIdx>
struct YUV422toRGB888Invoker
{
    Mat* dst;
    const uchar* src;
    int width, stride;

    YUV422toRGB888Invoker(Mat* _dst, int _stride, const uchar* _yuv)
        : dst(_dst), src(_yuv), width(_dst->cols), stride(_stride) {}

    void operator()(const BlockedRange& range) const
    {
        int rangeBegin = range.begin();
        int rangeEnd = range.end();

        const int uidx = 1 - yIdx + uIdx * 2;
        const int vidx = (2 + uidx) % 4;
        const uchar* yuv_src = src + rangeBegin * stride;

        for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += stride)
        {
            uchar* row = dst->ptr<uchar>(j);

            for (int i = 0; i < 2 * width; i += 4, row += 6)
            {
                int u = int(yuv_src[i + uidx]) - 128;
                int v = int(yuv_src[i + vidx]) - 128;

                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;

                int y00 = std::max(0, int(yuv_src[i + yIdx]) - 16) * ITUR_BT_601_CY;
                row[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);

                int y01 = std::max(0, int(yuv_src[i + yIdx + 2]) - 16) * ITUR_BT_601_CY;
                row[5-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row[4]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row[3+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
            }
        }
    }
};

template<int bIdx, int uIdx, int yIdx>
struct YUV422toRGBA8888Invoker
{
    Mat* dst;
    const uchar* src;
    int width, stride;

    YUV422toRGBA8888Invoker(Mat* _dst, int _stride, const uchar* _yuv)
        : dst(_dst), src(_yuv), width(_dst->cols), stride(_stride) {}

    void operator()(const BlockedRange& range) const
    {
        int rangeBegin = range.begin();
        int rangeEnd = range.end();

        const int uidx = 1 - yIdx + uIdx * 2;
        const int vidx = (2 + uidx) % 4;
        const uchar* yuv_src = src + rangeBegin * stride;

        for (int j = rangeBegin; j < rangeEnd; j++, yuv_src += stride)
        {
            uchar* row = dst->ptr<uchar>(j);

            for (int i = 0; i < 2 * width; i += 4, row += 8)
            {
                int u = int(yuv_src[i + uidx]) - 128;
                int v = int(yuv_src[i + vidx]) - 128;

                int ruv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVR * v;
                int guv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CVG * v + ITUR_BT_601_CUG * u;
                int buv = (1 << (ITUR_BT_601_SHIFT - 1)) + ITUR_BT_601_CUB * u;

                int y00 = std::max(0, int(yuv_src[i + yIdx]) - 16) * ITUR_BT_601_CY;
                row[2-bIdx] = saturate_cast<uchar>((y00 + ruv) >> ITUR_BT_601_SHIFT);
                row[1]      = saturate_cast<uchar>((y00 + guv) >> ITUR_BT_601_SHIFT);
                row[bIdx]   = saturate_cast<uchar>((y00 + buv) >> ITUR_BT_601_SHIFT);
                row[3]      = uchar(0xff);

                int y01 = std::max(0, int(yuv_src[i + yIdx + 2]) - 16) * ITUR_BT_601_CY;
                row[6-bIdx] = saturate_cast<uchar>((y01 + ruv) >> ITUR_BT_601_SHIFT);
                row[5]      = saturate_cast<uchar>((y01 + guv) >> ITUR_BT_601_SHIFT);
                row[4+bIdx] = saturate_cast<uchar>((y01 + buv) >> ITUR_BT_601_SHIFT);
                row[7]      = uchar(0xff);
            }
        }
    }
};

#define MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION (320*240)

template<int bIdx, int uIdx, int yIdx>
inline void cvtYUV422toRGB(Mat& _dst, int _stride, const uchar* _yuv)
{
    YUV422toRGB888Invoker<bIdx, uIdx, yIdx> converter(&_dst, _stride, _yuv);
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows));
}

template<int bIdx, int uIdx, int yIdx>
inline void cvtYUV422toRGBA(Mat& _dst, int _stride, const uchar* _yuv)
{
    YUV422toRGBA8888Invoker<bIdx, uIdx, yIdx> converter(&_dst, _stride, _yuv);
#ifdef HAVE_TBB
    if (_dst.total() >= MIN_SIZE_FOR_PARALLEL_YUV422_CONVERSION)
        parallel_for(BlockedRange(0, _dst.rows), converter);
    else
#endif
        converter(BlockedRange(0, _dst.rows));
}

3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
/////////////////////////// RGBA <-> mRGBA (alpha premultiplied) //////////////

template<typename _Tp>
struct RGBA2mRGBA
{
    typedef _Tp channel_type;

    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        _Tp max_val  = ColorChannel<_Tp>::max();
        _Tp half_val = ColorChannel<_Tp>::half();
        for( int i = 0; i < n; i++ )
        {
            _Tp v0 = *src++;
            _Tp v1 = *src++;
            _Tp v2 = *src++;
            _Tp v3 = *src++;
            
            *dst++ = (v0 * v3 + half_val) / max_val;
            *dst++ = (v1 * v3 + half_val) / max_val;
            *dst++ = (v2 * v3 + half_val) / max_val;
            *dst++ = v3;
        }
    }
};


template<typename _Tp>
struct mRGBA2RGBA
{
    typedef _Tp channel_type;

    void operator()(const _Tp* src, _Tp* dst, int n) const
    {
        _Tp max_val = ColorChannel<_Tp>::max();
        for( int i = 0; i < n; i++ )
        {
            _Tp v0 = *src++;
            _Tp v1 = *src++;
            _Tp v2 = *src++;
            _Tp v3 = *src++;
            _Tp v3_half = v3 / 2;
            
            *dst++ = (v3==0)? 0 : (v0 * max_val + v3_half) / v3;
            *dst++ = (v3==0)? 0 : (v1 * max_val + v3_half) / v3;
            *dst++ = (v3==0)? 0 : (v2 * max_val + v3_half) / v3;
            *dst++ = v3;
        }
    }
};

3187
}//namespace cv
3188

3189
//////////////////////////////////////////////////////////////////////////////////////////
3190
//                                   The main function                                  //
3191
//////////////////////////////////////////////////////////////////////////////////////////
3192

3193
void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn )
3194
{
3195
    Mat src = _src.getMat(), dst;
3196 3197
    Size sz = src.size();
    int scn = src.channels(), depth = src.depth(), bidx;
A
Andrey Kamaev 已提交
3198

3199
    CV_Assert( depth == CV_8U || depth == CV_16U || depth == CV_32F );
A
Andrey Kamaev 已提交
3200

3201 3202
    switch( code )
    {
3203 3204 3205 3206 3207
        case CV_BGR2BGRA: case CV_RGB2BGRA: case CV_BGRA2BGR:
        case CV_RGBA2BGR: case CV_RGB2BGR: case CV_BGRA2RGBA:
            CV_Assert( scn == 3 || scn == 4 );
            dcn = code == CV_BGR2BGRA || code == CV_RGB2BGRA || code == CV_BGRA2RGBA ? 4 : 3;
            bidx = code == CV_BGR2BGRA || code == CV_BGRA2BGR ? 0 : 2;
A
Andrey Kamaev 已提交
3208

3209 3210
            _dst.create( sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3211

3212
            if( depth == CV_8U )
3213 3214 3215 3216 3217 3218
            {
#ifdef HAVE_TEGRA_OPTIMIZATION
                if(!tegra::cvtBGR2RGB(src, dst, bidx))
#endif
                    CvtColorLoop(src, dst, RGB2RGB<uchar>(scn, dcn, bidx));
            }
3219 3220 3221 3222 3223
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, RGB2RGB<ushort>(scn, dcn, bidx));
            else
                CvtColorLoop(src, dst, RGB2RGB<float>(scn, dcn, bidx));
            break;
A
Andrey Kamaev 已提交
3224

3225 3226 3227
        case CV_BGR2BGR565: case CV_BGR2BGR555: case CV_RGB2BGR565: case CV_RGB2BGR555:
        case CV_BGRA2BGR565: case CV_BGRA2BGR555: case CV_RGBA2BGR565: case CV_RGBA2BGR555:
            CV_Assert( (scn == 3 || scn == 4) && depth == CV_8U );
3228 3229
            _dst.create(sz, CV_8UC2);
            dst = _dst.getMat();
3230 3231 3232 3233 3234 3235

#ifdef HAVE_TEGRA_OPTIMIZATION
            if(code == CV_BGR2BGR565 || code == CV_BGRA2BGR565 || code == CV_RGB2BGR565  || code == CV_RGBA2BGR565)
                if(tegra::cvtRGB2RGB565(src, dst, code == CV_RGB2BGR565 || code == CV_RGBA2BGR565 ? 0 : 2))
                    break;
#endif
A
Andrey Kamaev 已提交
3236

3237 3238 3239 3240 3241 3242 3243
            CvtColorLoop(src, dst, RGB2RGB5x5(scn,
                      code == CV_BGR2BGR565 || code == CV_BGR2BGR555 ||
                      code == CV_BGRA2BGR565 || code == CV_BGRA2BGR555 ? 0 : 2,
                      code == CV_BGR2BGR565 || code == CV_RGB2BGR565 ||
                      code == CV_BGRA2BGR565 || code == CV_RGBA2BGR565 ? 6 : 5 // green bits
                                              ));
            break;
A
Andrey Kamaev 已提交
3244

3245 3246
        case CV_BGR5652BGR: case CV_BGR5552BGR: case CV_BGR5652RGB: case CV_BGR5552RGB:
        case CV_BGR5652BGRA: case CV_BGR5552BGRA: case CV_BGR5652RGBA: case CV_BGR5552RGBA:
3247
            if(dcn <= 0) dcn = (code==CV_BGR5652BGRA || code==CV_BGR5552BGRA || code==CV_BGR5652RGBA || code==CV_BGR5552RGBA) ? 4 : 3;
3248
            CV_Assert( (dcn == 3 || dcn == 4) && scn == 2 && depth == CV_8U );
3249 3250
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3251

3252 3253 3254 3255 3256 3257 3258
            CvtColorLoop(src, dst, RGB5x52RGB(dcn,
                      code == CV_BGR5652BGR || code == CV_BGR5552BGR ||
                      code == CV_BGR5652BGRA || code == CV_BGR5552BGRA ? 0 : 2, // blue idx
                      code == CV_BGR5652BGR || code == CV_BGR5652RGB ||
                      code == CV_BGR5652BGRA || code == CV_BGR5652RGBA ? 6 : 5 // green bits
                      ));
            break;
A
Andrey Kamaev 已提交
3259

3260 3261
        case CV_BGR2GRAY: case CV_BGRA2GRAY: case CV_RGB2GRAY: case CV_RGBA2GRAY:
            CV_Assert( scn == 3 || scn == 4 );
3262 3263
            _dst.create(sz, CV_MAKETYPE(depth, 1));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3264

3265
            bidx = code == CV_BGR2GRAY || code == CV_BGRA2GRAY ? 0 : 2;
A
Andrey Kamaev 已提交
3266

3267
            if( depth == CV_8U )
3268 3269
            {
#ifdef HAVE_TEGRA_OPTIMIZATION
A
Andrey Kamaev 已提交
3270
                if(!tegra::cvtRGB2Gray(src, dst, bidx))
3271
#endif
3272
                CvtColorLoop(src, dst, RGB2Gray<uchar>(scn, bidx, 0));
3273
            }
3274 3275 3276 3277 3278
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, RGB2Gray<ushort>(scn, bidx, 0));
            else
                CvtColorLoop(src, dst, RGB2Gray<float>(scn, bidx, 0));
            break;
A
Andrey Kamaev 已提交
3279

3280 3281
        case CV_BGR5652GRAY: case CV_BGR5552GRAY:
            CV_Assert( scn == 2 && depth == CV_8U );
3282 3283
            _dst.create(sz, CV_8UC1);
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3284

3285 3286
            CvtColorLoop(src, dst, RGB5x52Gray(code == CV_BGR5652GRAY ? 6 : 5));
            break;
A
Andrey Kamaev 已提交
3287

3288
        case CV_GRAY2BGR: case CV_GRAY2BGRA:
3289
            if( dcn <= 0 ) dcn = (code==CV_GRAY2BGRA) ? 4 : 3;
3290
            CV_Assert( scn == 1 && (dcn == 3 || dcn == 4));
3291 3292
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3293

3294
            if( depth == CV_8U )
3295 3296
            {
#ifdef HAVE_TEGRA_OPTIMIZATION
A
Andrey Kamaev 已提交
3297
                if(!tegra::cvtGray2RGB(src, dst))
3298
#endif
3299
                CvtColorLoop(src, dst, Gray2RGB<uchar>(dcn));
3300
            }
3301 3302 3303 3304 3305
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, Gray2RGB<ushort>(dcn));
            else
                CvtColorLoop(src, dst, Gray2RGB<float>(dcn));
            break;
A
Andrey Kamaev 已提交
3306

3307 3308
        case CV_GRAY2BGR565: case CV_GRAY2BGR555:
            CV_Assert( scn == 1 && depth == CV_8U );
3309 3310
            _dst.create(sz, CV_8UC2);
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3311

3312 3313
            CvtColorLoop(src, dst, Gray2RGB5x5(code == CV_GRAY2BGR565 ? 6 : 5));
            break;
A
Andrey Kamaev 已提交
3314

3315 3316 3317 3318 3319 3320 3321 3322 3323
        case CV_BGR2YCrCb: case CV_RGB2YCrCb:
        case CV_BGR2YUV: case CV_RGB2YUV:
            {
            CV_Assert( scn == 3 || scn == 4 );
            bidx = code == CV_BGR2YCrCb || code == CV_RGB2YUV ? 0 : 2;
            static const float yuv_f[] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f };
            static const int yuv_i[] = { B2Y, G2Y, R2Y, 8061, 14369 };
            const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f;
            const int* coeffs_i = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_i;
A
Andrey Kamaev 已提交
3324

3325 3326
            _dst.create(sz, CV_MAKETYPE(depth, 3));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3327

3328
            if( depth == CV_8U )
3329 3330
            {
#ifdef HAVE_TEGRA_OPTIMIZATION
A
Andrey Kamaev 已提交
3331
                if((code == CV_RGB2YCrCb || code == CV_BGR2YCrCb) && tegra::cvtRGB2YCrCb(src, dst, bidx))
3332 3333
                    break;
#endif
3334
                CvtColorLoop(src, dst, RGB2YCrCb_i<uchar>(scn, bidx, coeffs_i));
3335
            }
3336 3337 3338 3339 3340 3341
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, RGB2YCrCb_i<ushort>(scn, bidx, coeffs_i));
            else
                CvtColorLoop(src, dst, RGB2YCrCb_f<float>(scn, bidx, coeffs_f));
            }
            break;
A
Andrey Kamaev 已提交
3342

3343 3344 3345 3346 3347 3348 3349
        case CV_YCrCb2BGR: case CV_YCrCb2RGB:
        case CV_YUV2BGR: case CV_YUV2RGB:
            {
            if( dcn <= 0 ) dcn = 3;
            CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) );
            bidx = code == CV_YCrCb2BGR || code == CV_YUV2RGB ? 0 : 2;
            static const float yuv_f[] = { 2.032f, -0.395f, -0.581f, 1.140f };
A
Andrey Kamaev 已提交
3350
            static const int yuv_i[] = { 33292, -6472, -9519, 18678 };
3351 3352
            const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f;
            const int* coeffs_i = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_i;
A
Andrey Kamaev 已提交
3353

3354 3355
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3356

3357 3358 3359 3360 3361 3362 3363 3364
            if( depth == CV_8U )
                CvtColorLoop(src, dst, YCrCb2RGB_i<uchar>(dcn, bidx, coeffs_i));
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, YCrCb2RGB_i<ushort>(dcn, bidx, coeffs_i));
            else
                CvtColorLoop(src, dst, YCrCb2RGB_f<float>(dcn, bidx, coeffs_f));
            }
            break;
A
Andrey Kamaev 已提交
3365

3366 3367 3368
        case CV_BGR2XYZ: case CV_RGB2XYZ:
            CV_Assert( scn == 3 || scn == 4 );
            bidx = code == CV_BGR2XYZ ? 0 : 2;
A
Andrey Kamaev 已提交
3369

3370 3371
            _dst.create(sz, CV_MAKETYPE(depth, 3));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3372

3373 3374 3375 3376 3377 3378 3379
            if( depth == CV_8U )
                CvtColorLoop(src, dst, RGB2XYZ_i<uchar>(scn, bidx, 0));
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, RGB2XYZ_i<ushort>(scn, bidx, 0));
            else
                CvtColorLoop(src, dst, RGB2XYZ_f<float>(scn, bidx, 0));
            break;
A
Andrey Kamaev 已提交
3380

3381 3382 3383 3384
        case CV_XYZ2BGR: case CV_XYZ2RGB:
            if( dcn <= 0 ) dcn = 3;
            CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) );
            bidx = code == CV_XYZ2BGR ? 0 : 2;
A
Andrey Kamaev 已提交
3385

3386 3387
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3388

3389 3390 3391 3392 3393 3394 3395
            if( depth == CV_8U )
                CvtColorLoop(src, dst, XYZ2RGB_i<uchar>(dcn, bidx, 0));
            else if( depth == CV_16U )
                CvtColorLoop(src, dst, XYZ2RGB_i<ushort>(dcn, bidx, 0));
            else
                CvtColorLoop(src, dst, XYZ2RGB_f<float>(dcn, bidx, 0));
            break;
A
Andrey Kamaev 已提交
3396

3397 3398 3399 3400 3401 3402 3403
        case CV_BGR2HSV: case CV_RGB2HSV: case CV_BGR2HSV_FULL: case CV_RGB2HSV_FULL:
        case CV_BGR2HLS: case CV_RGB2HLS: case CV_BGR2HLS_FULL: case CV_RGB2HLS_FULL:
            {
            CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) );
            bidx = code == CV_BGR2HSV || code == CV_BGR2HLS ||
                code == CV_BGR2HSV_FULL || code == CV_BGR2HLS_FULL ? 0 : 2;
            int hrange = depth == CV_32F ? 360 : code == CV_BGR2HSV || code == CV_RGB2HSV ||
3404
                code == CV_BGR2HLS || code == CV_RGB2HLS ? 180 : 256;
A
Andrey Kamaev 已提交
3405

3406 3407
            _dst.create(sz, CV_MAKETYPE(depth, 3));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3408

3409 3410 3411
            if( code == CV_BGR2HSV || code == CV_RGB2HSV ||
                code == CV_BGR2HSV_FULL || code == CV_RGB2HSV_FULL )
            {
3412
#ifdef HAVE_TEGRA_OPTIMIZATION
A
Andrey Kamaev 已提交
3413
                if(tegra::cvtRGB2HSV(src, dst, bidx, hrange))
3414 3415
                    break;
#endif
3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, RGB2HSV_b(scn, bidx, hrange));
                else
                    CvtColorLoop(src, dst, RGB2HSV_f(scn, bidx, (float)hrange));
            }
            else
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, RGB2HLS_b(scn, bidx, hrange));
                else
                    CvtColorLoop(src, dst, RGB2HLS_f(scn, bidx, (float)hrange));
            }
            }
            break;
A
Andrey Kamaev 已提交
3430

3431 3432 3433 3434 3435 3436 3437 3438 3439
        case CV_HSV2BGR: case CV_HSV2RGB: case CV_HSV2BGR_FULL: case CV_HSV2RGB_FULL:
        case CV_HLS2BGR: case CV_HLS2RGB: case CV_HLS2BGR_FULL: case CV_HLS2RGB_FULL:
            {
            if( dcn <= 0 ) dcn = 3;
            CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) );
            bidx = code == CV_HSV2BGR || code == CV_HLS2BGR ||
                code == CV_HSV2BGR_FULL || code == CV_HLS2BGR_FULL ? 0 : 2;
            int hrange = depth == CV_32F ? 360 : code == CV_HSV2BGR || code == CV_HSV2RGB ||
                code == CV_HLS2BGR || code == CV_HLS2RGB ? 180 : 255;
A
Andrey Kamaev 已提交
3440

3441 3442
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3443

3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
            if( code == CV_HSV2BGR || code == CV_HSV2RGB ||
                code == CV_HSV2BGR_FULL || code == CV_HSV2RGB_FULL )
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, HSV2RGB_b(dcn, bidx, hrange));
                else
                    CvtColorLoop(src, dst, HSV2RGB_f(dcn, bidx, (float)hrange));
            }
            else
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, HLS2RGB_b(dcn, bidx, hrange));
                else
                    CvtColorLoop(src, dst, HLS2RGB_f(dcn, bidx, (float)hrange));
            }
            }
            break;
A
Andrey Kamaev 已提交
3461

3462 3463 3464 3465 3466 3467 3468 3469
        case CV_BGR2Lab: case CV_RGB2Lab: case CV_LBGR2Lab: case CV_LRGB2Lab:
        case CV_BGR2Luv: case CV_RGB2Luv: case CV_LBGR2Luv: case CV_LRGB2Luv:
            {
            CV_Assert( (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) );
            bidx = code == CV_BGR2Lab || code == CV_BGR2Luv ||
                   code == CV_LBGR2Lab || code == CV_LBGR2Luv ? 0 : 2;
            bool srgb = code == CV_BGR2Lab || code == CV_RGB2Lab ||
                        code == CV_BGR2Luv || code == CV_RGB2Luv;
A
Andrey Kamaev 已提交
3470

3471 3472
            _dst.create(sz, CV_MAKETYPE(depth, 3));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3473

3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
            if( code == CV_BGR2Lab || code == CV_RGB2Lab ||
                code == CV_LBGR2Lab || code == CV_LRGB2Lab )
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, RGB2Lab_b(scn, bidx, 0, 0, srgb));
                else
                    CvtColorLoop(src, dst, RGB2Lab_f(scn, bidx, 0, 0, srgb));
            }
            else
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, RGB2Luv_b(scn, bidx, 0, 0, srgb));
                else
                    CvtColorLoop(src, dst, RGB2Luv_f(scn, bidx, 0, 0, srgb));
            }
            }
            break;
A
Andrey Kamaev 已提交
3491

3492 3493 3494 3495 3496 3497 3498 3499 3500
        case CV_Lab2BGR: case CV_Lab2RGB: case CV_Lab2LBGR: case CV_Lab2LRGB:
        case CV_Luv2BGR: case CV_Luv2RGB: case CV_Luv2LBGR: case CV_Luv2LRGB:
            {
            if( dcn <= 0 ) dcn = 3;
            CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) && (depth == CV_8U || depth == CV_32F) );
            bidx = code == CV_Lab2BGR || code == CV_Luv2BGR ||
                   code == CV_Lab2LBGR || code == CV_Luv2LBGR ? 0 : 2;
            bool srgb = code == CV_Lab2BGR || code == CV_Lab2RGB ||
                    code == CV_Luv2BGR || code == CV_Luv2RGB;
A
Andrey Kamaev 已提交
3501

3502 3503
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3504

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
            if( code == CV_Lab2BGR || code == CV_Lab2RGB ||
                code == CV_Lab2LBGR || code == CV_Lab2LRGB )
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, Lab2RGB_b(dcn, bidx, 0, 0, srgb));
                else
                    CvtColorLoop(src, dst, Lab2RGB_f(dcn, bidx, 0, 0, srgb));
            }
            else
            {
                if( depth == CV_8U )
                    CvtColorLoop(src, dst, Luv2RGB_b(dcn, bidx, 0, 0, srgb));
                else
                    CvtColorLoop(src, dst, Luv2RGB_f(dcn, bidx, 0, 0, srgb));
            }
            }
            break;
A
Andrey Kamaev 已提交
3522

3523
        case CV_BayerBG2GRAY: case CV_BayerGB2GRAY: case CV_BayerRG2GRAY: case CV_BayerGR2GRAY:
3524
            if(dcn <= 0) dcn = 1;
3525
            CV_Assert( scn == 1 && dcn == 1 );
A
Andrey Kamaev 已提交
3526

3527 3528
            _dst.create(sz, depth);
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3529

3530 3531 3532 3533 3534 3535 3536
            if( depth == CV_8U )
                Bayer2Gray_<uchar, SIMDBayerInterpolator_8u>(src, dst, code);
            else if( depth == CV_16U )
                Bayer2Gray_<ushort, SIMDBayerStubInterpolator_<ushort> >(src, dst, code);
            else
                CV_Error(CV_StsUnsupportedFormat, "Bayer->Gray demosaicing only supports 8u and 16u types");
            break;
A
Andrey Kamaev 已提交
3537

3538 3539
        case CV_BayerBG2BGR: case CV_BayerGB2BGR: case CV_BayerRG2BGR: case CV_BayerGR2BGR:
        case CV_BayerBG2BGR_VNG: case CV_BayerGB2BGR_VNG: case CV_BayerRG2BGR_VNG: case CV_BayerGR2BGR_VNG:
3540
            if(dcn <= 0) dcn = 3;
3541
            CV_Assert( scn == 1 && dcn == 3 );
A
Andrey Kamaev 已提交
3542

3543 3544
            _dst.create(sz, CV_MAKETYPE(depth, dcn));
            dst = _dst.getMat();
A
Andrey Kamaev 已提交
3545

3546 3547
            if( code == CV_BayerBG2BGR || code == CV_BayerGB2BGR ||
                code == CV_BayerRG2BGR || code == CV_BayerGR2BGR )
3548 3549 3550 3551 3552 3553 3554 3555
            {
                if( depth == CV_8U )
                    Bayer2RGB_<uchar, SIMDBayerInterpolator_8u>(src, dst, code);
                else if( depth == CV_16U )
                    Bayer2RGB_<ushort, SIMDBayerStubInterpolator_<ushort> >(src, dst, code);
                else
                    CV_Error(CV_StsUnsupportedFormat, "Bayer->RGB demosaicing only supports 8u and 16u types");
            }
3556
            else
3557 3558
            {
                CV_Assert( depth == CV_8U );
3559
                Bayer2RGB_VNG_8u(src, dst, code);
3560
            }
3561
            break;
3562 3563
        case CV_YUV2BGR_NV21:  case CV_YUV2RGB_NV21:  case CV_YUV2BGR_NV12:  case CV_YUV2RGB_NV12:
        case CV_YUV2BGRA_NV21: case CV_YUV2RGBA_NV21: case CV_YUV2BGRA_NV12: case CV_YUV2RGBA_NV12:
3564
            {
3565 3566
                // http://www.fourcc.org/yuv.php#NV21 == yuv420sp -> a plane of 8 bit Y samples followed by an interleaved V/U plane containing 8 bit 2x2 subsampled chroma samples
                // http://www.fourcc.org/yuv.php#NV12 -> a plane of 8 bit Y samples followed by an interleaved U/V plane containing 8 bit 2x2 subsampled colour difference samples
A
Andrey Kamaev 已提交
3567

3568
                if (dcn <= 0) dcn = (code==CV_YUV420sp2BGRA || code==CV_YUV420sp2RGBA || code==CV_YUV2BGRA_NV12 || code==CV_YUV2RGBA_NV12) ? 4 : 3;
A
Andrey Kamaev 已提交
3569 3570 3571
                const int bIdx = (code==CV_YUV2BGR_NV21 || code==CV_YUV2BGRA_NV21 || code==CV_YUV2BGR_NV12 || code==CV_YUV2BGRA_NV12) ? 0 : 2;
                const int uIdx = (code==CV_YUV2BGR_NV21 || code==CV_YUV2BGRA_NV21 || code==CV_YUV2RGB_NV21 || code==CV_YUV2RGBA_NV21) ? 1 : 0;

3572
                CV_Assert( dcn == 3 || dcn == 4 );
3573
                CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U );
A
Andrey Kamaev 已提交
3574

3575
                Size dstSz(sz.width, sz.height * 2 / 3);
3576
                _dst.create(dstSz, CV_MAKETYPE(depth, dcn));
3577 3578
                dst = _dst.getMat();

3579
                int srcstep = (int)src.step;
3580 3581
                const uchar* y = src.ptr();
                const uchar* uv = y + srcstep * dstSz.height;
A
Andrey Kamaev 已提交
3582 3583

                switch(dcn*100 + bIdx * 10 + uIdx)
3584
                {
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601
                    case 300: cvtYUV420sp2RGB<0, 0> (dst, srcstep, y, uv); break;
                    case 301: cvtYUV420sp2RGB<0, 1> (dst, srcstep, y, uv); break;
                    case 320: cvtYUV420sp2RGB<2, 0> (dst, srcstep, y, uv); break;
                    case 321: cvtYUV420sp2RGB<2, 1> (dst, srcstep, y, uv); break;
                    case 400: cvtYUV420sp2RGBA<0, 0>(dst, srcstep, y, uv); break;
                    case 401: cvtYUV420sp2RGBA<0, 1>(dst, srcstep, y, uv); break;
                    case 420: cvtYUV420sp2RGBA<2, 0>(dst, srcstep, y, uv); break;
                    case 421: cvtYUV420sp2RGBA<2, 1>(dst, srcstep, y, uv); break;
                    default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break;
                };
            }
            break;
        case CV_YUV2BGR_YV12: case CV_YUV2RGB_YV12: case CV_YUV2BGRA_YV12: case CV_YUV2RGBA_YV12:
        case CV_YUV2BGR_IYUV: case CV_YUV2RGB_IYUV: case CV_YUV2BGRA_IYUV: case CV_YUV2RGBA_IYUV:
            {
                //http://www.fourcc.org/yuv.php#YV12 == yuv420p -> It comprises an NxM Y plane followed by (N/2)x(M/2) V and U planes.
                //http://www.fourcc.org/yuv.php#IYUV == I420 -> It comprises an NxN Y plane followed by (N/2)x(N/2) U and V planes
A
Andrey Kamaev 已提交
3602

3603
                if (dcn <= 0) dcn = (code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12 || code==CV_YUV2RGBA_IYUV || code==CV_YUV2BGRA_IYUV) ? 4 : 3;
A
Andrey Kamaev 已提交
3604 3605 3606
                const int bIdx = (code==CV_YUV2BGR_YV12 || code==CV_YUV2BGRA_YV12 || code==CV_YUV2BGR_IYUV || code==CV_YUV2BGRA_IYUV) ? 0 : 2;
                const int uIdx  = (code==CV_YUV2BGR_YV12 || code==CV_YUV2RGB_YV12 || code==CV_YUV2BGRA_YV12 || code==CV_YUV2RGBA_YV12) ? 1 : 0;

3607 3608 3609 3610 3611 3612
                CV_Assert( dcn == 3 || dcn == 4 );
                CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U );

                Size dstSz(sz.width, sz.height * 2 / 3);
                _dst.create(dstSz, CV_MAKETYPE(depth, dcn));
                dst = _dst.getMat();
A
Andrey Kamaev 已提交
3613

3614 3615 3616
                int srcstep = (int)src.step;
                const uchar* y = src.ptr();
                const uchar* u = y + srcstep * dstSz.height;
3617
                const uchar* v = y + srcstep * (dstSz.height + dstSz.height/4) + (dstSz.width/2) * ((dstSz.height % 4)/2);
A
Andrey Kamaev 已提交
3618

3619 3620
                int ustepIdx = 0;
                int vstepIdx = dstSz.height % 4 == 2 ? 1 : 0;
A
Andrey Kamaev 已提交
3621 3622 3623 3624

                if(uIdx == 1) { std::swap(u ,v), std::swap(ustepIdx, vstepIdx); };

                switch(dcn*10 + bIdx)
3625
                {
3626 3627 3628 3629
                    case 30: cvtYUV420p2RGB<0>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break;
                    case 32: cvtYUV420p2RGB<2>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break;
                    case 40: cvtYUV420p2RGBA<0>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break;
                    case 42: cvtYUV420p2RGBA<2>(dst, srcstep, y, u, v, ustepIdx, vstepIdx); break;
3630 3631
                    default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break;
                };
3632 3633
            }
            break;
3634 3635 3636
        case CV_YUV2GRAY_420:
            {
                if (dcn <= 0) dcn = 1;
A
Andrey Kamaev 已提交
3637

3638 3639 3640 3641 3642 3643
                CV_Assert( dcn == 1 );
                CV_Assert( sz.width % 2 == 0 && sz.height % 3 == 0 && depth == CV_8U );

                Size dstSz(sz.width, sz.height * 2 / 3);
                _dst.create(dstSz, CV_MAKETYPE(depth, dcn));
                dst = _dst.getMat();
A
Andrey Kamaev 已提交
3644

3645 3646 3647
                src(Range(0, dstSz.height), Range::all()).copyTo(dst);
            }
            break;
3648 3649 3650 3651 3652 3653
        case CV_YUV2RGB_UYVY: case CV_YUV2BGR_UYVY: case CV_YUV2RGBA_UYVY: case CV_YUV2BGRA_UYVY:
        case CV_YUV2RGB_YUY2: case CV_YUV2BGR_YUY2: case CV_YUV2RGB_YVYU: case CV_YUV2BGR_YVYU:
        case CV_YUV2RGBA_YUY2: case CV_YUV2BGRA_YUY2: case CV_YUV2RGBA_YVYU: case CV_YUV2BGRA_YVYU:
            {
                //http://www.fourcc.org/yuv.php#UYVY
                //http://www.fourcc.org/yuv.php#YUY2
A
Andrey Kamaev 已提交
3654 3655
                //http://www.fourcc.org/yuv.php#YVYU

3656
                if (dcn <= 0) dcn = (code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY || code==CV_YUV2RGBA_YUY2 || code==CV_YUV2BGRA_YUY2 || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 4 : 3;
A
Andrey Kamaev 已提交
3657 3658 3659 3660
                const int bIdx = (code==CV_YUV2BGR_UYVY || code==CV_YUV2BGRA_UYVY || code==CV_YUV2BGR_YUY2 || code==CV_YUV2BGRA_YUY2 || code==CV_YUV2BGR_YVYU || code==CV_YUV2BGRA_YVYU) ? 0 : 2;
                const int ycn  = (code==CV_YUV2RGB_UYVY || code==CV_YUV2BGR_UYVY || code==CV_YUV2RGBA_UYVY || code==CV_YUV2BGRA_UYVY) ? 1 : 0;
                const int uIdx = (code==CV_YUV2RGB_YVYU || code==CV_YUV2BGR_YVYU || code==CV_YUV2RGBA_YVYU || code==CV_YUV2BGRA_YVYU) ? 1 : 0;

3661 3662 3663 3664 3665
                CV_Assert( dcn == 3 || dcn == 4 );
                CV_Assert( scn == 2 && depth == CV_8U );

                _dst.create(sz, CV_8UC(dcn));
                dst = _dst.getMat();
A
Andrey Kamaev 已提交
3666 3667

                switch(dcn*1000 + bIdx*100 + uIdx*10 + ycn)
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
                {
                    case 3000: cvtYUV422toRGB<0,0,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3001: cvtYUV422toRGB<0,0,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3010: cvtYUV422toRGB<0,1,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3011: cvtYUV422toRGB<0,1,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3200: cvtYUV422toRGB<2,0,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3201: cvtYUV422toRGB<2,0,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3210: cvtYUV422toRGB<2,1,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 3211: cvtYUV422toRGB<2,1,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4000: cvtYUV422toRGBA<0,0,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4001: cvtYUV422toRGBA<0,0,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4010: cvtYUV422toRGBA<0,1,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4011: cvtYUV422toRGBA<0,1,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4200: cvtYUV422toRGBA<2,0,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4201: cvtYUV422toRGBA<2,0,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4210: cvtYUV422toRGBA<2,1,0>(dst, (int)src.step, src.ptr<uchar>()); break;
                    case 4211: cvtYUV422toRGBA<2,1,1>(dst, (int)src.step, src.ptr<uchar>()); break;
                    default: CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" ); break;
                };
            }
            break;
        case CV_YUV2GRAY_UYVY: case CV_YUV2GRAY_YUY2:
            {
                if (dcn <= 0) dcn = 1;
A
Andrey Kamaev 已提交
3692

3693 3694 3695 3696 3697
                CV_Assert( dcn == 1 );
                CV_Assert( scn == 2 && depth == CV_8U );

                extractChannel(_src, _dst, code == CV_YUV2GRAY_UYVY ? 1 : 0);
            }
3698
            break;
3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
        case CV_RGBA2mRGBA:
            {
                if (dcn <= 0) dcn = 4;
                CV_Assert( scn == 4 && dcn == 4 );

                _dst.create(sz, CV_MAKETYPE(depth, dcn));
                dst = _dst.getMat();

                if( depth == CV_8U )
                {
                    CvtColorLoop(src, dst, RGBA2mRGBA<uchar>());
                } else {
                    CV_Error( CV_StsBadArg, "Unsupported image depth" );
                }
            }
            break;
        case CV_mRGBA2RGBA:
            {
                if (dcn <= 0) dcn = 4;
                CV_Assert( scn == 4 && dcn == 4 );

                _dst.create(sz, CV_MAKETYPE(depth, dcn));
                dst = _dst.getMat();

                if( depth == CV_8U )
                {
                    CvtColorLoop(src, dst, mRGBA2RGBA<uchar>());
                } else {
                    CV_Error( CV_StsBadArg, "Unsupported image depth" );
                }
            }
            break;
3731 3732
        default:
            CV_Error( CV_StsBadFlag, "Unknown/unsupported color conversion code" );
3733 3734
    }
}
A
Andrey Kamaev 已提交
3735

3736 3737
CV_IMPL void
cvCvtColor( const CvArr* srcarr, CvArr* dstarr, int code )
3738
{
3739 3740
    cv::Mat src = cv::cvarrToMat(srcarr), dst0 = cv::cvarrToMat(dstarr), dst = dst0;
    CV_Assert( src.depth() == dst.depth() );
A
Andrey Kamaev 已提交
3741

3742 3743
    cv::cvtColor(src, dst, code, dst.channels());
    CV_Assert( dst.data == dst0.data );
3744 3745
}

3746

3747
/* End of file. */