canny.cpp 9.75 KB
Newer Older
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
/*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.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel 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 Intel Corporation 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"

44 45 46
void cv::Canny( InputArray _src, OutputArray _dst,
                double low_thresh, double high_thresh,
                int aperture_size, bool L2gradient )
47
{
48 49
    Mat src = _src.getMat();
    CV_Assert( src.depth() == CV_8U );
50

51 52
    _dst.create(src.size(), CV_8U);
    Mat dst = _dst.getMat();
Andrey Kamaev's avatar
Andrey Kamaev committed
53 54 55 56 57 58 59 60 61 62 63

    if (!L2gradient && (aperture_size & CV_CANNY_L2_GRADIENT) == CV_CANNY_L2_GRADIENT)
    {
        //backward compatibility
        aperture_size &= ~CV_CANNY_L2_GRADIENT;
        L2gradient = true;
    }

    if ((aperture_size & 1) == 0 || (aperture_size != -1 && (aperture_size < 3 || aperture_size > 7)))
        CV_Error(CV_StsBadFlag, "");

Andrey Kamaev's avatar
Andrey Kamaev committed
64
#ifdef HAVE_TEGRA_OPTIMIZATION
65
    if (tegra::canny(src, dst, low_thresh, high_thresh, aperture_size, L2gradient))
Andrey Kamaev's avatar
Andrey Kamaev committed
66 67
        return;
#endif
68

Andrey Kamaev's avatar
Andrey Kamaev committed
69 70 71
    const int cn = src.channels();
    cv::Mat dx(src.rows, src.cols, CV_16SC(cn));
    cv::Mat dy(src.rows, src.cols, CV_16SC(cn));
72

Andrey Kamaev's avatar
Andrey Kamaev committed
73 74
    cv::Sobel(src, dx, CV_16S, 1, 0, aperture_size, 1, 0, cv::BORDER_REPLICATE);
    cv::Sobel(src, dy, CV_16S, 0, 1, aperture_size, 1, 0, cv::BORDER_REPLICATE);
75

Andrey Kamaev's avatar
Andrey Kamaev committed
76 77
    if (low_thresh > high_thresh)
        std::swap(low_thresh, high_thresh);
78

Andrey Kamaev's avatar
Andrey Kamaev committed
79
    if (L2gradient)
80
    {
Andrey Kamaev's avatar
Andrey Kamaev committed
81 82
        low_thresh = std::min(32767.0, low_thresh);
        high_thresh = std::min(32767.0, high_thresh);
83

Andrey Kamaev's avatar
Andrey Kamaev committed
84 85
        if (low_thresh > 0) low_thresh *= low_thresh;
        if (high_thresh > 0) high_thresh *= high_thresh;
86
    }
Andrey Kamaev's avatar
Andrey Kamaev committed
87 88
    int low = cvFloor(low_thresh);
    int high = cvFloor(high_thresh);
89

Andrey Kamaev's avatar
Andrey Kamaev committed
90 91
    ptrdiff_t mapstep = src.cols + 2;
    cv::AutoBuffer<uchar> buffer((src.cols+2)*(src.rows+2) + cn * mapstep * 3 * sizeof(int));
92

Andrey Kamaev's avatar
Andrey Kamaev committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106
    int* mag_buf[3];
    mag_buf[0] = (int*)(uchar*)buffer;
    mag_buf[1] = mag_buf[0] + mapstep*cn;
    mag_buf[2] = mag_buf[1] + mapstep*cn;
    memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));

    uchar* map = (uchar*)(mag_buf[2] + mapstep*cn);
    memset(map, 1, mapstep);
    memset(map + mapstep*(src.rows + 1), 1, mapstep);

    int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
    std::vector<uchar*> stack(maxsize);
    uchar **stack_top = &stack[0];
    uchar **stack_bottom = &stack[0];
107

Andrey Kamaev's avatar
Andrey Kamaev committed
108
    /* sector numbers
109 110 111
       (Top-Left Origin)

        1   2   3
Andrey Kamaev's avatar
Andrey Kamaev committed
112 113
         *  *  *
          * * *
114
        0*******0
Andrey Kamaev's avatar
Andrey Kamaev committed
115 116
          * * *
         *  *  *
117 118 119
        3   2   1
    */

Andrey Kamaev's avatar
Andrey Kamaev committed
120
    #define CANNY_PUSH(d)    *(d) = uchar(2), *stack_top++ = (d)
121 122 123 124 125 126 127
    #define CANNY_POP(d)     (d) = *--stack_top

    // calculate magnitude and angle of gradient, perform non-maxima supression.
    // fill the map with one of the following values:
    //   0 - the pixel might belong to an edge
    //   1 - the pixel can not belong to an edge
    //   2 - the pixel does belong to an edge
Andrey Kamaev's avatar
Andrey Kamaev committed
128
    for (int i = 0; i <= src.rows; i++)
129
    {
Andrey Kamaev's avatar
Andrey Kamaev committed
130 131
        int* _norm = mag_buf[(i > 0) + 1] + 1;
        if (i < src.rows)
132
        {
Andrey Kamaev's avatar
Andrey Kamaev committed
133 134 135 136
            short* _dx = dx.ptr<short>(i);
            short* _dy = dy.ptr<short>(i);

            if (!L2gradient)
137
            {
Andrey Kamaev's avatar
Andrey Kamaev committed
138 139
                for (int j = 0; j < src.cols*cn; j++)
                    _norm[j] = std::abs(int(_dx[j])) + std::abs(int(_dy[j]));
140 141 142
            }
            else
            {
Andrey Kamaev's avatar
Andrey Kamaev committed
143 144
                for (int j = 0; j < src.cols*cn; j++)
                    _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];
145
            }
146

Andrey Kamaev's avatar
Andrey Kamaev committed
147
            if (cn > 1)
148
            {
Andrey Kamaev's avatar
Andrey Kamaev committed
149
                for(int j = 0, jn = 0; j < src.cols; ++j, jn += cn)
150
                {
Andrey Kamaev's avatar
Andrey Kamaev committed
151 152 153 154 155 156
                    int maxIdx = jn;
                    for(int k = 1; k < cn; ++k)
                        if(_norm[jn + k] > _norm[maxIdx]) maxIdx = jn + k;
                    _norm[j] = _norm[maxIdx];
                    _dx[j] = _dx[maxIdx];
                    _dy[j] = _dy[maxIdx];
157 158
                }
            }
Andrey Kamaev's avatar
Andrey Kamaev committed
159
            _norm[-1] = _norm[src.cols] = 0;
160 161
        }
        else
Andrey Kamaev's avatar
Andrey Kamaev committed
162
            memset(_norm-1, 0, /* cn* */mapstep*sizeof(int));
163

164 165
        // at the very beginning we do not have a complete ring
        // buffer of 3 magnitude rows for non-maxima suppression
Andrey Kamaev's avatar
Andrey Kamaev committed
166
        if (i == 0)
167 168
            continue;

Andrey Kamaev's avatar
Andrey Kamaev committed
169 170 171 172 173 174 175 176 177 178 179
        uchar* _map = map + mapstep*i + 1;
        _map[-1] = _map[src.cols] = 1;

        int* _mag = mag_buf[1] + 1; // take the central row
        ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
        ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];

        const short* _x = dx.ptr<short>(i-1);
        const short* _y = dy.ptr<short>(i-1);

        if ((stack_top - stack_bottom) + src.cols > maxsize)
180 181
        {
            int sz = (int)(stack_top - stack_bottom);
Andrey Kamaev's avatar
Andrey Kamaev committed
182
            maxsize = maxsize * 3/2;
183 184 185 186 187
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

Andrey Kamaev's avatar
Andrey Kamaev committed
188 189
        int prev_flag = 0;
        for (int j = 0; j < src.cols; j++)
190 191
        {
            #define CANNY_SHIFT 15
Andrey Kamaev's avatar
Andrey Kamaev committed
192
            const int TG22 = (int)(0.4142135623730950488016887242097*(1<<CANNY_SHIFT) + 0.5);
193 194 195

            int m = _mag[j];

Andrey Kamaev's avatar
Andrey Kamaev committed
196
            if (m > low)
197
            {
Andrey Kamaev's avatar
Andrey Kamaev committed
198 199 200 201
                int xs = _x[j];
                int ys = _y[j];
                int x = std::abs(xs);
                int y = std::abs(ys) << CANNY_SHIFT;
202

Andrey Kamaev's avatar
Andrey Kamaev committed
203
                int tg22x = x * TG22;
204

Andrey Kamaev's avatar
Andrey Kamaev committed
205
                if (y < tg22x)
206
                {
Andrey Kamaev's avatar
Andrey Kamaev committed
207
                    if (m > _mag[j-1] && m >= _mag[j+1]) goto __ocv_canny_push;
208
                }
Andrey Kamaev's avatar
Andrey Kamaev committed
209
                else
210
                {
Andrey Kamaev's avatar
Andrey Kamaev committed
211 212
                    int tg67x = tg22x + (x << (CANNY_SHIFT+1));
                    if (y > tg67x)
213
                    {
Andrey Kamaev's avatar
Andrey Kamaev committed
214
                        if (m > _mag[j+magstep2] && m >= _mag[j+magstep1]) goto __ocv_canny_push;
215
                    }
Andrey Kamaev's avatar
Andrey Kamaev committed
216
                    else
217
                    {
Andrey Kamaev's avatar
Andrey Kamaev committed
218 219
                        int s = (xs ^ ys) < 0 ? -1 : 1;
                        if (m > _mag[j+magstep2-s] && m > _mag[j+magstep1+s]) goto __ocv_canny_push;
220 221 222 223
                    }
                }
            }
            prev_flag = 0;
Andrey Kamaev's avatar
Andrey Kamaev committed
224 225 226 227 228 229 230 231 232 233
            _map[j] = uchar(1);
            continue;
__ocv_canny_push:
            if (!prev_flag && m > high && _map[j-mapstep] != 2)
            {
                CANNY_PUSH(_map + j);
                prev_flag = 1;
            }
            else
                _map[j] = 0;
234 235
        }

Andrey Kamaev's avatar
Andrey Kamaev committed
236
        // scroll the ring buffer
237 238 239 240 241 242 243
        _mag = mag_buf[0];
        mag_buf[0] = mag_buf[1];
        mag_buf[1] = mag_buf[2];
        mag_buf[2] = _mag;
    }

    // now track the edges (hysteresis thresholding)
Andrey Kamaev's avatar
Andrey Kamaev committed
244
    while (stack_top > stack_bottom)
245 246
    {
        uchar* m;
Andrey Kamaev's avatar
Andrey Kamaev committed
247
        if ((stack_top - stack_bottom) + 8 > maxsize)
248 249
        {
            int sz = (int)(stack_top - stack_bottom);
Andrey Kamaev's avatar
Andrey Kamaev committed
250
            maxsize = maxsize * 3/2;
251 252 253 254 255 256
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        CANNY_POP(m);
Andrey Kamaev's avatar
Andrey Kamaev committed
257 258 259 260 261 262 263 264 265

        if (!m[-1])         CANNY_PUSH(m - 1);
        if (!m[1])          CANNY_PUSH(m + 1);
        if (!m[-mapstep-1]) CANNY_PUSH(m - mapstep - 1);
        if (!m[-mapstep])   CANNY_PUSH(m - mapstep);
        if (!m[-mapstep+1]) CANNY_PUSH(m - mapstep + 1);
        if (!m[mapstep-1])  CANNY_PUSH(m + mapstep - 1);
        if (!m[mapstep])    CANNY_PUSH(m + mapstep);
        if (!m[mapstep+1])  CANNY_PUSH(m + mapstep + 1);
266 267 268
    }

    // the final pass, form the final image
Andrey Kamaev's avatar
Andrey Kamaev committed
269 270 271
    const uchar* pmap = map + mapstep + 1;
    uchar* pdst = dst.ptr();
    for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
272
    {
Andrey Kamaev's avatar
Andrey Kamaev committed
273 274
        for (int j = 0; j < src.cols; j++)
            pdst[j] = (uchar)-(pmap[j] >> 1);
275 276 277
    }
}

278 279
void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
              double threshold2, int aperture_size )
280
{
281 282
    cv::Mat src = cv::cvarrToMat(image), dst = cv::cvarrToMat(edges);
    CV_Assert( src.size == dst.size && src.depth() == CV_8U && dst.type() == CV_8U );
283

284 285
    cv::Canny(src, dst, threshold1, threshold2, aperture_size & 255,
              (aperture_size & CV_CANNY_L2_GRADIENT) != 0);
286 287 288
}

/* End of file. */