clahe.cpp 10.3 KB
Newer Older
wester committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/*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) 2013, NVIDIA Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holders 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"

// ----------------------------------------------------------------------
// CLAHE

namespace
{
    class CLAHE_CalcLut_Body : public cv::ParallelLoopBody
    {
    public:
wester committed
52
        CLAHE_CalcLut_Body(const cv::Mat& src, cv::Mat& lut, cv::Size tileSize, int tilesX, int clipLimit, float lutScale) :
wester committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            src_(src), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), clipLimit_(clipLimit), lutScale_(lutScale)
        {
        }

        void operator ()(const cv::Range& range) const;

    private:
        cv::Mat src_;
        mutable cv::Mat lut_;

        cv::Size tileSize_;
        int tilesX_;
        int clipLimit_;
        float lutScale_;
    };

wester committed
69
    void CLAHE_CalcLut_Body::operator ()(const cv::Range& range) const
wester committed
70
    {
wester committed
71 72 73 74
        const int histSize = 256;

        uchar* tileLut = lut_.ptr(range.start);
        const size_t lut_step = lut_.step;
wester committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

        for (int k = range.start; k < range.end; ++k, tileLut += lut_step)
        {
            const int ty = k / tilesX_;
            const int tx = k % tilesX_;

            // retrieve tile submatrix

            cv::Rect tileROI;
            tileROI.x = tx * tileSize_.width;
            tileROI.y = ty * tileSize_.height;
            tileROI.width = tileSize_.width;
            tileROI.height = tileSize_.height;

            const cv::Mat tile = src_(tileROI);

            // calc histogram

            int tileHist[histSize] = {0, };

            int height = tileROI.height;
wester committed
96 97
            const size_t sstep = tile.step;
            for (const uchar* ptr = tile.ptr<uchar>(0); height--; ptr += sstep)
wester committed
98 99 100 101 102
            {
                int x = 0;
                for (; x <= tileROI.width - 4; x += 4)
                {
                    int t0 = ptr[x], t1 = ptr[x+1];
wester committed
103
                    tileHist[t0]++; tileHist[t1]++;
wester committed
104
                    t0 = ptr[x+2]; t1 = ptr[x+3];
wester committed
105
                    tileHist[t0]++; tileHist[t1]++;
wester committed
106 107 108
                }

                for (; x < tileROI.width; ++x)
wester committed
109
                    tileHist[ptr[x]]++;
wester committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
            }

            // clip histogram

            if (clipLimit_ > 0)
            {
                // how many pixels were clipped
                int clipped = 0;
                for (int i = 0; i < histSize; ++i)
                {
                    if (tileHist[i] > clipLimit_)
                    {
                        clipped += tileHist[i] - clipLimit_;
                        tileHist[i] = clipLimit_;
                    }
                }

                // redistribute clipped pixels
                int redistBatch = clipped / histSize;
                int residual = clipped - redistBatch * histSize;

                for (int i = 0; i < histSize; ++i)
                    tileHist[i] += redistBatch;

a  
Kai Westerkamp committed
134 135
                for (int i = 0; i < residual; ++i)
                    tileHist[i]++;
wester committed
136 137 138 139 140 141 142 143
            }

            // calc Lut

            int sum = 0;
            for (int i = 0; i < histSize; ++i)
            {
                sum += tileHist[i];
wester committed
144
                tileLut[i] = cv::saturate_cast<uchar>(sum * lutScale_);
wester committed
145 146 147 148 149 150 151
            }
        }
    }

    class CLAHE_Interpolation_Body : public cv::ParallelLoopBody
    {
    public:
wester committed
152
        CLAHE_Interpolation_Body(const cv::Mat& src, cv::Mat& dst, const cv::Mat& lut, cv::Size tileSize, int tilesX, int tilesY) :
wester committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
            src_(src), dst_(dst), lut_(lut), tileSize_(tileSize), tilesX_(tilesX), tilesY_(tilesY)
        {
        }

        void operator ()(const cv::Range& range) const;

    private:
        cv::Mat src_;
        mutable cv::Mat dst_;
        cv::Mat lut_;

        cv::Size tileSize_;
        int tilesX_;
        int tilesY_;
    };

wester committed
169
    void CLAHE_Interpolation_Body::operator ()(const cv::Range& range) const
wester committed
170
    {
wester committed
171
        const size_t lut_step = lut_.step;
wester committed
172 173 174

        for (int y = range.start; y < range.end; ++y)
        {
wester committed
175 176
            const uchar* srcRow = src_.ptr<uchar>(y);
            uchar* dstRow = dst_.ptr<uchar>(y);
wester committed
177

wester committed
178
            const float tyf = (static_cast<float>(y) / tileSize_.height) - 0.5f;
wester committed
179 180 181 182

            int ty1 = cvFloor(tyf);
            int ty2 = ty1 + 1;

wester committed
183
            const float ya = tyf - ty1;
wester committed
184 185 186 187

            ty1 = std::max(ty1, 0);
            ty2 = std::min(ty2, tilesY_ - 1);

wester committed
188 189
            const uchar* lutPlane1 = lut_.ptr(ty1 * tilesX_);
            const uchar* lutPlane2 = lut_.ptr(ty2 * tilesX_);
wester committed
190 191 192

            for (int x = 0; x < src_.cols; ++x)
            {
wester committed
193 194 195 196 197 198 199 200 201
                const float txf = (static_cast<float>(x) / tileSize_.width) - 0.5f;

                int tx1 = cvFloor(txf);
                int tx2 = tx1 + 1;

                const float xa = txf - tx1;

                tx1 = std::max(tx1, 0);
                tx2 = std::min(tx2, tilesX_ - 1);
wester committed
202

wester committed
203
                const int srcVal = srcRow[x];
wester committed
204

wester committed
205 206
                const size_t ind1 = tx1 * lut_step + srcVal;
                const size_t ind2 = tx2 * lut_step + srcVal;
wester committed
207

wester committed
208 209 210 211 212 213 214 215
                float res = 0;

                res += lutPlane1[ind1] * ((1.0f - xa) * (1.0f - ya));
                res += lutPlane1[ind2] * ((xa) * (1.0f - ya));
                res += lutPlane2[ind1] * ((1.0f - xa) * (ya));
                res += lutPlane2[ind2] * ((xa) * (ya));

                dstRow[x] = cv::saturate_cast<uchar>(res);
wester committed
216 217 218 219 220 221 222 223 224
            }
        }
    }

    class CLAHE_Impl : public cv::CLAHE
    {
    public:
        CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);

wester committed
225 226
        cv::AlgorithmInfo* info() const;

wester committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        void apply(cv::InputArray src, cv::OutputArray dst);

        void setClipLimit(double clipLimit);
        double getClipLimit() const;

        void setTilesGridSize(cv::Size tileGridSize);
        cv::Size getTilesGridSize() const;

        void collectGarbage();

    private:
        double clipLimit_;
        int tilesX_;
        int tilesY_;

        cv::Mat srcExt_;
        cv::Mat lut_;
    };

    CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
        clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
    {
    }

wester committed
251 252 253 254 255
    CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE",
        obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
        obj.info()->addParam(obj, "tilesX", obj.tilesX_);
        obj.info()->addParam(obj, "tilesY", obj.tilesY_))

wester committed
256 257
    void CLAHE_Impl::apply(cv::InputArray _src, cv::OutputArray _dst)
    {
wester committed
258 259 260 261 262 263
        cv::Mat src = _src.getMat();

        CV_Assert( src.type() == CV_8UC1 );

        _dst.create( src.size(), src.type() );
        cv::Mat dst = _dst.getMat();
wester committed
264

wester committed
265
        const int histSize = 256;
wester committed
266

wester committed
267
        lut_.create(tilesX_ * tilesY_, histSize, CV_8UC1);
wester committed
268 269

        cv::Size tileSize;
wester committed
270
        cv::Mat srcForLut;
wester committed
271

wester committed
272
        if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
wester committed
273
        {
wester committed
274 275
            tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
            srcForLut = src;
wester committed
276 277 278
        }
        else
        {
wester committed
279 280 281 282
            cv::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0, tilesX_ - (src.cols % tilesX_), cv::BORDER_REFLECT_101);

            tileSize = cv::Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
            srcForLut = srcExt_;
wester committed
283 284 285 286 287 288 289 290 291 292 293 294
        }

        const int tileSizeTotal = tileSize.area();
        const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;

        int clipLimit = 0;
        if (clipLimit_ > 0.0)
        {
            clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
            clipLimit = std::max(clipLimit, 1);
        }

wester committed
295 296
        CLAHE_CalcLut_Body calcLutBody(srcForLut, lut_, tileSize, tilesX_, clipLimit, lutScale);
        cv::parallel_for_(cv::Range(0, tilesX_ * tilesY_), calcLutBody);
wester committed
297

wester committed
298 299
        CLAHE_Interpolation_Body interpolationBody(src, dst, lut_, tileSize, tilesX_, tilesY_);
        cv::parallel_for_(cv::Range(0, src.rows), interpolationBody);
wester committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    }

    void CLAHE_Impl::setClipLimit(double clipLimit)
    {
        clipLimit_ = clipLimit;
    }

    double CLAHE_Impl::getClipLimit() const
    {
        return clipLimit_;
    }

    void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
    {
        tilesX_ = tileGridSize.width;
        tilesY_ = tileGridSize.height;
    }

    cv::Size CLAHE_Impl::getTilesGridSize() const
    {
        return cv::Size(tilesX_, tilesY_);
    }

    void CLAHE_Impl::collectGarbage()
    {
        srcExt_.release();
        lut_.release();
    }
}

cv::Ptr<cv::CLAHE> cv::createCLAHE(double clipLimit, cv::Size tileGridSize)
{
wester committed
332
    return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
wester committed
333
}