imgproc.cpp 80.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
yao's avatar
yao committed
15
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
16 17 18 19 20 21 22 23 24 25 26
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Niko Li, newlife20080214@gmail.com
//    Jia Haipeng, jiahaipeng95@gmail.com
//    Shengen Yan, yanshengen@gmail.com
//    Rock Li, Rock.Li@amd.com
//    Zero Lin, Zero.Lin@amd.com
//    Zhang Ying, zhangying913@gmail.com
//    Xu Pang, pangxu010@163.com
//    Wu Zailong, bullet@yeah.net
yao's avatar
yao committed
27
//    Wenju He, wenju@multicorewareinc.com
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
//
// 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 oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include <iomanip>

using namespace cv;
using namespace cv::ocl;

namespace cv
{
    namespace ocl
    {

        ////////////////////////////////////OpenCL kernel strings//////////////////////////
        extern const char *meanShift;
        extern const char *imgproc_copymakeboder;
        extern const char *imgproc_median;
        extern const char *imgproc_threshold;
        extern const char *imgproc_resize;
        extern const char *imgproc_remap;
        extern const char *imgproc_warpAffine;
        extern const char *imgproc_warpPerspective;
        extern const char *imgproc_integral_sum;
        extern const char *imgproc_integral;
        extern const char *imgproc_histogram;
        extern const char *imgproc_bilateral;
        extern const char *imgproc_calcHarris;
        extern const char *imgproc_calcMinEigenVal;
81
        extern const char *imgproc_convolve;
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        ////////////////////////////////////OpenCL call wrappers////////////////////////////

        template <typename T> struct index_and_sizeof;
        template <> struct index_and_sizeof<char>
        {
            enum { index = 1 };
        };
        template <> struct index_and_sizeof<unsigned char>
        {
            enum { index = 2 };
        };
        template <> struct index_and_sizeof<short>
        {
            enum { index = 3 };
        };
        template <> struct index_and_sizeof<unsigned short>
        {
            enum { index = 4 };
        };
        template <> struct index_and_sizeof<int>
        {
            enum { index = 5 };
        };
        template <> struct index_and_sizeof<float>
        {
            enum { index = 6 };
        };
        template <> struct index_and_sizeof<double>
        {
            enum { index = 7 };
        };

        /////////////////////////////////////////////////////////////////////////////////////
        // threshold

        typedef void (*gpuThresh_t)(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type);

119
        static void threshold_8u(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type)
120 121 122 123 124 125
        {
            CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
            Context *clCxt = src.clCxt;

            uchar thresh_uchar = cvFloor(thresh);
            uchar max_val = cvRound(maxVal);
126
            std::string kernelName = "threshold";
127 128 129 130 131 132 133 134

            size_t cols = (dst.cols + (dst.offset % 16) + 15) / 16;
            size_t bSizeX = 16, bSizeY = 16;
            size_t gSizeX = cols % bSizeX == 0 ? cols : (cols + bSizeX - 1) / bSizeX * bSizeX;
            size_t gSizeY = dst.rows;
            size_t globalThreads[3] = {gSizeX, gSizeY, 1};
            size_t localThreads[3] = {bSizeX, bSizeY, 1};

135 136 137 138 139 140 141 142 143 144 145 146
            std::vector< std::pair<size_t, const void *> > args;
            args.push_back( std::make_pair(sizeof(cl_mem), &src.data));
            args.push_back( std::make_pair(sizeof(cl_mem), &dst.data));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.offset));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.step));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.offset));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.step));
            args.push_back( std::make_pair(sizeof(cl_uchar), (void *)&thresh_uchar));
            args.push_back( std::make_pair(sizeof(cl_uchar), (void *)&max_val));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&type));
147
            openCLExecuteKernel(clCxt, &imgproc_threshold, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
148 149
        }

150
        static void threshold_32f(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type)
151 152 153 154 155 156 157 158 159 160 161
        {
            CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
            Context *clCxt = src.clCxt;

            float thresh_f = thresh;
            float max_val = maxVal;
            int dst_offset = (dst.offset >> 2);
            int dst_step = (dst.step >> 2);
            int src_offset = (src.offset >> 2);
            int src_step = (src.step >> 2);

162
            std::string kernelName = "threshold";
163 164 165 166 167 168 169 170 171

            size_t cols = (dst.cols + (dst_offset & 3) + 3) / 4;
            //size_t cols = dst.cols;
            size_t bSizeX = 16, bSizeY = 16;
            size_t gSizeX = cols % bSizeX == 0 ? cols : (cols + bSizeX - 1) / bSizeX * bSizeX;
            size_t gSizeY = dst.rows;
            size_t globalThreads[3] = {gSizeX, gSizeY, 1};
            size_t localThreads[3] = {bSizeX, bSizeY, 1};

172 173 174 175 176 177 178 179 180 181 182 183
            std::vector< std::pair<size_t, const void *> > args;
            args.push_back( std::make_pair(sizeof(cl_mem), &src.data));
            args.push_back( std::make_pair(sizeof(cl_mem), &dst.data));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&src_offset));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&src_step));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst_offset));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst_step));
            args.push_back( std::make_pair(sizeof(cl_float), (void *)&thresh_f));
            args.push_back( std::make_pair(sizeof(cl_float), (void *)&max_val));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&type));
184
            openCLExecuteKernel(clCxt, &imgproc_threshold, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

        }

        //threshold: support 8UC1 and 32FC1 data type and five threshold type
        double threshold(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type)
        {
            //TODO: These limitations shall be removed later.
            CV_Assert(src.type() == CV_8UC1 || src.type() == CV_32FC1);
            CV_Assert(type == THRESH_BINARY || type == THRESH_BINARY_INV || type == THRESH_TRUNC
                      || type == THRESH_TOZERO || type == THRESH_TOZERO_INV );

            static const gpuThresh_t gpuThresh_callers[2] = {threshold_8u, threshold_32f};

            dst.create( src.size(), src.type() );
            gpuThresh_callers[(src.type() == CV_32FC1)](src, dst, thresh, maxVal, type);

            return thresh;
        }
203 204 205
        ////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////   remap   //////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////
206

207
        void remap( const oclMat &src, oclMat &dst, oclMat &map1, oclMat &map2, int interpolation, int borderType, const Scalar &borderValue )
208 209
        {
            Context *clCxt = src.clCxt;
210 211 212 213
            CV_Assert(interpolation == INTER_LINEAR || interpolation == INTER_NEAREST
                      || interpolation == INTER_CUBIC || interpolation == INTER_LANCZOS4);
            CV_Assert((map1.type() == CV_16SC2 && !map2.data) || (map1.type() == CV_32FC2 && !map2.data) || (map1.type() == CV_32FC1 && map2.type() == CV_32FC1));
            CV_Assert(!map2.data || map2.size() == map1.size());
niko's avatar
niko committed
214
            CV_Assert(dst.size() == map1.size());
215 216

            dst.create(map1.size(), src.type());
217

218

219
            std::string kernelName;
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

            if( map1.type() == CV_32FC2 && !map2.data )
            {
                if(interpolation == INTER_LINEAR && borderType == BORDER_CONSTANT)
                    kernelName = "remapLNFConstant";
                else if(interpolation == INTER_NEAREST && borderType == BORDER_CONSTANT)
                    kernelName = "remapNNFConstant";
            }
            else if(map1.type() == CV_16SC2 && !map2.data)
            {
                if(interpolation == INTER_LINEAR && borderType == BORDER_CONSTANT)
                    kernelName = "remapLNSConstant";
                else if(interpolation == INTER_NEAREST && borderType == BORDER_CONSTANT)
                    kernelName = "remapNNSConstant";

            }
236
            else if(map1.type() == CV_32FC1 && map2.type() == CV_32FC1)
niko's avatar
niko committed
237 238 239 240 241 242 243
            {
                if(interpolation == INTER_LINEAR && borderType == BORDER_CONSTANT)
                    kernelName = "remapLNF1Constant";
                else if (interpolation == INTER_NEAREST && borderType == BORDER_CONSTANT)
                    kernelName = "remapNNF1Constant";
            }

Niko's avatar
Niko committed
244 245 246
            //int channels = dst.oclchannels();
            //int depth = dst.depth();
            //int type = src.type();
247 248
            size_t blkSizeX = 16, blkSizeY = 16;
            size_t glbSizeX;
niko's avatar
niko committed
249
            int cols = dst.cols;
250
            if(src.type() == CV_8UC1)
251
            {
252 253 254
                cols = (dst.cols + dst.offset % 4 + 3) / 4;
                glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;

niko's avatar
niko committed
255
            }
Niko's avatar
Niko committed
256
            else if(src.type() == CV_32FC1 && interpolation == INTER_LINEAR)
niko's avatar
niko committed
257
            {
258 259
                cols = (dst.cols + (dst.offset >> 2) % 4 + 3) / 4;
                glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
260 261 262
            }
            else
            {
263 264
                glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;

265
            }
niko's avatar
niko committed
266

267 268 269
            size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
            size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
            size_t localThreads[3] = {blkSizeX, blkSizeY, 1};
niko's avatar
niko committed
270

271

272
            std::vector< std::pair<size_t, const void *> > args;
273 274
            if(map1.channels() == 2)
            {
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&map1.data));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&cols));
yao's avatar
yao committed
291
                float borderFloat[4] = {(float)borderValue[0], (float)borderValue[1], (float)borderValue[2], (float)borderValue[3]};
Andrey Kamaev's avatar
Andrey Kamaev committed
292

yao's avatar
yao committed
293
               if(src.clCxt -> impl -> double_support != 0)
294
                {
295
                    args.push_back( std::make_pair(sizeof(cl_double4), (void *)&borderValue));
296 297 298
                }
                else
                {
299
                    args.push_back( std::make_pair(sizeof(cl_float4), (void *)&borderFloat));
300
                }
niko's avatar
niko committed
301 302 303
            }
            if(map1.channels() == 1)
            {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&map1.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&map2.data));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.offset));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.step));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&map1.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&cols));
niko's avatar
niko committed
321 322
                if(src.clCxt -> impl -> double_support != 0)
                {
323
                    args.push_back( std::make_pair(sizeof(cl_double4), (void *)&borderValue));
niko's avatar
niko committed
324 325 326
                }
                else
                {
327
                    float borderFloat[4] = {(float)borderValue[0], (float)borderValue[1], (float)borderValue[2], (float)borderValue[3]};
328
                    args.push_back( std::make_pair(sizeof(cl_float4), (void *)&borderFloat));
niko's avatar
niko committed
329 330
                }
            }
331 332 333
            openCLExecuteKernel(clCxt, &imgproc_remap, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
        }

334 335 336
        ////////////////////////////////////////////////////////////////////////////////////////////
        // resize

337
        static void resize_gpu( const oclMat &src, oclMat &dst, double fx, double fy, int interpolation)
338 339 340 341 342 343 344
        {
            CV_Assert( (src.channels() == dst.channels()) );
            Context *clCxt = src.clCxt;
            float ifx = 1. / fx;
            float ify = 1. / fy;
            double ifx_d = 1. / fx;
            double ify_d = 1. / fy;
345 346 347 348 349
            int srcStep_in_pixel = src.step1() / src.oclchannels();
            int srcoffset_in_pixel = src.offset / src.elemSize();
            int dstStep_in_pixel = dst.step1() / dst.oclchannels();
            int dstoffset_in_pixel = dst.offset / dst.elemSize();
            //printf("%d %d\n",src.step1() , dst.elemSize());
350
            std::string kernelName;
351 352 353 354 355 356 357 358 359 360 361
            if(interpolation == INTER_LINEAR)
                kernelName = "resizeLN";
            else if(interpolation == INTER_NEAREST)
                kernelName = "resizeNN";

            //TODO: improve this kernel
            size_t blkSizeX = 16, blkSizeY = 16;
            size_t glbSizeX;
            if(src.type() == CV_8UC1)
            {
                size_t cols = (dst.cols + dst.offset % 4 + 3) / 4;
362
                glbSizeX = cols % blkSizeX == 0 && cols != 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
363 364 365
            }
            else
            {
366
                glbSizeX = dst.cols % blkSizeX == 0 && dst.cols != 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
367
            }
368
            size_t glbSizeY = dst.rows % blkSizeY == 0 && dst.rows != 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
369 370 371
            size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
            size_t localThreads[3] = {blkSizeX, blkSizeY, 1};

372
            std::vector< std::pair<size_t, const void *> > args;
373 374
            if(interpolation == INTER_NEAREST)
            {
375 376 377 378 379 380 381 382 383 384
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dstoffset_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&srcoffset_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dstStep_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&srcStep_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
385 386
                if(src.clCxt -> impl -> double_support != 0)
                {
387 388
                    args.push_back( std::make_pair(sizeof(cl_double), (void *)&ifx_d));
                    args.push_back( std::make_pair(sizeof(cl_double), (void *)&ify_d));
389 390 391
                }
                else
                {
392 393
                    args.push_back( std::make_pair(sizeof(cl_float), (void *)&ifx));
                    args.push_back( std::make_pair(sizeof(cl_float), (void *)&ify));
394
                }
395 396 397
            }
            else
            {
398 399 400 401 402 403 404 405 406 407 408 409
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back( std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dstoffset_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&srcoffset_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dstStep_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&srcStep_in_pixel));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
                args.push_back( std::make_pair(sizeof(cl_float), (void *)&ifx));
                args.push_back( std::make_pair(sizeof(cl_float), (void *)&ify));
410 411
            }

412
            openCLExecuteKernel(clCxt, &imgproc_resize, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
413 414 415 416 417 418
        }


        void resize(const oclMat &src, oclMat &dst, Size dsize,
                    double fx, double fy, int interpolation)
        {
419 420
            CV_Assert(src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4
                      || src.type() == CV_32FC1 || src.type() == CV_32FC3 || src.type() == CV_32FC4);
421 422 423 424 425 426 427 428
            CV_Assert(interpolation == INTER_LINEAR || interpolation == INTER_NEAREST);
            CV_Assert( src.size().area() > 0 );
            CV_Assert( !(dsize == Size()) || (fx > 0 && fy > 0) );

            if(!(dsize == Size()) && (fx > 0 && fy > 0))
            {
                if(dsize.width != (int)(src.cols * fx) || dsize.height != (int)(src.rows * fy))
                {
429
                    CV_Error(CV_StsUnmatchedSizes, "invalid dsize and fx, fy!");
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
                }
            }
            if( dsize == Size() )
            {
                dsize = Size(saturate_cast<int>(src.cols * fx), saturate_cast<int>(src.rows * fy));
            }
            else
            {
                fx = (double)dsize.width / src.cols;
                fy = (double)dsize.height / src.rows;
            }

            dst.create(dsize, src.type());

            if( interpolation == INTER_NEAREST || interpolation == INTER_LINEAR )
            {
                resize_gpu( src, dst, fx, fy, interpolation);
                return;
            }
            CV_Error(CV_StsUnsupportedFormat, "Non-supported interpolation method");
        }


        ////////////////////////////////////////////////////////////////////////
        // medianFilter
        void medianFilter(const oclMat &src, oclMat &dst, int m)
        {
            CV_Assert( m % 2 == 1 && m > 1 );
            CV_Assert( m <= 5 || src.depth() == CV_8U );
            CV_Assert( src.cols <= dst.cols && src.rows <= dst.rows );

            if(src.data == dst.data)
            {
                oclMat src1;
                src.copyTo(src1);
                return medianFilter(src1, dst, m);
            }

468 469 470 471
            int srcStep = src.step1() / src.oclchannels();
            int dstStep = dst.step1() / dst.oclchannels();
            int srcOffset = src.offset / src.oclchannels() / src.elemSize1();
            int dstOffset = dst.offset / dst.oclchannels() / dst.elemSize1();
472 473

            Context *clCxt = src.clCxt;
474
            std::string kernelName = "medianFilter";
475 476


477 478 479 480 481 482 483 484 485
            std::vector< std::pair<size_t, const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcOffset));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstOffset));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcStep));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstStep));
486 487 488 489 490 491

            size_t globalThreads[3] = {(src.cols + 18) / 16 * 16, (src.rows + 15) / 16 * 16, 1};
            size_t localThreads[3] = {16, 16, 1};

            if(m == 3)
            {
492
                std::string kernelName = "medianFilter3";
493
                openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
494 495 496
            }
            else if(m == 5)
            {
497
                std::string kernelName = "medianFilter5";
498
                openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
499 500 501 502
            }
            else
            {
                CV_Error(CV_StsUnsupportedFormat, "Non-supported filter length");
503 504
                //std::string kernelName = "medianFilter";
                //args.push_back( std::make_pair( sizeof(cl_int),(void*)&m));
505

506
                //openCLExecuteKernel(clCxt,&imgproc_median,kernelName,globalThreads,localThreads,args,src.oclchannels(),-1);
507 508 509 510 511 512
            }

        }

        ////////////////////////////////////////////////////////////////////////
        // copyMakeBorder
niko's avatar
niko committed
513
        void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int bordertype, const Scalar &scalar)
514
        {
515
            //CV_Assert(src.oclchannels() != 2);
niko's avatar
niko committed
516
            CV_Assert(top >= 0 && bottom >= 0 && left >= 0 && right >= 0);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            if((dst.cols != dst.wholecols) || (dst.rows != dst.wholerows)) //has roi
            {
                if(((bordertype & cv::BORDER_ISOLATED) == 0) &&
                        (bordertype != cv::BORDER_CONSTANT) &&
                        (bordertype != cv::BORDER_REPLICATE))
                {
                    CV_Error(CV_StsBadArg, "unsupported border type");
                }
            }
            bordertype &= ~cv::BORDER_ISOLATED;
            if((bordertype == cv::BORDER_REFLECT) || (bordertype == cv::BORDER_WRAP))
            {
                CV_Assert((src.cols >= left) && (src.cols >= right) && (src.rows >= top) && (src.rows >= bottom));
            }
            if(bordertype == cv::BORDER_REFLECT_101)
            {
                CV_Assert((src.cols > left) && (src.cols > right) && (src.rows > top) && (src.rows > bottom));
            }
niko's avatar
niko committed
535
            dst.create(src.rows + top + bottom, src.cols + left + right, src.type());
536 537
            int srcStep = src.step1() / src.oclchannels();
            int dstStep = dst.step1() / dst.oclchannels();
niko's avatar
niko committed
538 539
            int srcOffset = src.offset / src.elemSize();
            int dstOffset = dst.offset / dst.elemSize();
540 541
            int __bordertype[] = {cv::BORDER_CONSTANT, cv::BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101};
            const char *borderstr[] = {"BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101"};
542
            size_t bordertype_index;
543 544 545 546 547 548 549 550 551
            for(bordertype_index = 0; bordertype_index < sizeof(__bordertype) / sizeof(int); bordertype_index++)
            {
                if(__bordertype[bordertype_index] == bordertype)
                    break;
            }
            if(bordertype_index == sizeof(__bordertype) / sizeof(int))
            {
                CV_Error(CV_StsBadArg, "unsupported border type");
            }
552
            std::string kernelName = "copymakeborder";
553 554 555 556 557
            size_t localThreads[3] = {16, 16, 1};
            size_t globalThreads[3] = {(dst.cols + localThreads[0] - 1) / localThreads[0] *localThreads[0],
                                       (dst.rows + localThreads[1] - 1) / localThreads[1] *localThreads[1], 1
                                      };

558 559 560 561 562 563 564 565 566 567 568 569 570
            std::vector< std::pair<size_t, const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcStep));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcOffset));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstStep));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstOffset));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&top));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&left));
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            char compile_option[64];
            union sc
            {
                cl_uchar4 uval;
                cl_char4  cval;
                cl_ushort4 usval;
                cl_short4 shval;
                cl_int4 ival;
                cl_float4 fval;
                cl_double4 dval;
            } val;
            switch(dst.depth())
            {
            case CV_8U:
                val.uval.s[0] = saturate_cast<uchar>(scalar.val[0]);
                val.uval.s[1] = saturate_cast<uchar>(scalar.val[1]);
                val.uval.s[2] = saturate_cast<uchar>(scalar.val[2]);
                val.uval.s[3] = saturate_cast<uchar>(scalar.val[3]);
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=uchar -D %s", borderstr[bordertype_index]);
593
                    args.push_back( std::make_pair( sizeof(cl_uchar) , (void *)&val.uval.s[0] ));
594 595 596 597 598 599 600 601
                    if(((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
                    {
                        kernelName = "copymakeborder_C1_D0";
                        globalThreads[0] = (dst.cols / 4 + localThreads[0] - 1) / localThreads[0] * localThreads[0];
                    }
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=uchar4 -D %s", borderstr[bordertype_index]);
602
                    args.push_back( std::make_pair( sizeof(cl_uchar4) , (void *)&val.uval ));
603 604 605 606 607 608 609 610 611 612 613 614 615 616
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_8S:
                val.cval.s[0] = saturate_cast<char>(scalar.val[0]);
                val.cval.s[1] = saturate_cast<char>(scalar.val[1]);
                val.cval.s[2] = saturate_cast<char>(scalar.val[2]);
                val.cval.s[3] = saturate_cast<char>(scalar.val[3]);
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=char -D %s", borderstr[bordertype_index]);
617
                    args.push_back( std::make_pair( sizeof(cl_char) , (void *)&val.cval.s[0] ));
618 619 620
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=char4 -D %s", borderstr[bordertype_index]);
621
                    args.push_back( std::make_pair( sizeof(cl_char4) , (void *)&val.cval ));
622 623 624 625 626 627 628 629 630 631 632 633 634 635
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_16U:
                val.usval.s[0] = saturate_cast<ushort>(scalar.val[0]);
                val.usval.s[1] = saturate_cast<ushort>(scalar.val[1]);
                val.usval.s[2] = saturate_cast<ushort>(scalar.val[2]);
                val.usval.s[3] = saturate_cast<ushort>(scalar.val[3]);
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=ushort -D %s", borderstr[bordertype_index]);
636
                    args.push_back( std::make_pair( sizeof(cl_ushort) , (void *)&val.usval.s[0] ));
637 638 639
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=ushort4 -D %s", borderstr[bordertype_index]);
640
                    args.push_back( std::make_pair( sizeof(cl_ushort4) , (void *)&val.usval ));
641 642 643 644 645 646 647 648 649 650 651 652 653 654
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_16S:
                val.shval.s[0] = saturate_cast<short>(scalar.val[0]);
                val.shval.s[1] = saturate_cast<short>(scalar.val[1]);
                val.shval.s[2] = saturate_cast<short>(scalar.val[2]);
                val.shval.s[3] = saturate_cast<short>(scalar.val[3]);
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=short -D %s", borderstr[bordertype_index]);
655
                    args.push_back( std::make_pair( sizeof(cl_short) , (void *)&val.shval.s[0] ));
656 657 658
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=short4 -D %s", borderstr[bordertype_index]);
659
                    args.push_back( std::make_pair( sizeof(cl_short4) , (void *)&val.shval ));
660 661 662 663 664 665 666 667 668 669 670 671 672 673
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_32S:
                val.ival.s[0] = saturate_cast<int>(scalar.val[0]);
                val.ival.s[1] = saturate_cast<int>(scalar.val[1]);
                val.ival.s[2] = saturate_cast<int>(scalar.val[2]);
                val.ival.s[3] = saturate_cast<int>(scalar.val[3]);
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=int -D %s", borderstr[bordertype_index]);
674
                    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&val.ival.s[0] ));
675 676 677 678 679 680
                    break;
                case 2:
                    sprintf(compile_option, "-D GENTYPE=int2 -D %s", borderstr[bordertype_index]);
                    cl_int2 i2val;
                    i2val.s[0] = val.ival.s[0];
                    i2val.s[1] = val.ival.s[1];
681
                    args.push_back( std::make_pair( sizeof(cl_int2) , (void *)&i2val ));
682 683 684
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=int4 -D %s", borderstr[bordertype_index]);
685
                    args.push_back( std::make_pair( sizeof(cl_int4) , (void *)&val.ival ));
686 687 688 689 690 691 692 693 694 695 696 697 698 699
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_32F:
                val.fval.s[0] = scalar.val[0];
                val.fval.s[1] = scalar.val[1];
                val.fval.s[2] = scalar.val[2];
                val.fval.s[3] = scalar.val[3];
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=float -D %s", borderstr[bordertype_index]);
700
                    args.push_back( std::make_pair( sizeof(cl_float) , (void *)&val.fval.s[0] ));
701 702 703
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=float4 -D %s", borderstr[bordertype_index]);
704
                    args.push_back( std::make_pair( sizeof(cl_float4) , (void *)&val.fval ));
705 706 707 708 709 710 711 712 713 714 715 716 717 718
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            case CV_64F:
                val.dval.s[0] = scalar.val[0];
                val.dval.s[1] = scalar.val[1];
                val.dval.s[2] = scalar.val[2];
                val.dval.s[3] = scalar.val[3];
                switch(dst.oclchannels())
                {
                case 1:
                    sprintf(compile_option, "-D GENTYPE=double -D %s", borderstr[bordertype_index]);
719
                    args.push_back( std::make_pair( sizeof(cl_double) , (void *)&val.dval.s[0] ));
720 721 722
                    break;
                case 4:
                    sprintf(compile_option, "-D GENTYPE=double4 -D %s", borderstr[bordertype_index]);
723
                    args.push_back( std::make_pair( sizeof(cl_double4) , (void *)&val.dval ));
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
                    break;
                default:
                    CV_Error(CV_StsUnsupportedFormat, "unsupported channels");
                }
                break;
            default:
                CV_Error(CV_StsUnsupportedFormat, "unknown depth");
            }

            openCLExecuteKernel(src.clCxt, &imgproc_copymakeboder, kernelName, globalThreads, localThreads, args, -1, -1, compile_option);
            //uchar* cputemp=new uchar[32*dst.wholerows];
            ////int* cpudata=new int[this->step*this->wholerows/sizeof(int)];
            //openCLSafeCall(clEnqueueReadBuffer(src.clCxt->impl->clCmdQueue, (cl_mem)dst.data, CL_TRUE,
            //						0, 32*dst.wholerows, cputemp, 0, NULL, NULL));
            //for(int i=0;i<dst.wholerows;i++)
            //{
            //	for(int j=0;j<dst.wholecols;j++)
            //	{
742
            //		std::cout<< (int)cputemp[i*32+j]<<" ";
743
            //	}
744
            //	std::cout<<std::endl;
745 746
            //}
            //delete []cputemp;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
        }

        ////////////////////////////////////////////////////////////////////////
        // warp

        namespace
        {
#define F double

            void convert_coeffs(F *M)
            {
                double D = M[0] * M[4] - M[1] * M[3];
                D = D != 0 ? 1. / D : 0;
                double A11 = M[4] * D, A22 = M[0] * D;
                M[0] = A11;
                M[1] *= -D;
                M[3] *= -D;
                M[4] = A22;
                double b1 = -M[0] * M[2] - M[1] * M[5];
                double b2 = -M[3] * M[2] - M[4] * M[5];
                M[2] = b1;
                M[5] = b2;
            }

            double invert(double *M)
            {
#define Sd(y,x) (Sd[y*3+x])
#define Dd(y,x) (Dd[y*3+x])
775 776 777
#define det3(m)    (m(0,0)*(m(1,1)*m(2,2) - m(1,2)*m(2,1)) -  \
                    m(0,1)*(m(1,0)*m(2,2) - m(1,2)*m(2,0)) +  \
                    m(0,2)*(m(1,0)*m(2,1) - m(1,1)*m(2,0)))
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
                double *Sd = M;
                double *Dd = M;
                double d = det3(Sd);
                double result = 0;
                if( d != 0)
                {
                    double t[9];
                    result = d;
                    d = 1. / d;

                    t[0] = (Sd(1, 1) * Sd(2, 2) - Sd(1, 2) * Sd(2, 1)) * d;
                    t[1] = (Sd(0, 2) * Sd(2, 1) - Sd(0, 1) * Sd(2, 2)) * d;
                    t[2] = (Sd(0, 1) * Sd(1, 2) - Sd(0, 2) * Sd(1, 1)) * d;

                    t[3] = (Sd(1, 2) * Sd(2, 0) - Sd(1, 0) * Sd(2, 2)) * d;
                    t[4] = (Sd(0, 0) * Sd(2, 2) - Sd(0, 2) * Sd(2, 0)) * d;
                    t[5] = (Sd(0, 2) * Sd(1, 0) - Sd(0, 0) * Sd(1, 2)) * d;

                    t[6] = (Sd(1, 0) * Sd(2, 1) - Sd(1, 1) * Sd(2, 0)) * d;
                    t[7] = (Sd(0, 1) * Sd(2, 0) - Sd(0, 0) * Sd(2, 1)) * d;
                    t[8] = (Sd(0, 0) * Sd(1, 1) - Sd(0, 1) * Sd(1, 0)) * d;

                    Dd(0, 0) = t[0];
                    Dd(0, 1) = t[1];
                    Dd(0, 2) = t[2];
                    Dd(1, 0) = t[3];
                    Dd(1, 1) = t[4];
                    Dd(1, 2) = t[5];
                    Dd(2, 0) = t[6];
                    Dd(2, 1) = t[7];
                    Dd(2, 2) = t[8];
                }
                return result;
            }

            void warpAffine_gpu(const oclMat &src, oclMat &dst, F coeffs[2][3], int interpolation)
            {
815
                CV_Assert( (src.oclchannels() == dst.oclchannels()) );
816 817
                int srcStep = src.step1();
                int dstStep = dst.step1();
818 819
                float float_coeffs[2][3];
                cl_mem coeffs_cm;
820 821

                Context *clCxt = src.clCxt;
822 823
                std::string s[3] = {"NN", "Linear", "Cubic"};
                std::string kernelName = "warpAffine" + s[interpolation];
824 825


826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
                if(src.clCxt -> impl -> double_support != 0)
                {
                    cl_int st;
                    coeffs_cm = clCreateBuffer( clCxt->impl->clContext, CL_MEM_READ_WRITE, sizeof(F) * 2 * 3, NULL, &st );
                    openCLVerifyCall(st);
                    openCLSafeCall(clEnqueueWriteBuffer(clCxt->impl->clCmdQueue, (cl_mem)coeffs_cm, 1, 0, sizeof(F) * 2 * 3, coeffs, 0, 0, 0));
                }
                else
                {
                    cl_int st;
                    for(int m = 0; m < 2; m++)
                        for(int n = 0; n < 3; n++)
                        {
                            float_coeffs[m][n] = coeffs[m][n];
                        }
                    coeffs_cm = clCreateBuffer( clCxt->impl->clContext, CL_MEM_READ_WRITE, sizeof(float) * 2 * 3, NULL, &st );
                    openCLSafeCall(clEnqueueWriteBuffer(clCxt->impl->clCmdQueue, (cl_mem)coeffs_cm, 1, 0, sizeof(float) * 2 * 3, float_coeffs, 0, 0, 0));

                }
845 846 847
                //TODO: improve this kernel
                size_t blkSizeX = 16, blkSizeY = 16;
                size_t glbSizeX;
niko's avatar
niko committed
848
                size_t cols;
849 850 851
                //if(src.type() == CV_8UC1 && interpolation != 2)
                if(src.type() == CV_8UC1 && interpolation != 2)
                {
niko's avatar
niko committed
852
                    cols = (dst.cols + dst.offset % 4 + 3) / 4;
853 854 855 856
                    glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
                }
                else
                {
niko's avatar
niko committed
857
                    cols = dst.cols;
858 859 860 861 862 863
                    glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
                }
                size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
                size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
                size_t localThreads[3] = {blkSizeX, blkSizeY, 1};

864 865 866 867 868 869 870 871 872 873 874 875 876 877
                std::vector< std::pair<size_t, const void *> > args;

                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&srcStep));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dstStep));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.offset));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.offset));
                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
878

879
                openCLExecuteKernel(clCxt, &imgproc_warpAffine, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
880 881 882 883 884 885
                openCLSafeCall(clReleaseMemObject(coeffs_cm));
            }


            void warpPerspective_gpu(const oclMat &src, oclMat &dst, double coeffs[3][3], int interpolation)
            {
886
                CV_Assert( (src.oclchannels() == dst.oclchannels()) );
887 888
                int srcStep = src.step1();
                int dstStep = dst.step1();
889 890
                float float_coeffs[3][3];
                cl_mem coeffs_cm;
891 892

                Context *clCxt = src.clCxt;
893 894
                std::string s[3] = {"NN", "Linear", "Cubic"};
                std::string kernelName = "warpPerspective" + s[interpolation];
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
                if(src.clCxt -> impl -> double_support != 0)
                {
                    cl_int st;
                    coeffs_cm = clCreateBuffer( clCxt->impl->clContext, CL_MEM_READ_WRITE, sizeof(double) * 3 * 3, NULL, &st );
                    openCLVerifyCall(st);
                    openCLSafeCall(clEnqueueWriteBuffer(clCxt->impl->clCmdQueue, (cl_mem)coeffs_cm, 1, 0, sizeof(double) * 3 * 3, coeffs, 0, 0, 0));
                }
                else
                {
                    cl_int st;
                    for(int m = 0; m < 3; m++)
                        for(int n = 0; n < 3; n++)
                            float_coeffs[m][n] = coeffs[m][n];

                    coeffs_cm = clCreateBuffer( clCxt->impl->clContext, CL_MEM_READ_WRITE, sizeof(float) * 3 * 3, NULL, &st );
                    openCLVerifyCall(st);
                    openCLSafeCall(clEnqueueWriteBuffer(clCxt->impl->clCmdQueue, (cl_mem)coeffs_cm, 1, 0, sizeof(float) * 3 * 3, float_coeffs, 0, 0, 0));
                }
914 915 916
                //TODO: improve this kernel
                size_t blkSizeX = 16, blkSizeY = 16;
                size_t glbSizeX;
niko's avatar
niko committed
917
                size_t cols;
918 919
                if(src.type() == CV_8UC1 && interpolation == 0)
                {
niko's avatar
niko committed
920
                    cols = (dst.cols + dst.offset % 4 + 3) / 4;
921 922 923 924 925 926
                    glbSizeX = cols % blkSizeX == 0 ? cols : (cols / blkSizeX + 1) * blkSizeX;
                }
                else
                    /*
                    */
                {
niko's avatar
niko committed
927
                    cols = dst.cols;
928 929 930 931 932 933
                    glbSizeX = dst.cols % blkSizeX == 0 ? dst.cols : (dst.cols / blkSizeX + 1) * blkSizeX;
                }
                size_t glbSizeY = dst.rows % blkSizeY == 0 ? dst.rows : (dst.rows / blkSizeY + 1) * blkSizeY;
                size_t globalThreads[3] = {glbSizeX, glbSizeY, 1};
                size_t localThreads[3] = {blkSizeX, blkSizeY, 1};

934 935 936 937 938 939 940 941 942 943 944 945 946 947
                std::vector< std::pair<size_t, const void *> > args;

                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&src.data));
                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&dst.data));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.cols));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.rows));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&srcStep));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dstStep));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.offset));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.offset));
                args.push_back(std::make_pair(sizeof(cl_mem), (void *)&coeffs_cm));
                args.push_back(std::make_pair(sizeof(cl_int), (void *)&cols));
948

949
                openCLExecuteKernel(clCxt, &imgproc_warpPerspective, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
950 951 952 953 954 955 956 957
                openCLSafeCall(clReleaseMemObject(coeffs_cm));
            }
        }

        void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
        {
            int interpolation = flags & INTER_MAX;

958
            CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
959 960 961 962 963 964 965 966
            CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);

            dst.create(dsize, src.type());

            CV_Assert(M.rows == 2 && M.cols == 3);

            int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
            F coeffs[2][3];
967 968 969

            double coeffsM[2*3];
            Mat coeffsMat(2, 3, CV_64F, (void *)coeffsM);
970 971 972
            M.convertTo(coeffsMat, coeffsMat.type());
            if(!warpInd)
            {
973
                convert_coeffs(coeffsM);
974
            }
975 976 977 978 979

            for(int i = 0; i < 2; ++i)
                for(int j = 0; j < 3; ++j)
                    coeffs[i][j] = coeffsM[i*3+j];

980 981 982 983 984 985 986
            warpAffine_gpu(src, dst, coeffs, interpolation);
        }

        void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags)
        {
            int interpolation = flags & INTER_MAX;

987
            CV_Assert((src.depth() == CV_8U  || src.depth() == CV_32F) && src.oclchannels() != 2 && src.oclchannels() != 3);
988 989 990 991 992 993 994 995 996
            CV_Assert(interpolation == INTER_NEAREST || interpolation == INTER_LINEAR || interpolation == INTER_CUBIC);

            dst.create(dsize, src.type());


            CV_Assert(M.rows == 3 && M.cols == 3);

            int warpInd = (flags & WARP_INVERSE_MAP) >> 4;
            double coeffs[3][3];
997 998 999

            double coeffsM[3*3];
            Mat coeffsMat(3, 3, CV_64F, (void *)coeffsM);
1000 1001 1002
            M.convertTo(coeffsMat, coeffsMat.type());
            if(!warpInd)
            {
1003
                invert(coeffsM);
1004 1005
            }

1006 1007 1008 1009
            for(int i = 0; i < 3; ++i)
                for(int j = 0; j < 3; ++j)
                    coeffs[i][j] = coeffsM[i*3+j];

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
            warpPerspective_gpu(src, dst, coeffs, interpolation);
        }


        ////////////////////////////////////////////////////////////////////////
        // integral

        void integral(const oclMat &src, oclMat &sum, oclMat &sqsum)
        {
            CV_Assert(src.type() == CV_8UC1);
1020
            if(src.clCxt->impl->double_support == 0 && src.depth() == CV_64F)
1021
            {
1022
                CV_Error(CV_GpuNotSupported, "select device don't support double");
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
            }
            int vlen = 4;
            int offset = src.offset / vlen;
            int pre_invalid = src.offset % vlen;
            int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;

            oclMat t_sum , t_sqsum;
            t_sum.create(src.cols, src.rows, CV_32SC1);
            t_sqsum.create(src.cols, src.rows, CV_32FC1);

            int w = src.cols + 1, h = src.rows + 1;
            sum.create(h, w, CV_32SC1);
            sqsum.create(h, w, CV_32FC1);
            int sum_offset = sum.offset / vlen, sqsum_offset = sqsum.offset / vlen;

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step));
1048 1049 1050
            size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
            openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_cols", gt, lt, args, -1, -1);
            args.clear();
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sqsum.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sum.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sqsum.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum.step));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sqsum.step));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum_offset));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sqsum_offset));
1062 1063
            size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
            openCLExecuteKernel(src.clCxt, &imgproc_integral, "integral_rows", gt2, lt2, args, -1, -1);
1064
            //std::cout << "tested" << std::endl;
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
        }
        void integral(const oclMat &src, oclMat &sum)
        {
            CV_Assert(src.type() == CV_8UC1);
            int vlen = 4;
            int offset = src.offset / vlen;
            int pre_invalid = src.offset % vlen;
            int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;

            oclMat t_sum;
            t_sum.create(src.cols, src.rows, CV_32SC1);

            int w = src.cols + 1, h = src.rows + 1;
            sum.create(h, w, CV_32SC1);
            int sum_offset = sum.offset / vlen;

1081 1082 1083 1084 1085 1086 1087 1088 1089
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&pre_invalid ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step));
1090
            size_t gt[3] = {((vcols + 1) / 2) * 256, 1, 1}, lt[3] = {256, 1, 1};
niko's avatar
niko committed
1091
            openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_cols", gt, lt, args, -1, -1);
1092
            args.clear();
1093 1094 1095 1096 1097 1098 1099
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&t_sum.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sum.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&t_sum.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum.step));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sum_offset));
1100
            size_t gt2[3] = {t_sum.cols  * 32, 1, 1}, lt2[3] = {256, 1, 1};
niko's avatar
niko committed
1101
            openCLExecuteKernel(src.clCxt, &imgproc_integral_sum, "integral_sum_rows", gt2, lt2, args, -1, -1);
1102
            //std::cout << "tested" << std::endl;
1103 1104 1105
        }

        /////////////////////// corner //////////////////////////////
1106
        static void extractCovData(const oclMat &src, oclMat &Dx, oclMat &Dy,
1107 1108 1109 1110 1111 1112 1113
                            int blockSize, int ksize, int borderType)
        {
            CV_Assert(src.type() == CV_8UC1 || src.type() == CV_32FC1);
            double scale = static_cast<double>(1 << ((ksize > 0 ? ksize : 3) - 1)) * blockSize;
            if (ksize < 0)
                scale *= 2.;

1114 1115
            if (src.depth() == CV_8U)
            {
1116 1117
                scale *= 255.;
                scale = 1. / scale;
1118 1119 1120
            }
            else
            {
1121 1122
                scale = 1. / scale;
            }
niko's avatar
niko committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
            if (ksize > 0)
            {
                Sobel(src, Dx, CV_32F, 1, 0, ksize, scale, 0, borderType);
                Sobel(src, Dy, CV_32F, 0, 1, ksize, scale, 0, borderType);
            }
            else
            {
                Scharr(src, Dx, CV_32F, 1, 0, scale, 0, borderType);
                Scharr(src, Dy, CV_32F, 0, 1, scale, 0, borderType);
            }
            CV_Assert(Dx.offset == 0 && Dy.offset == 0);
1134 1135
        }

1136
        static void corner_ocl(const char *src_str, std::string kernelName, int block_size, float k, oclMat &Dx, oclMat &Dy,
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
                        oclMat &dst, int border_type)
        {
            char borderType[30];
            switch (border_type)
            {
            case cv::BORDER_CONSTANT:
                sprintf(borderType, "BORDER_CONSTANT");
                break;
            case cv::BORDER_REFLECT101:
                sprintf(borderType, "BORDER_REFLECT101");
                break;
            case cv::BORDER_REFLECT:
                sprintf(borderType, "BORDER_REFLECT");
                break;
            case cv::BORDER_REPLICATE:
                sprintf(borderType, "BORDER_REPLICATE");
                break;
            default:
1155
                std::cout << "BORDER type is not supported!" << std::endl;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
            }
            char build_options[150];
            sprintf(build_options, "-D anX=%d -D anY=%d -D ksX=%d -D ksY=%d -D %s",
                    block_size / 2, block_size / 2, block_size, block_size, borderType);

            size_t blockSizeX = 256, blockSizeY = 1;
            size_t gSize = blockSizeX - block_size / 2 * 2;
            size_t globalSizeX = (Dx.cols) % gSize == 0 ? Dx.cols / gSize * blockSizeX : (Dx.cols / gSize + 1) * blockSizeX;
            size_t rows_per_thread = 2;
            size_t globalSizeY = ((Dx.rows + rows_per_thread - 1) / rows_per_thread) % blockSizeY == 0 ?
                                 ((Dx.rows + rows_per_thread - 1) / rows_per_thread) :
                                 (((Dx.rows + rows_per_thread - 1) / rows_per_thread) / blockSizeY + 1) * blockSizeY;

            size_t gt[3] = { globalSizeX, globalSizeY, 1 };
            size_t lt[3]  = { blockSizeX, blockSizeY, 1 };
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dx.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&Dy.data));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.wholerows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dx.wholecols ));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&Dx.step));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.wholerows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&Dy.wholecols ));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&Dy.step));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.offset));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.rows));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.cols));
            args.push_back( std::make_pair(sizeof(cl_int), (void *)&dst.step));
            args.push_back( std::make_pair( sizeof(cl_float) , (void *)&k));
1188 1189 1190 1191 1192 1193
            openCLExecuteKernel(dst.clCxt, &src_str, kernelName, gt, lt, args, -1, -1, build_options);
        }

        void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize,
                          double k, int borderType)
        {
1194
            if(src.clCxt->impl->double_support == 0 && src.depth() == CV_64F)
1195
            {
1196
                CV_Error(CV_GpuNotSupported, "select device don't support double");
1197
            }
1198
            CV_Assert(src.cols >= blockSize / 2 && src.rows >= blockSize / 2);
1199
            oclMat Dx, Dy;
niko's avatar
niko committed
1200
            CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
1201 1202 1203 1204 1205 1206 1207
            extractCovData(src, Dx, Dy, blockSize, ksize, borderType);
            dst.create(src.size(), CV_32F);
            corner_ocl(imgproc_calcHarris, "calcHarris", blockSize, static_cast<float>(k), Dx, Dy, dst, borderType);
        }

        void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int borderType)
        {
1208
            if(src.clCxt->impl->double_support == 0 && src.depth() == CV_64F)
1209
            {
1210
                CV_Error(CV_GpuNotSupported, "select device don't support double");
1211
            }
1212
            CV_Assert(src.cols >= blockSize / 2 && src.rows >= blockSize / 2);
1213
            oclMat Dx, Dy;
niko's avatar
niko committed
1214
            CV_Assert(borderType == cv::BORDER_CONSTANT || borderType == cv::BORDER_REFLECT101 || borderType == cv::BORDER_REPLICATE || borderType == cv::BORDER_REFLECT);
1215 1216 1217 1218 1219
            extractCovData(src, Dx, Dy, blockSize, ksize, borderType);
            dst.create(src.size(), CV_32F);
            corner_ocl(imgproc_calcMinEigenVal, "calcMinEigenVal", blockSize, 0, Dx, Dy, dst, borderType);
        }
        /////////////////////////////////// MeanShiftfiltering ///////////////////////////////////////////////
1220
        static void meanShiftFiltering_gpu(const oclMat &src, oclMat dst, int sp, int sr, int maxIter, float eps)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
        {
            CV_Assert( (src.cols == dst.cols) && (src.rows == dst.rows) );
            CV_Assert( !(dst.step & 0x3) );
            Context *clCxt = src.clCxt;

            //Arrange the NDRange
            int col = src.cols, row = src.rows;
            int ltx = 16, lty = 8;
            if(src.cols % ltx != 0)
                col = (col / ltx + 1) * ltx;
            if(src.rows % lty != 0)
                row = (row / lty + 1) * lty;

            size_t globalThreads[3] = {col, row, 1};
            size_t localThreads[3]  = {ltx, lty, 1};

            //set args
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.step ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sp ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sr ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&maxIter ));
            args.push_back( std::make_pair( sizeof(cl_float) , (void *)&eps ));
1251 1252 1253 1254 1255 1256 1257 1258
            openCLExecuteKernel(clCxt, &meanShift, "meanshift_kernel", globalThreads, localThreads, args, -1, -1);
        }

        void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr, TermCriteria criteria)
        {
            if( src.empty() )
                CV_Error( CV_StsBadArg, "The input image is empty" );

1259
            if( src.depth() != CV_8U || src.oclchannels() != 4 )
1260 1261
                CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );

Niko's avatar
Niko committed
1262 1263 1264 1265
            //            if(src.clCxt->impl->double_support == 0)
            //            {
            //                CV_Error( CV_GpuNotSupported, "Selected device doesn't support double, so a deviation exists.\nIf the accuracy is acceptable, the error can be ignored.\n");
            //            }
niko's avatar
niko committed
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
            dst.create( src.size(), CV_8UC4 );

            if( !(criteria.type & TermCriteria::MAX_ITER) )
                criteria.maxCount = 5;

            int maxIter = std::min(std::max(criteria.maxCount, 1), 100);

            float eps;
            if( !(criteria.type & TermCriteria::EPS) )
                eps = 1.f;
            eps = (float)std::max(criteria.epsilon, 0.0);

            meanShiftFiltering_gpu(src, dst, sp, sr, maxIter, eps);

        }

1283
        static void meanShiftProc_gpu(const oclMat &src, oclMat dstr, oclMat dstsp, int sp, int sr, int maxIter, float eps)
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
        {
            //sanity checks
            CV_Assert( (src.cols == dstr.cols) && (src.rows == dstr.rows) &&
                       (src.rows == dstsp.rows) && (src.cols == dstsp.cols));
            CV_Assert( !(dstsp.step & 0x3) );
            Context *clCxt = src.clCxt;

            //Arrange the NDRange
            int col = src.cols, row = src.rows;
            int ltx = 16, lty = 8;
            if(src.cols % ltx != 0)
                col = (col / ltx + 1) * ltx;
            if(src.rows % lty != 0)
                row = (row / lty + 1) * lty;

            size_t globalThreads[3] = {col, row, 1};
            size_t localThreads[3]  = {ltx, lty, 1};

            //set args
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dstr.data ));
            args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dstsp.data ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstsp.step ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstsp.offset ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.cols ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstr.rows ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sp ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sr ));
            args.push_back( std::make_pair( sizeof(cl_int) , (void *)&maxIter ));
            args.push_back( std::make_pair( sizeof(cl_float) , (void *)&eps ));
1319 1320 1321 1322 1323 1324 1325 1326
            openCLExecuteKernel(clCxt, &meanShift, "meanshiftproc_kernel", globalThreads, localThreads, args, -1, -1);
        }

        void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr, TermCriteria criteria)
        {
            if( src.empty() )
                CV_Error( CV_StsBadArg, "The input image is empty" );

1327
            if( src.depth() != CV_8U || src.oclchannels() != 4 )
1328 1329
                CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 4-channel images are supported" );

Niko's avatar
Niko committed
1330 1331 1332 1333
            //            if(src.clCxt->impl->double_support == 0)
            //            {
            //                CV_Error( CV_GpuNotSupported, "Selected device doesn't support double, so a deviation exists.\nIf the accuracy is acceptable, the error can be ignored.\n");
            //            }
niko's avatar
niko committed
1334

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
            dstr.create( src.size(), CV_8UC4 );
            dstsp.create( src.size(), CV_16SC2 );

            if( !(criteria.type & TermCriteria::MAX_ITER) )
                criteria.maxCount = 5;

            int maxIter = std::min(std::max(criteria.maxCount, 1), 100);

            float eps;
            if( !(criteria.type & TermCriteria::EPS) )
                eps = 1.f;
            eps = (float)std::max(criteria.epsilon, 0.0);

            meanShiftProc_gpu(src, dstr, dstsp, sp, sr, maxIter, eps);
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////hist///////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        namespace histograms
        {
            const int PARTIAL_HISTOGRAM256_COUNT = 256;
            const int HISTOGRAM256_BIN_COUNT = 256;
        }
        ///////////////////////////////calcHist/////////////////////////////////////////////////////////////////
1360
        static void calc_sub_hist(const oclMat &mat_src, const oclMat &mat_sub_hist)
1361 1362 1363 1364 1365 1366
        {
            using namespace histograms;

            Context  *clCxt = mat_src.clCxt;
            int depth = mat_src.depth();

1367
            std::string kernelName = "calc_sub_hist";
1368

niko's avatar
niko committed
1369
            size_t localThreads[3]  = { HISTOGRAM256_BIN_COUNT, 1, 1 };
1370 1371
            size_t globalThreads[3] = { PARTIAL_HISTOGRAM256_COUNT *localThreads[0], 1, 1};

niko's avatar
niko committed
1372 1373 1374 1375
            int dataWidth = 16;
            int dataWidth_bits = 4;
            int mask = dataWidth - 1;

1376
            int cols = mat_src.cols * mat_src.oclchannels();
1377 1378 1379
            int src_offset = mat_src.offset;
            int hist_step = mat_sub_hist.step >> 2;
            int left_col = 0, right_col = 0;
niko's avatar
niko committed
1380

1381
            if(cols >= dataWidth * 2 - 1)
niko's avatar
niko committed
1382
            {
1383 1384 1385 1386 1387 1388
                left_col = dataWidth - (src_offset & mask);
                left_col &= mask;
                src_offset += left_col;
                cols -= left_col;
                right_col = cols & mask;
                cols -= right_col;
niko's avatar
niko committed
1389 1390 1391
            }
            else
            {
1392 1393 1394 1395
                left_col = cols;
                right_col = 0;
                cols = 0;
                globalThreads[0] = 0;
niko's avatar
niko committed
1396
            }
1397

1398
            std::vector<std::pair<size_t , const void *> > args;
niko's avatar
niko committed
1399
            if(globalThreads[0] != 0)
1400
            {
1401 1402 1403 1404 1405 1406
                int tempcols = cols >> dataWidth_bits;
                int inc_x = globalThreads[0] % tempcols;
                int inc_y = globalThreads[0] / tempcols;
                src_offset >>= dataWidth_bits;
                int src_step = mat_src.step >> dataWidth_bits;
                int datacount = tempcols * mat_src.rows;
1407 1408 1409 1410 1411 1412 1413 1414 1415
                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src.data));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset));
                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&datacount));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&tempcols));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&inc_x));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&inc_y));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&hist_step));
1416
                openCLExecuteKernel(clCxt, &imgproc_histogram, kernelName, globalThreads, localThreads, args, -1, depth);
1417 1418 1419
            }
            if(left_col != 0 || right_col != 0)
            {
niko's avatar
niko committed
1420
                kernelName = "calc_sub_hist_border";
1421 1422 1423 1424 1425
                src_offset = mat_src.offset;
                localThreads[0] = 1;
                localThreads[1] = 256;
                globalThreads[0] = left_col + right_col;
                globalThreads[1] = (mat_src.rows + localThreads[1] - 1) / localThreads[1] * localThreads[1];
1426

1427
                args.clear();
1428 1429 1430 1431 1432 1433 1434 1435
                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src.data));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.step));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset));
                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_sub_hist.data));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&left_col));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.rows));
                args.push_back( std::make_pair( sizeof(cl_int), (void *)&hist_step));
1436 1437 1438
                openCLExecuteKernel(clCxt, &imgproc_histogram, kernelName, globalThreads, localThreads, args, -1, depth);
            }
        }
1439
        static void merge_sub_hist(const oclMat &sub_hist, oclMat &mat_hist)
1440 1441 1442 1443
        {
            using namespace histograms;

            Context  *clCxt = sub_hist.clCxt;
1444
            std::string kernelName = "merge_hist";
1445 1446 1447 1448

            size_t localThreads[3]  = { 256, 1, 1 };
            size_t globalThreads[3] = { HISTOGRAM256_BIN_COUNT *localThreads[0], 1, 1};
            int src_step = sub_hist.step >> 2;
1449 1450 1451 1452
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&sub_hist.data));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step));
1453 1454 1455 1456 1457 1458 1459 1460 1461
            openCLExecuteKernel(clCxt, &imgproc_histogram, kernelName, globalThreads, localThreads, args, -1, -1);
        }
        void calcHist(const oclMat &mat_src, oclMat &mat_hist)
        {
            using namespace histograms;
            CV_Assert(mat_src.type() == CV_8UC1);
            mat_hist.create(1, 256, CV_32SC1);

            oclMat buf(PARTIAL_HISTOGRAM256_COUNT, HISTOGRAM256_BIN_COUNT, CV_32SC1);
niko's avatar
niko committed
1462 1463
            buf.setTo(0);

1464 1465 1466 1467 1468 1469 1470 1471 1472
            calc_sub_hist(mat_src, buf);
            merge_sub_hist(buf, mat_hist);
        }
        ///////////////////////////////////equalizeHist/////////////////////////////////////////////////////
        void equalizeHist(const oclMat &mat_src, oclMat &mat_dst)
        {
            mat_dst.create(mat_src.rows, mat_src.cols, CV_8UC1);

            oclMat mat_hist(1, 256, CV_32SC1);
yao's avatar
yao committed
1473

1474 1475 1476
            calcHist(mat_src, mat_hist);

            Context *clCxt = mat_src.clCxt;
1477
            std::string kernelName = "calLUT";
1478 1479 1480
            size_t localThreads[3] = { 256, 1, 1};
            size_t globalThreads[3] = { 256, 1, 1};
            oclMat lut(1, 256, CV_8UC1);
1481
            std::vector<std::pair<size_t , const void *> > args;
yao's avatar
yao committed
1482
            int total = mat_src.rows * mat_src.cols;
1483 1484 1485
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_hist.data));
            args.push_back( std::make_pair( sizeof(int), (void *)&total));
1486 1487 1488 1489
            openCLExecuteKernel(clCxt, &imgproc_histogram, kernelName, globalThreads, localThreads, args, -1, -1);
            LUT(mat_src, lut, mat_dst);
        }
        //////////////////////////////////bilateralFilter////////////////////////////////////////////////////
1490 1491 1492 1493
        static void
        oclbilateralFilter_8u( const oclMat &src, oclMat &dst, int d,
                               double sigma_color, double sigma_space,
                               int borderType )
niko's avatar
niko committed
1494
        {
1495
            int cn = src.channels();
Niko's avatar
Niko committed
1496
            int i, j, maxk, radius;
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

            CV_Assert( (src.channels() == 1 || src.channels() == 3) &&
                       src.type() == dst.type() && src.size() == dst.size() &&
                       src.data != dst.data );

            if( sigma_color <= 0 )
                sigma_color = 1;
            if( sigma_space <= 0 )
                sigma_space = 1;

            double gauss_color_coeff = -0.5 / (sigma_color * sigma_color);
            double gauss_space_coeff = -0.5 / (sigma_space * sigma_space);

            if( d <= 0 )
                radius = cvRound(sigma_space * 1.5);
            else
                radius = d / 2;
            radius = MAX(radius, 1);
            d = radius * 2 + 1;

            oclMat temp;
            copyMakeBorder( src, temp, radius, radius, radius, radius, borderType );

1520 1521 1522
            std::vector<float> _color_weight(cn * 256);
            std::vector<float> _space_weight(d * d);
            std::vector<int> _space_ofs(d * d);
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
            float *color_weight = &_color_weight[0];
            float *space_weight = &_space_weight[0];
            int *space_ofs = &_space_ofs[0];
            int dst_step_in_pixel = dst.step / dst.elemSize();
            int dst_offset_in_pixel = dst.offset / dst.elemSize();
            int temp_step_in_pixel = temp.step / temp.elemSize();
            // initialize color-related bilateral filter coefficients
            for( i = 0; i < 256 * cn; i++ )
                color_weight[i] = (float)std::exp(i * i * gauss_color_coeff);

            // initialize space-related bilateral filter coefficients
            for( i = -radius, maxk = 0; i <= radius; i++ )
                for( j = -radius; j <= radius; j++ )
                {
                    double r = std::sqrt((double)i * i + (double)j * j);
                    if( r > radius )
                        continue;
                    space_weight[maxk] = (float)std::exp(r * r * gauss_space_coeff);
                    space_ofs[maxk++] = (int)(i * temp_step_in_pixel + j);
                }
            oclMat oclcolor_weight(1, cn * 256, CV_32FC1, color_weight);
            oclMat oclspace_weight(1, d * d, CV_32FC1, space_weight);
            oclMat oclspace_ofs(1, d * d, CV_32SC1, space_ofs);

1547
            std::string kernelName = "bilateral";
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
            size_t localThreads[3]  = { 16, 16, 1 };
            size_t globalThreads[3] = { (dst.cols + localThreads[0] - 1) / localThreads[0] *localThreads[0],
                                        (dst.rows + localThreads[1] - 1) / localThreads[1] *localThreads[1],
                                        1
                                      };
            if((dst.type() == CV_8UC1) && ((dst.offset & 3) == 0) && ((dst.cols & 3) == 0))
            {
                kernelName = "bilateral2";
                globalThreads[0] = (dst.cols / 4 + localThreads[0] - 1) / localThreads[0] * localThreads[0];
            }
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
            std::vector<std::pair<size_t , const void *> > args;
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&temp.data ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&maxk ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&radius ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step_in_pixel ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset_in_pixel ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp_step_in_pixel ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp.rows ));
            args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp.cols ));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclcolor_weight.data ));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclspace_weight.data ));
            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&oclspace_ofs.data ));
1573
            openCLExecuteKernel(src.clCxt, &imgproc_bilateral, kernelName, globalThreads, localThreads, args, dst.oclchannels(), dst.depth());
niko's avatar
niko committed
1574
        }
1575 1576 1577
        void bilateralFilter(const oclMat &src, oclMat &dst, int radius, double sigmaclr, double sigmaspc, int borderType)
        {

1578 1579 1580 1581 1582 1583
            dst.create( src.size(), src.type() );
            if( src.depth() == CV_8U )
                oclbilateralFilter_8u( src, dst, radius, sigmaclr, sigmaspc, borderType );
            else
                CV_Error( CV_StsUnsupportedFormat,
                          "Bilateral filtering is only implemented for 8uimages" );
1584 1585 1586 1587
        }

    }
}
niko's avatar
niko committed
1588 1589 1590 1591 1592
//////////////////////////////////convolve////////////////////////////////////////////////////
inline int divUp(int total, int grain)
{
    return (total + grain - 1) / grain;
}
1593
static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, std::string kernelName, const char **kernelString)
niko's avatar
niko committed
1594 1595 1596
{
    CV_Assert(src.depth() == CV_32FC1);
    CV_Assert(temp1.depth() == CV_32F);
1597
    CV_Assert(temp1.cols <= 17 && temp1.rows <= 17);
niko's avatar
niko committed
1598

1599
    dst.create(src.size(), src.type());
niko's avatar
niko committed
1600 1601 1602 1603 1604

    CV_Assert(src.cols == dst.cols && src.rows == dst.rows);
    CV_Assert(src.type() == dst.type());

    Context  *clCxt = src.clCxt;
1605
    int channels = dst.oclchannels();
niko's avatar
niko committed
1606 1607
    int depth = dst.depth();

1608 1609
    size_t vector_length = 1;
    int offset_cols = ((dst.offset % dst.step) / dst.elemSize1()) & (vector_length - 1);
niko's avatar
niko committed
1610 1611 1612 1613
    int cols = divUp(dst.cols * channels + offset_cols, vector_length);
    int rows = dst.rows;

    size_t localThreads[3]  = { 16, 16, 1 };
1614 1615 1616 1617
    size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
                                divUp(rows, localThreads[1]) *localThreads[1],
                                1
                              };
niko's avatar
niko committed
1618

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    std::vector<std::pair<size_t , const void *> > args;
    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&temp1.data ));
    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.step ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.rows ));
    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.cols ));
niko's avatar
niko committed
1630 1631 1632

    openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
}
1633
void cv::ocl::convolve(const oclMat &x, const oclMat &t, oclMat &y)
niko's avatar
niko committed
1634 1635 1636 1637
{
    CV_Assert(x.depth() == CV_32F);
    CV_Assert(t.depth() == CV_32F);
    CV_Assert(x.type() == y.type() && x.size() == y.size());
1638
    y.create(x.size(), x.type());
1639
    std::string kernelName = "convolve";
1640

niko's avatar
niko committed
1641 1642
    convolve_run(x, t, y, kernelName, &imgproc_convolve);
}