slic.cpp 56.8 KB
Newer Older
1 2 3
/*********************************************************************
 * Software License Agreement (BSD License)
 *
4
 * SLIC, SLICO Copyright (c) 2013
5 6 7 8
 * Radhakrishna Achanta
 * email : Radhakrishna [dot] Achanta [at] epfl [dot] ch
 * web : http://ivrl.epfl.ch/people/achanta
 *
9
 * MSLIC Copyright (c) 2016, 2017
10 11
 * Yong-Jin Liu
 * email : liuyongjin [at] tsinghua [dot] edu [dot] cn
12
 * web : http://47.89.51.189/liuyj
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
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions 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.
 *   * Neither the name of the copyright holders nor the names of its
 *     contributors may 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 OWNER 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.
 *********************************************************************/

/*
 "SLIC Superpixels Compared to State-of-the-art Superpixel Methods"
 Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi, Pascal Fua,
 and Sabine Susstrunk, IEEE TPAMI, Volume 34, Issue 11, Pages 2274-2282,
 November 2012.

 "SLIC Superpixels" Radhakrishna Achanta, Appu Shaji, Kevin Smith,
 Aurelien Lucchi, Pascal Fua, and Sabine Süsstrunk, EPFL Technical
 Report no. 149300, June 2010.

52 53
 "Intrinsic Manifold SLIC: A Simple and Efficient Method for Computing
 Content-Sensitive Superpixels"
54
 Yong-Jin Liu, Cheng-Chi Yu, Min-Jing Yu, Ying He,
55 56
 IEEE Transactions on Pattern Analysis and Machine Intelligence,
 March 2017, Issue 99.
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
 OpenCV port by: Cristian Balint <cristian dot balint at gmail dot com>
 */

#include "precomp.hpp"

using namespace std;


namespace cv {
namespace ximgproc {

class SuperpixelSLICImpl : public SuperpixelSLIC
{
public:

    SuperpixelSLICImpl( InputArray image, int algorithm, int region_size, float ruler );

75
    virtual ~SuperpixelSLICImpl() CV_OVERRIDE;
76 77

    // perform amount of iteration
78
    virtual void iterate( int num_iterations = 10 ) CV_OVERRIDE;
79 80

    // get amount of superpixels
81
    virtual int getNumberOfSuperpixels() const CV_OVERRIDE;
82 83

    // get image with labels
84
    virtual void getLabels( OutputArray labels_out ) const CV_OVERRIDE;
85 86

    // get mask image with contour
87
    virtual void getLabelContourMask( OutputArray image, bool thick_line = true ) const CV_OVERRIDE;
88 89

    // enforce connectivity over labels
90
    virtual void enforceLabelConnectivity( int min_element_size = 25 ) CV_OVERRIDE;
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112


protected:

    // image width
    int m_width;

    // image width
    int m_height;

    // image channels
    int m_nr_channels;

    // algorithm
    int m_algorithm;

    // region size
    int m_region_size;

    // compactness
    float m_ruler;

113 114 115 116 117 118 119 120 121 122 123 124 125
    // ratio (MSLIC)
    float m_ratio;

    // split (MSLIC)
    float m_split;

    // current iter
    int m_cur_iter;

    // current iter
    int m_iterations;


126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
private:

    // labels no
    int m_numlabels;

    // stacked channels
    // of original image
    vector<Mat> m_chvec;

    // seeds on x
    vector<float> m_kseedsx;

    // seeds on y
    vector<float> m_kseedsy;

    // labels storage
    Mat m_klabels;

    // seeds storage
    vector< vector<float> > m_kseeds;

147 148 149 150 151 152
    // adaptive k (MSLIC)
    vector<float> m_adaptk;

    // merge threshold (MSLIC)
    float m_merge;

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    // initialization
    inline void initialize();

    // detect edges over all channels
    inline void DetectChEdges( Mat& edgemag );

    // random perturb seeds
    inline void PerturbSeeds( const Mat& edgemag );

    // fetch seeds
    inline void GetChSeedsS();

    // fetch seeds
    inline void GetChSeedsK();

    // SLIC
    inline void PerformSLIC( const int& num_iterations );

    // SLICO
    inline void PerformSLICO( const int& num_iterations );
173 174 175 176 177 178 179

    // MSLIC
    inline void PerformMSLIC( const int& num_iterations );

    // MSLIC
    inline void SuperpixelSplit();

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
};

CV_EXPORTS Ptr<SuperpixelSLIC> createSuperpixelSLIC( InputArray image, int algorithm, int region_size, float ruler )
{
    return makePtr<SuperpixelSLICImpl>( image, algorithm, region_size, ruler );
}

SuperpixelSLICImpl::SuperpixelSLICImpl( InputArray _image, int _algorithm, int _region_size, float _ruler )
                   : m_algorithm(_algorithm), m_region_size(_region_size), m_ruler(_ruler)
{
    if ( _image.isMat() )
    {
      Mat image = _image.getMat();

      // image should be valid
      CV_Assert( !image.empty() );

      // initialize sizes
      m_width = image.size().width;
      m_height = image.size().height;
      m_nr_channels = image.channels();

      // intialize channels
      split( image, m_chvec );
    }
    else if ( _image.isMatVector() )
    {
      _image.getMatVector( m_chvec );

      // array should be valid
      CV_Assert( !m_chvec.empty() );

      // initialize sizes
      m_width = m_chvec[0].size().width;
      m_height = m_chvec[0].size().height;
      m_nr_channels = (int) m_chvec.size();
    }
    else
      CV_Error( Error::StsInternal, "Invalid InputArray." );

    // init
    initialize();
}

SuperpixelSLICImpl::~SuperpixelSLICImpl()
{
    m_chvec.clear();
    m_kseeds.clear();
    m_kseedsx.clear();
    m_kseedsy.clear();
    m_klabels.release();
}

int SuperpixelSLICImpl::getNumberOfSuperpixels() const
{
    return m_numlabels;
}

void SuperpixelSLICImpl::initialize()
{
    // total amount of superpixels given its size as input
    m_numlabels = int(float(m_width * m_height)
                /  float(m_region_size * m_region_size));

    // initialize seed storage
    m_kseeds.resize( m_nr_channels );

    // intitialize label storage
    m_klabels = Mat( m_height, m_width, CV_32S, Scalar::all(0) );

    // storage for edge magnitudes
    Mat edgemag = Mat( m_height, m_width, CV_32F, Scalar::all(0) );

    // perturb seeds is not absolutely necessary,
    // one can set this flag to false
    bool perturbseeds = true;

    if ( perturbseeds ) DetectChEdges( edgemag );

    if( m_algorithm == SLICO )
      GetChSeedsK();
261 262
    else if( ( m_algorithm == SLIC ) ||
             ( m_algorithm == MSLIC ) )
263 264 265 266
      GetChSeedsS();
    else
      CV_Error( Error::StsInternal, "No such algorithm" );

267 268 269
    // update amount of labels now
    m_numlabels = (int)m_kseeds[0].size();

270 271 272
    // perturb seeds given edges
    if ( perturbseeds ) PerturbSeeds( edgemag );

273 274 275 276 277
    if( m_algorithm == MSLIC )
    {
      m_merge = 4.0f;
      m_adaptk.resize( m_numlabels, 1.0f );
    }
278 279 280 281
}

void SuperpixelSLICImpl::iterate( int num_iterations )
{
282 283 284
    // store total iterations
    m_iterations = num_iterations;

285 286 287 288
    if( m_algorithm == SLICO )
      PerformSLICO( num_iterations );
    else if( m_algorithm == SLIC )
      PerformSLIC( num_iterations );
289 290
    else if( m_algorithm == MSLIC )
      PerformMSLIC( num_iterations );
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    else
      CV_Error( Error::StsInternal, "No such algorithm" );

    // re-update amount of labels
    m_numlabels = (int)m_kseeds[0].size();
}

void SuperpixelSLICImpl::getLabels(OutputArray labels_out) const
{
    labels_out.assign( m_klabels );
}

void SuperpixelSLICImpl::getLabelContourMask(OutputArray _mask, bool _thick_line) const
{
    // default width
    int line_width = 2;

    if ( !_thick_line ) line_width = 1;

310
    _mask.create( m_height, m_width, CV_8UC1 );
311 312
    Mat mask = _mask.getMat();

313
    mask.setTo(0);
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

    const int dx8[8] = { -1, -1,  0,  1, 1, 1, 0, -1 };
    const int dy8[8] = {  0, -1, -1, -1, 0, 1, 1,  1 };

    int sz = m_width*m_height;

    vector<bool> istaken(sz, false);

    int mainindex = 0;
    for( int j = 0; j < m_height; j++ )
    {
      for( int k = 0; k < m_width; k++ )
      {
        int np = 0;
        for( int i = 0; i < 8; i++ )
        {
          int x = k + dx8[i];
          int y = j + dy8[i];

          if( (x >= 0 && x < m_width) && (y >= 0 && y < m_height) )
          {
            int index = y*m_width + x;

            if( false == istaken[index] )
            {
              if( m_klabels.at<int>(j,k) != m_klabels.at<int>(y,x) ) np++;
            }
          }
        }
        if( np > line_width )
        {
345
           mask.at<char>(j,k) = (uchar)255;
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
           istaken[mainindex] = true;
        }
        mainindex++;
      }
    }
}

/*
 * EnforceLabelConnectivity
 *
 *   1. finding an adjacent label for each new component at the start
 *   2. if a certain component is too small, assigning the previously found
 *      adjacent label to this component, and not incrementing the label.
 *
 */
void SuperpixelSLICImpl::enforceLabelConnectivity( int min_element_size )
{

    if ( min_element_size == 0 ) return;
    CV_Assert( min_element_size >= 0 && min_element_size <= 100 );

367 368 369 370 371 372 373
    vector<float> adaptk( m_numlabels, 1.0f );

    if( m_algorithm == MSLIC )
    {
      adaptk.clear();
    }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    const int dx4[4] = { -1,  0,  1,  0 };
    const int dy4[4] = {  0, -1,  0,  1 };

    const int sz = m_width * m_height;
    const int supsz = sz / m_numlabels;

    int div = int(100.0f/(float)min_element_size + 0.5f);
    int min_sp_sz = max(3, supsz / div);

    Mat nlabels( m_height, m_width, CV_32S, Scalar(INT_MAX) );

    int label = 0;
    vector<int> xvec(sz);
    vector<int> yvec(sz);

389 390 391 392 393 394 395 396 397 398 399 400 401 402
    // MSLIC
    int currentlabel;
    float diffch = 0.0f;
    vector<float> adjch;
    vector<float> curch;
    map<int,int> hashtable;

    if( m_algorithm == MSLIC )
    {
      hashtable[-1] = 0;
      adjch.resize( m_nr_channels, 0 );
      curch.resize( m_nr_channels, 0 );
    }

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    //adjacent label
    int adjlabel = 0;

    for( int j = 0; j < m_height; j++ )
    {
        for( int k = 0; k < m_width; k++ )
        {
            if( nlabels.at<int>(j,k) == INT_MAX )
            {
                nlabels.at<int>(j,k) = label;
                //--------------------
                // Start a new segment
                //--------------------
                xvec[0] = k;
                yvec[0] = j;
418
                currentlabel = m_klabels.at<int>(j,k);
419 420 421 422 423 424 425 426 427
                //-------------------------------------------------------
                // Quickly find an adjacent label for use later if needed
                //-------------------------------------------------------
                for( int n = 0; n < 4; n++ )
                {
                    int x = xvec[0] + dx4[n];
                    int y = yvec[0] + dy4[n];
                    if( (x >= 0 && x < m_width) && (y >= 0 && y < m_height) )
                    {
428 429 430 431 432 433 434 435 436 437 438
                        if( nlabels.at<int>(y,x) != INT_MAX )
                        {
                            adjlabel = nlabels.at<int>(y,x);
                            if( m_algorithm == MSLIC )
                            {
                                for( int b = 0; b < m_nr_channels; b++ )
                                {
                                  adjch[b] = m_kseeds[b][m_klabels.at<int>(y,x)];
                                }
                            }
                        }
439 440 441
                    }
                }

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                if( m_algorithm == MSLIC )
                {
                    float ssumch = 0.0f;
                    for( int b = 0; b < m_nr_channels; b++ )
                    {
                        curch[b] = m_kseeds[b][m_klabels.at<int>(j,k)];
                        // squared distance
                        float diff = curch[b] - adjch[b];
                        ssumch += diff * diff;
                    }
                    // L2 distance with adj
                    diffch = sqrt( ssumch );
                    adaptk.push_back( m_adaptk[currentlabel] );
                }

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
                int count(1);
                for( int c = 0; c < count; c++ )
                {
                    for( int n = 0; n < 4; n++ )
                    {
                        int x = xvec[c] + dx4[n];
                        int y = yvec[c] + dy4[n];

                        if( (x >= 0 && x < m_width) && (y >= 0 && y < m_height) )
                        {
                            if( INT_MAX == nlabels.at<int>(y,x) &&
                                m_klabels.at<int>(j,k) == m_klabels.at<int>(y,x) )
                            {
                                xvec[count] = x;
                                yvec[count] = y;
                                nlabels.at<int>(y,x) = label;
                                count++;
                            }
                        }
                    }
                }
478 479
                // MSLIC only
                if( m_algorithm == MSLIC )
480
                {
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                  if ( m_cur_iter < m_iterations - 1 )
                  {
                      hashtable[label] = count;
                      //-------------------------------------------------------
                      // If segment size is less then a limit, or is very similar
                      // to it's neighbour assign adjacent label found before,
                      // and decrement label count.
                      //-------------------------------------------------------
                      if( ( count <= min_sp_sz ) ||
                          (
                            ( diffch < m_merge ) &&
                            ( hashtable[adjlabel] + hashtable[(int)adaptk.size()-1]
                           <= 3 * m_region_size * m_region_size )
                          )
                        )
                      {
                          if( ( diffch < m_merge) &&
                              ( hashtable[adjlabel] + hashtable[(int)adaptk.size()-1]
                             <= 3 * m_region_size * m_region_size )
                            )
                          {
                              adaptk[adjlabel] = min( 2.0f, float(adaptk[adjlabel] + adaptk[(int)adaptk.size()-1]) );
                              hashtable[adjlabel] += hashtable[(int)adaptk.size()-1];
                          }

                          for( int c = 0; c < count; c++ )
                          {
                              nlabels.at<int>(yvec[c],xvec[c]) = adjlabel;
                          }

                          label--;
                          adaptk.pop_back();
                      }
                  } else
                  {
                      //-------------------------------------------------------
                      // If segment size is less then a limit, assign an
                      // adjacent label found before, and decrement label count.
                      //-------------------------------------------------------
                      if( count <= min_sp_sz )
                      {
                          for( int c = 0; c < count; c++ )
                          {
                              nlabels.at<int>(yvec[c],xvec[c]) = adjlabel;
                          }
                          label--;
                      }
                  }
                // SLIC or SLICO
                } else
                {
                  //-------------------------------------------------------
                  // If segment size is less then a limit, assign an
                  // adjacent label found before, and decrement label count.
                  //-------------------------------------------------------
                  if( count <= min_sp_sz )
                  {
                      for( int c = 0; c < count; c++ )
                      {
                          nlabels.at<int>(yvec[c],xvec[c]) = adjlabel;
                      }
                      label--;
                  }
544 545 546 547 548 549 550 551
                }
                label++;
            }
        }
    }
    // replace old
    m_klabels = nlabels;
    m_numlabels = label;
552 553 554

    m_adaptk.clear();
    m_adaptk = adaptk;
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 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 775 776 777 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 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
}

/*
 * DetectChEdges
 */
inline void SuperpixelSLICImpl::DetectChEdges( Mat &edgemag )
{
    Mat dx, dy;
    Mat S_dx, S_dy;

    for (int c = 0; c < m_nr_channels; c++)
    {
        // derivate
        Sobel( m_chvec[c], dx, CV_32F, 1, 0, 1, 1.0f, 0.0f, BORDER_DEFAULT );
        Sobel( m_chvec[c], dy, CV_32F, 0, 1, 1, 1.0f, 0.0f, BORDER_DEFAULT );

        // acumulate ^2 derivate
        S_dx = S_dx + dx.mul(dx);
        S_dy = S_dy + dy.mul(dy);

    }
    // total magnitude
    edgemag += S_dx + S_dy;
}

/*
 * PerturbSeeds
 */
inline void SuperpixelSLICImpl::PerturbSeeds( const Mat& edgemag )
{
    const int dx8[8] = { -1, -1,  0,  1,  1,  1,  0, -1 };
    const int dy8[8] = {  0, -1, -1, -1,  0,  1,  1,  1 };

    for( int n = 0; n < m_numlabels; n++ )
    {
        int ox = (int)m_kseedsx[n]; //original x
        int oy = (int)m_kseedsy[n]; //original y

        int storex = ox;
        int storey = oy;
        for( int i = 0; i < 8; i++ )
        {
            int nx = ox + dx8[i]; //new x
            int ny = oy + dy8[i]; //new y

            if( nx >= 0 && nx < m_width && ny >= 0 && ny < m_height)
            {
                if( edgemag.at<float>(ny,nx) < edgemag.at<float>(storey,storex) )
                {
                    storex = nx;
                    storey = ny;
                }
            }
        }
        if( storex != ox && storey != oy )
        {
            m_kseedsx[n] = (float)storex;
            m_kseedsy[n] = (float)storey;

            switch ( m_chvec[0].depth() )
            {
              case CV_8U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<uchar>( storey, storex );
                break;

              case CV_8S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<char>( storey, storex );
                break;

              case CV_16U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<ushort>( storey, storex );
                break;

              case CV_16S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<short>( storey, storex );
                break;

              case CV_32S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = (float) m_chvec[b].at<int>( storey, storex );
                break;

              case CV_32F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<float>( storey, storex );
                break;

              case CV_64F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = (float) m_chvec[b].at<double>( storey, storex );
                break;

              default:
                CV_Error( Error::StsInternal, "Invalid matrix depth" );
                break;
            }
        }
    }
}

/*
 * GetChannelsSeeds_ForGivenStepSize
 *
 * The k seed values are
 * taken as uniform spatial
 * pixel samples.
 *
 */
inline void SuperpixelSLICImpl::GetChSeedsS()
{
    int n = 0;
    int numseeds = 0;

    int xstrips = int(0.5f + float(m_width) / float(m_region_size) );
    int ystrips = int(0.5f + float(m_height) / float(m_region_size) );

    int xerr = m_width  - m_region_size*xstrips;
    int yerr = m_height - m_region_size*ystrips;

    float xerrperstrip = float(xerr) / float(xstrips);
    float yerrperstrip = float(yerr) / float(ystrips);

    int xoff = m_region_size / 2;
    int yoff = m_region_size / 2;

    numseeds = xstrips*ystrips;

    for ( int b = 0; b < m_nr_channels; b++ )
      m_kseeds[b].resize(numseeds);

    m_kseedsx.resize(numseeds);
    m_kseedsy.resize(numseeds);

    for( int y = 0; y < ystrips; y++ )
    {
        int ye = y * (int)yerrperstrip;
        int Y = y*m_region_size + yoff+ye;
        if( Y > m_height-1 ) continue;
        for( int x = 0; x < xstrips; x++ )
        {
            int xe = x * (int)xerrperstrip;
            int X = x*m_region_size + xoff+xe;
            if( X > m_width-1 ) continue;

            switch ( m_chvec[0].depth() )
            {
              case CV_8U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<uchar>(Y,X);
                break;

              case CV_8S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<char>(Y,X);
                break;

              case CV_16U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<ushort>(Y,X);
                break;

              case CV_16S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<short>(Y,X);
                break;

              case CV_32S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = (float) m_chvec[b].at<int>(Y,X);
                break;

              case CV_32F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = m_chvec[b].at<float>(Y,X);
                break;

              case CV_64F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b][n] = (float) m_chvec[b].at<double>(Y,X);
                break;

              default:
                CV_Error( Error::StsInternal, "Invalid matrix depth" );
                break;
            }

            m_kseedsx[n] = (float)X;
            m_kseedsy[n] = (float)Y;

            n++;
        }
    }
}

/*
 * GetChannlesSeeds_ForGivenK
 *
 * The k seed values are
 * taken as uniform spatial
 * pixel samples.
 *
 */
inline void SuperpixelSLICImpl::GetChSeedsK()
{
    int xoff = m_region_size / 2;
    int yoff = m_region_size / 2;
    int n = 0; int r = 0;
    for( int y = 0; y < m_height; y++ )
    {
        int Y = y*m_region_size + yoff;
        if( Y > m_height-1 ) continue;
        for( int x = 0; x < m_width; x++ )
        {
            // hex grid
            int X = x*m_region_size + ( xoff<<( r & 0x1) );
            if( X > m_width-1 ) continue;

            switch ( m_chvec[0].depth() )
            {
              case CV_8U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( m_chvec[b].at<uchar>(Y,X) );
                break;

              case CV_8S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( m_chvec[b].at<char>(Y,X) );
                break;

              case CV_16U:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( m_chvec[b].at<ushort>(Y,X) );
                break;

              case CV_16S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( m_chvec[b].at<short>(Y,X) );
                break;

              case CV_32S:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( (float) m_chvec[b].at<int>(Y,X) );
                break;

              case CV_32F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( m_chvec[b].at<float>(Y,X) );
                break;

              case CV_64F:
                for( int b = 0; b < m_nr_channels; b++ )
                  m_kseeds[b].push_back( (float) m_chvec[b].at<double>(Y,X) );
                break;

              default:
                CV_Error( Error::StsInternal, "Invalid matrix depth" );
                break;
            }

            m_kseedsx.push_back((float)X);
            m_kseedsy.push_back((float)Y);

            n++;
        }
        r++;
    }
}

struct SeedNormInvoker : ParallelLoopBody
{
    SeedNormInvoker( vector< vector<float> >* _kseeds, vector< vector<float> >* _sigma,
                     vector<int>* _clustersize, vector<float>* _sigmax, vector<float>* _sigmay,
                     vector<float>* _kseedsx, vector<float>* _kseedsy, int _nr_channels )
    {
      sigma = _sigma;
      kseeds = _kseeds;
      sigmax = _sigmax;
      sigmay = _sigmay;
      kseedsx = _kseedsx;
      kseedsy = _kseedsy;
      nr_channels = _nr_channels;
      clustersize = _clustersize;
    }

843
    void operator ()(const cv::Range& range) const CV_OVERRIDE
844 845 846 847 848 849
    {
      for (int k = range.start; k < range.end; ++k)
      {
            if( clustersize->at(k) <= 0 ) clustersize->at(k) = 1;

            for ( int b = 0; b < nr_channels; b++ )
850
              kseeds->at(b)[k] = sigma->at(b)[k] / float(clustersize->at(k));
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

            kseedsx->at(k) = sigmax->at(k) / float(clustersize->at(k));
            kseedsy->at(k) = sigmay->at(k) / float(clustersize->at(k));
      } // end for k
    }
    vector<float>* sigmax;
    vector<float>* sigmay;
    vector<float>* kseedsx;
    vector<float>* kseedsy;
    vector<int>* clustersize;
    vector< vector<float> >* sigma;
    vector< vector<float> >* kseeds;
    int nr_channels;
};

struct SeedsCenters
{
    SeedsCenters( const vector<Mat>& _chvec, const Mat& _klabels,
                  const int _numlabels, const int _nr_channels )
    {
      chvec = _chvec;
      klabels = _klabels;
      numlabels = _numlabels;
      nr_channels = _nr_channels;

      // allocate and init arrays
      sigma.resize(nr_channels);
      for( int b =0 ; b < nr_channels ; b++ )
        sigma[b].assign(numlabels, 0);

      sigmax.assign(numlabels, 0);
      sigmay.assign(numlabels, 0);
      clustersize.assign(numlabels, 0);
    }

    SeedsCenters( const SeedsCenters& counter, Split )
    {
      *this = counter;
      // refill with zero all arrays
      for( int b = 0; b < nr_channels; b++ )
        fill(sigma[b].begin(), sigma[b].end(), 0.0f);

      fill(sigmax.begin(), sigmax.end(), 0.0f);
      fill(sigmay.begin(), sigmay.end(), 0.0f);
      fill(clustersize.begin(), clustersize.end(), 0);
    }

    void operator()( const BlockedRange& range )
    {
      // previous block state
      vector<float> tmp_sigmax = sigmax;
      vector<float> tmp_sigmay = sigmay;
      vector<vector <float> > tmp_sigma = sigma;
      vector<int> tmp_clustersize = clustersize;

      for ( int x = range.begin(); x != range.end(); x++ )
      {
        for( int y = 0; y < chvec[0].rows; y++ )
        {
            int idx = klabels.at<int>(y,x);

            switch ( chvec[0].depth() )
            {
              case CV_8U:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<uchar>(y,x);
                break;

              case CV_8S:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<char>(y,x);
                break;

              case CV_16U:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<ushort>(y,x);
                break;

              case CV_16S:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<short>(y,x);
                break;

              case CV_32S:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<int>(y,x);
                break;

              case CV_32F:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += chvec[b].at<float>(y,x);
                break;

              case CV_64F:
                for( int b = 0; b < nr_channels; b++ )
                  tmp_sigma[b][idx] += (float) chvec[b].at<double>(y,x);
                break;

              default:
                CV_Error( Error::StsInternal, "Invalid matrix depth" );
                break;
            }

            tmp_sigmax[idx] += x;
            tmp_sigmay[idx] += y;

            tmp_clustersize[idx]++;

        }
      }
      sigma = tmp_sigma;
      sigmax = tmp_sigmax;
      sigmay = tmp_sigmay;
      clustersize = tmp_clustersize;
    }

    void join( SeedsCenters& sc )
    {
      for (int l = 0; l < numlabels; l++)
      {
        sigmax[l] += sc.sigmax[l];
        sigmay[l] += sc.sigmay[l];
        for( int b = 0; b < nr_channels; b++ )
            sigma[b][l] += sc.sigma[b][l];
        clustersize[l] += sc.clustersize[l];
      }
    }

    Mat klabels;
    int numlabels;
    int nr_channels;
    vector<Mat> chvec;
    vector<float> sigmax;
    vector<float> sigmay;
    vector<int> clustersize;
    vector< vector<float> > sigma;
};

struct SLICOGrowInvoker : ParallelLoopBody
{
    SLICOGrowInvoker( vector<Mat>* _chvec, Mat* _distchans, Mat* _distxy, Mat* _distvec,
                      Mat* _klabels, float _kseedsxn, float _kseedsyn, float _xywt,
                      float _maxchansn, vector< vector<float> > *_kseeds,
                      int _x1, int _x2, int _nr_channels, int _n )
    {
      chvec = _chvec;
      distchans = _distchans;
      distxy = _distxy;
      distvec = _distvec;
      kseedsxn = _kseedsxn;
      kseedsyn = _kseedsyn;
      klabels = _klabels;
      maxchansn = _maxchansn;
      kseeds = _kseeds;
      x1 = _x1;
      x2 = _x2;
      n = _n;
      xywt = _xywt;
      nr_channels = _nr_channels;
    }

1012
    void operator ()(const cv::Range& range) const CV_OVERRIDE
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    {
      int cols = klabels->cols;
      int rows = klabels->rows;
      for (int y = range.start; y < range.end; ++y)
      {
        for( int x = x1; x < x2; x++ )
        {
          CV_Assert( y < rows && x < cols && y >= 0 && x >= 0 );
          distchans->at<float>(y,x) = 0;

            switch ( chvec->at(0).depth() )
            {
              case CV_8U:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<uchar>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_8S:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<char>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_16U:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<ushort>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_16S:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<short>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_32S:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<int>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_32F:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = chvec->at(b).at<float>(y,x)
                             - kseeds->at(b)[n];
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              case CV_64F:
                for( int b = 0; b < nr_channels; b++ )
                {
                  float diff = float(chvec->at(b).at<double>(y,x)
                             - kseeds->at(b)[n]);
                  distchans->at<float>(y,x) += diff * diff;
                }
                break;

              default:
                CV_Error( Error::StsInternal, "Invalid matrix depth" );
                break;
            }


          float difx = x - kseedsxn;
          float dify = y - kseedsyn;
          distxy->at<float>(y,x) = difx*difx + dify*dify;

          // only varying m, prettier superpixels
          float dist = distchans->at<float>(y,x)
                     / maxchansn + distxy->at<float>(y,x)/xywt;

          if( dist < distvec->at<float>(y,x) )
          {
            distvec->at<float>(y,x) = dist;
            klabels->at<int>(y,x) = n;
          }
        } // end for x
      } // end for y
    }

    Mat* klabels;
    vector< vector<float> > *kseeds;
    float maxchansn, xywt;
    vector<Mat>* chvec;
    Mat *distchans, *distxy, *distvec;
    float kseedsxn, kseedsyn;
    int x1, x2, nr_channels, n;
};

/*
 *
 *    Magic SLIC - no parameters
 *
 *    Performs k mean segmentation. It is fast because it looks locally, not
 * over the entire image.
 * This function picks the maximum value of color distance as compact factor
 * M and maximum pixel distance as grid step size S from each cluster (13 April 2011).
 * So no need to input a constant value of M and S. There are two clear
 * advantages:
 *
 * [1] The algorithm now better handles both textured and non-textured regions
 * [2] There is not need to set any parameters!!!
 *
 * SLICO (or SLIC Zero) dynamically varies only the compactness factor S,
 * not the step size S.
 *
 */
inline void SuperpixelSLICImpl::PerformSLICO( const int&  itrnum )
{
    Mat distxy( m_height, m_width, CV_32F, Scalar::all(FLT_MAX) );
    Mat distvec( m_height, m_width, CV_32F, Scalar::all(FLT_MAX) );
    Mat distchans( m_height, m_width, CV_32F, Scalar::all(FLT_MAX) );

    // this is the variable value of M, just start with 10
    vector<float> maxchans( m_numlabels, FLT_MIN );
    // this is the variable value of M, just start with 10
    vector<float> maxxy( m_numlabels, FLT_MIN );
    // note: this is different from how usual SLIC/LKM works
1149
    const float xywt = float(m_region_size*m_region_size);
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

    for( int itr = 0; itr < itrnum; itr++ )
    {
        distvec.setTo(FLT_MAX);
        for( int n = 0; n < m_numlabels; n++ )
        {
            int y1 = max(0, (int) m_kseedsy[n] - m_region_size);
            int y2 = min(m_height, (int) m_kseedsy[n] + m_region_size);
            int x1 = max(0, (int) m_kseedsx[n] - m_region_size);
            int x2 = min((int) m_width,(int) m_kseedsx[n] + m_region_size);

            parallel_for_( Range(y1, y2), SLICOGrowInvoker( &m_chvec, &distchans, &distxy, &distvec,
                           &m_klabels, m_kseedsx[n], m_kseedsy[n], xywt, maxchans[n], &m_kseeds,
                           x1, x2, m_nr_channels, n ) );
        }
        //-----------------------------------------------------------------
        // Assign the max color distance for a cluster
        //-----------------------------------------------------------------
        if( itr == 0 )
        {
            maxchans.assign(m_numlabels,FLT_MIN);
            maxxy.assign(m_numlabels,FLT_MIN);
        }

        for( int x = 0; x < m_width; x++ )
        {
          for( int y = 0; y < m_height; y++ )
          {
              int idx = m_klabels.at<int>(y,x);

              if( maxchans[idx] < distchans.at<float>(y,x) )
                  maxchans[idx] = distchans.at<float>(y,x);

              if( maxxy[idx] < distxy.at<float>(y,x) )
                  maxxy[idx] = distxy.at<float>(y,x);
          }
        }
        //-----------------------------------------------------------------
        // Recalculate the centroid and store in the seed values
        //-----------------------------------------------------------------

1191 1192 1193
        // parallel reduce structure
        SeedsCenters sc( m_chvec, m_klabels, m_numlabels, m_nr_channels );

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        // accumulate center distances
        parallel_reduce( BlockedRange(0, m_width), sc );

        // normalize centers
        parallel_for_( Range(0, m_numlabels), SeedNormInvoker( &m_kseeds, &sc.sigma,
                       &sc.clustersize, &sc.sigmax, &sc.sigmay, &m_kseedsx, &m_kseedsy, m_nr_channels  ) );

    }
}

struct SLICGrowInvoker : ParallelLoopBody
{
    SLICGrowInvoker( vector<Mat>* _chvec, Mat* _distvec, Mat* _klabels,
                     float _kseedsxn, float _kseedsyn, float _xywt,
                     vector< vector<float> > *_kseeds, int _x1, int _x2,
                     int _nr_channels, int _n )
    {
      chvec = _chvec;
      distvec = _distvec;
      kseedsxn = _kseedsxn;
      kseedsyn = _kseedsyn;
      klabels = _klabels;
      kseeds = _kseeds;
      x1 = _x1;
      x2 = _x2;
      n = _n;
      xywt = _xywt;
      nr_channels = _nr_channels;
    }

1224
    void operator ()(const cv::Range& range) const CV_OVERRIDE
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    {
      for (int y = range.start; y < range.end; ++y)
      {
        for( int x = x1; x < x2; x++ )
        {
          float dist = 0;

          switch ( chvec->at(0).depth() )
          {
            case CV_8U:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<uchar>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_8S:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<char>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_16U:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<ushort>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_16S:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<short>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_32S:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<int>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_32F:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = chvec->at(b).at<float>(y,x) - kseeds->at(b)[n];
                dist += diff * diff;
              }
              break;

            case CV_64F:
              for( int b = 0; b < nr_channels; b++ )
              {
                float diff = float(chvec->at(b).at<double>(y,x) - kseeds->at(b)[n]);
                dist += diff * diff;
              }
              break;

            default:
              CV_Error( Error::StsInternal, "Invalid matrix depth" );
              break;
          }

          float difx = x - kseedsxn;
          float dify = y - kseedsyn;
          float distxy = difx*difx + dify*dify;

          dist += distxy / xywt;

          //this would be more exact but expensive
          //dist = sqrt(dist) + sqrt(distxy/xywt);

          if( dist < distvec->at<float>(y,x) )
          {
            distvec->at<float>(y,x) = dist;
            klabels->at<int>(y,x) = n;
          }
        } //end for x
      } // end for y
    }

    Mat* klabels;
    vector< vector<float> > *kseeds;
    float xywt;
    vector<Mat>* chvec;
    Mat *distvec;
    float kseedsxn, kseedsyn;
    int x1, x2, nr_channels, n;
};

/*
 *    PerformSuperpixelSLIC
 *
 *    Performs k mean segmentation. It is fast because it looks locally, not
 * over the entire image.
 *
 */
inline void SuperpixelSLICImpl::PerformSLIC( const int&  itrnum )
{
    Mat distvec( m_height, m_width, CV_32F );

1333
    const float xywt = (m_region_size/m_ruler)*(m_region_size/m_ruler);
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354

    for( int itr = 0; itr < itrnum; itr++ )
    {
        distvec.setTo(FLT_MAX);
        for( int n = 0; n < m_numlabels; n++ )
        {
            int y1 = max(0, (int) m_kseedsy[n] - m_region_size);
            int y2 = min(m_height, (int) m_kseedsy[n] + m_region_size);
            int x1 = max(0, (int) m_kseedsx[n] - m_region_size);
            int x2 = min((int) m_width,(int) m_kseedsx[n] + m_region_size);

            parallel_for_( Range(y1, y2), SLICGrowInvoker( &m_chvec, &distvec,
                           &m_klabels, m_kseedsx[n], m_kseedsy[n], xywt, &m_kseeds,
                           x1, x2, m_nr_channels, n ) );
        }

        //-----------------------------------------------------------------
        // Recalculate the centroid and store in the seed values
        //-----------------------------------------------------------------
        // instead of reassigning memory on each iteration, just reset.

1355 1356 1357
        // parallel reduce structure
        SeedsCenters sc( m_chvec, m_klabels, m_numlabels, m_nr_channels );

1358 1359 1360 1361
        // accumulate center distances
        parallel_reduce( BlockedRange(0, m_width), sc );

        // normalize centers
1362 1363
        parallel_for_( Range(0, m_numlabels), SeedNormInvoker( &m_kseeds, &sc.sigma,
                       &sc.clustersize, &sc.sigmax, &sc.sigmay, &m_kseedsx, &m_kseedsy, m_nr_channels  ) );
1364 1365 1366 1367

    }
}

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
/*
 *    PerformSuperpixelMSLIC
 *
 *
 */
inline void SuperpixelSLICImpl::PerformMSLIC( const int&  itrnum )
{
    vector< vector<float> > sigma(m_nr_channels);
    for( int b = 0; b < m_nr_channels; b++ )
      sigma[b].resize(m_numlabels, 0);

    Mat distvec( m_height, m_width, CV_32F );

    const float xywt = (m_region_size/m_ruler)*(m_region_size/m_ruler);

    int offset = m_region_size;

    // from paper
    m_split = 4.0f;
    m_ratio = 5.0f;

    for( int itr = 0; itr < itrnum; itr++ )
    {
        m_cur_iter = itr;

        distvec.setTo(FLT_MAX);
        for( int n = 0; n < m_numlabels; n++ )
        {
            if ( m_adaptk[n] < 1.0f )
                offset = int(m_region_size * m_adaptk[n]);
            else
                offset = int(m_region_size * m_adaptk[n]);

            int y1 = max(0,        (int) m_kseedsy[n] - offset);
            int y2 = min(m_height, (int) m_kseedsy[n] + offset);
            int x1 = max(0,        (int) m_kseedsx[n] - offset);
            int x2 = min(m_width,  (int) m_kseedsx[n] + offset);

            parallel_for_( Range(y1, y2), SLICGrowInvoker( &m_chvec, &distvec,
                           &m_klabels, m_kseedsx[n], m_kseedsy[n], xywt, &m_kseeds,
                           x1, x2, m_nr_channels, n ) );
        }

        //-----------------------------------------------------------------
        // Recalculate the centroid and store in the seed values
        //-----------------------------------------------------------------
        // instead of reassigning memory on each iteration, just reset.

        // parallel reduce structure
        SeedsCenters sc( m_chvec, m_klabels, m_numlabels, m_nr_channels );

        // accumulate center distances
        parallel_reduce( BlockedRange(0, m_width), sc );

        // normalize centers
        parallel_for_( Range(0, m_numlabels), SeedNormInvoker( &m_kseeds, &sc.sigma,
                       &sc.clustersize, &sc.sigmax, &sc.sigmay, &m_kseedsx, &m_kseedsy, m_nr_channels ) );

        // 13% as in original paper
        enforceLabelConnectivity( 13 );
        SuperpixelSplit();
    }
}

inline void SuperpixelSLICImpl::SuperpixelSplit()
{
    Mat klabels = m_klabels.clone();

    // parallel reduce structure
    SeedsCenters msc( m_chvec, m_klabels, m_numlabels, m_nr_channels );

    // accumulate center distances
    parallel_reduce( BlockedRange(0, m_width), msc );

    const float invwt = 1.0f / ( (m_region_size/m_ruler)*(m_region_size/m_ruler) );
    const float sqrt_invwt = sqrt(invwt);

    if ( m_cur_iter < m_iterations - 2 )
    {
        vector<float> avglabs( m_numlabels, 0 );
        for( int y = 0; y < m_height - 1; y++ )
        {
            for( int x = 0; x < m_width - 1; x++ )
            {
                if ( klabels.at<int>( y, x ) == klabels.at<int>( y+1, x ) &&
                     klabels.at<int>( y, x ) == klabels.at<int>( y, x+1 ) )
                {
                    float x1 = 1, y1 = 0;
                    float x2 = 0, y2 = 1;

                    vector<float> ch1(m_nr_channels);
                    vector<float> ch2(m_nr_channels);

                    switch ( m_chvec.at(0).depth() )
                    {
                      case CV_8U:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<uchar>( y+1, x   )
                                          - m_chvec[c].at<uchar>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<uchar>( y,   x+1 )
                                          - m_chvec[c].at<uchar>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_8S:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<char>( y+1, x   )
                                          - m_chvec[c].at<char>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<char>( y,   x+1 )
                                          - m_chvec[c].at<char>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_16U:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<ushort>( y+1, x   )
                                          - m_chvec[c].at<ushort>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<ushort>( y,   x+1 )
                                          - m_chvec[c].at<ushort>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_16S:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<short>( y+1, x   )
                                          - m_chvec[c].at<short>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<short>( y,   x+1 )
                                          - m_chvec[c].at<short>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_32S:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<int>( y+1, x   )
                                          - m_chvec[c].at<int>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<int>( y,   x+1 )
                                          - m_chvec[c].at<int>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_32F:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = m_chvec[c].at<float>( y+1, x   )
                                   - m_chvec[c].at<float>( y,   x   );
                            ch2[c] = m_chvec[c].at<float>( y,   x+1 )
                                   - m_chvec[c].at<float>( y,   x   );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      case CV_64F:
                        for( int c = 0; c < m_nr_channels; c++ )
                        {
                            ch1[c] = float( m_chvec[c].at<double>( y+1, x   )
                                          - m_chvec[c].at<double>( y,   x   ) );
                            ch2[c] = float( m_chvec[c].at<double>( y,   x+1 )
                                          - m_chvec[c].at<double>( y,   x   ) );

                            ch1[c] /= sqrt_invwt;
                            ch2[c] /= sqrt_invwt;
                        }
                        break;

                      default:
                        CV_Error( Error::StsInternal, "Invalid matrix depth" );
                        break;
                    }
                    float ch11sqsum = 0.0f;
                    float ch12sqsum = 0.0f;
                    float ch22sqsum = 0.0f;
                    for( int c = 0; c < m_nr_channels; c++ )
                    {
                       ch11sqsum += ch1[c]*ch1[c];
                       ch12sqsum += ch1[c]*ch2[c];
                       ch22sqsum += ch2[c]*ch2[c];
                    }

                    // adjacent metric for N channels
                    avglabs[ klabels.at<int>(y,x) ]
                              += sqrt(   (x1*x1 + y1*y1 + ch11sqsum) * (x2*x2 + y2*y2 + ch22sqsum)
                                       - (x1*x2 + y1*y2 + ch12sqsum) * (x1*x2 + y1*y2 + ch12sqsum) );
                }
             }
        }
        for ( int i = 0; i < m_numlabels; i++ )
        {
            avglabs[i] /= m_region_size * m_region_size;
        }

        m_kseedsx.clear();
        m_kseedsy.clear();
        m_kseedsx.resize( m_numlabels, 0 );
        m_kseedsy.resize( m_numlabels, 0 );
        for( int c = 0; c < m_nr_channels; c++ )
        {
          m_kseeds[c].clear();
          m_kseeds[c].resize( m_numlabels, 0 );
        }

        for( int k = 0; k < m_numlabels; k++ )
        {
            m_kseedsx[k] = msc.sigmax[k] / msc.clustersize[k];
            m_kseedsy[k] = msc.sigmay[k] / msc.clustersize[k];
            for( int c = 0; c < m_nr_channels; c++ )
                m_kseeds[c][k] = msc.sigma[c][k] / msc.clustersize[k];
        }

        for( int k = 0; k < m_numlabels; k++ )
        {
            int xindex = 0, yindex = 0;
            if ( ( m_adaptk[k] <= 0.5f ) ||
                 ( avglabs[k] < (m_split * m_ratio) ) )
            {
                m_kseedsx[k] = msc.sigmax[k] / msc.clustersize[k];
                m_kseedsy[k] = msc.sigmay[k] / msc.clustersize[k];
                for( int c = 0; c < m_nr_channels; c++ )
                  m_kseeds[c][k] = msc.sigma[c][k] / msc.clustersize[k];

                m_adaptk[k] = sqrt( m_ratio / avglabs[k] );
                m_adaptk[k] = max( 0.5f, m_adaptk[k] );
                m_adaptk[k] = min( 2.0f, m_adaptk[k] );
            }
            // if segment size is too large
            // split it and calculate four new seeds
            else
            {
                xindex = (int)( msc.sigmax[k] / msc.clustersize[k] );
                yindex = (int)( msc.sigmay[k] / msc.clustersize[k] );
                m_adaptk[k] = max( 0.5f, m_adaptk[k] / 2 );

                const float minadaptk = min( 1.0f, m_adaptk[k] ) * m_region_size / 2;

                int x1 = (int)( xindex - minadaptk );
                int x2 = (int)( xindex + minadaptk );
                int x3 = (int)( xindex - minadaptk );
                int x4 = (int)( xindex + minadaptk );

                int y1 = (int)( yindex + minadaptk );
                int y2 = (int)( yindex + minadaptk );
                int y3 = (int)( yindex - minadaptk );
                int y4 = (int)( yindex - minadaptk );

                if ( x1 < 0         ) x1 = 0;
                if ( x2 >= m_width  ) x2 = m_width  - 1;
                if ( x3 < 0         ) x3 = 0;
                if ( x4 >= m_width  ) x4 = m_width  - 1;
                if ( y1 >= m_height ) y1 = m_height - 1;
                if ( y2 >= m_height ) y2 = m_height - 1;
                if ( y3 < 0         ) y3 = 0;
                if ( y4 < 0         ) y4 = 0;

                m_kseedsx[k] = (float)x1;
                m_kseedsy[k] = (float)y1;
                for( int c = 0; c < m_nr_channels; c++ )
                {
                    switch ( m_chvec[c].depth() )
                    {
                      case CV_8U:
                        m_kseeds[c][k] = m_chvec[c].at<uchar>(y1,x1);
                        break;

                      case CV_8S:
                        m_kseeds[c][k] = m_chvec[c].at<char>(y1,x1);
                        break;

                      case CV_16U:
                        m_kseeds[c][k] = m_chvec[c].at<ushort>(y1,x1);
                        break;

                      case CV_16S:
                        m_kseeds[c][k] = m_chvec[c].at<short>(y1,x1);
                        break;

                      case CV_32S:
                        m_kseeds[c][k] = float(m_chvec[c].at<int>(y1,x1));
                        break;

                      case CV_32F:
                        m_kseeds[c][k] = m_chvec[c].at<float>(y1,x1);
                        break;

                      case CV_64F:
                        m_kseeds[c][k] = float(m_chvec[c].at<double>(y1,x1));
                        break;

                      default:
                        CV_Error( Error::StsInternal, "Invalid matrix depth" );
                        break;
                    }
                }

                m_kseedsx.push_back( (float)x2 );
                m_kseedsx.push_back( (float)x3 );
                m_kseedsx.push_back( (float)x4 );
                m_kseedsy.push_back( (float)y2 );
                m_kseedsy.push_back( (float)y3 );
                m_kseedsy.push_back( (float)y4 );

                for( int c = 0; c < m_nr_channels; c++ )
                {
                    switch ( m_chvec[c].depth() )
                    {
                      case CV_8U:
                        m_kseeds[c].push_back( m_chvec[c].at<uchar>(y2,x2) );
                        m_kseeds[c].push_back( m_chvec[c].at<uchar>(y3,x3) );
                        m_kseeds[c].push_back( m_chvec[c].at<uchar>(y4,x4) );
                        break;

                      case CV_8S:
                        m_kseeds[c].push_back( m_chvec[c].at<char>(y2,x2) );
                        m_kseeds[c].push_back( m_chvec[c].at<char>(y3,x3) );
                        m_kseeds[c].push_back( m_chvec[c].at<char>(y4,x4) );
                        break;

                      case CV_16U:
                        m_kseeds[c].push_back( m_chvec[c].at<ushort>(y2,x2) );
                        m_kseeds[c].push_back( m_chvec[c].at<ushort>(y3,x3) );
                        m_kseeds[c].push_back( m_chvec[c].at<ushort>(y4,x4) );
                        break;

                      case CV_16S:
                        m_kseeds[c].push_back( m_chvec[c].at<short>(y2,x2) );
                        m_kseeds[c].push_back( m_chvec[c].at<short>(y3,x3) );
                        m_kseeds[c].push_back( m_chvec[c].at<short>(y4,x4) );
                        break;

                      case CV_32S:
                        m_kseeds[c].push_back( float(m_chvec[c].at<int>(y2,x2)) );
                        m_kseeds[c].push_back( float(m_chvec[c].at<int>(y3,x3)) );
                        m_kseeds[c].push_back( float(m_chvec[c].at<int>(y4,x4)) );
                        break;

                      case CV_32F:
                        m_kseeds[c].push_back( m_chvec[c].at<float>(y2,x2) );
                        m_kseeds[c].push_back( m_chvec[c].at<float>(y3,x3) );
                        m_kseeds[c].push_back( m_chvec[c].at<float>(y4,x4) );
                        break;

                      case CV_64F:
                        m_kseeds[c].push_back( float(m_chvec[c].at<double>(y2,x2)) );
                        m_kseeds[c].push_back( float(m_chvec[c].at<double>(y3,x3)) );
                        m_kseeds[c].push_back( float(m_chvec[c].at<double>(y4,x4)) );
                        break;

                      default:
                        CV_Error( Error::StsInternal, "Invalid matrix depth" );
                        break;
                    }
                }
                m_adaptk.push_back( m_adaptk[k] );
                m_adaptk.push_back( m_adaptk[k] );
                m_adaptk.push_back( m_adaptk[k] );
                msc.clustersize.push_back( 1 );
                msc.clustersize.push_back( 1 );
                msc.clustersize.push_back( 1 );
            }
        }
    }
    else
    {
        m_kseedsx.clear();
        m_kseedsy.clear();
        m_kseedsx.resize( m_numlabels, 0 );
        m_kseedsy.resize( m_numlabels, 0 );
        for( int c = 0; c < m_nr_channels; c++ )
        {
          m_kseeds[c].clear();
          m_kseeds[c].resize( m_numlabels, 0 );
        }

        for( int k = 0; k < m_numlabels; k++ )
        {
            m_kseedsx[k] = msc.sigmax[k] / msc.clustersize[k];
            m_kseedsy[k] = msc.sigmay[k] / msc.clustersize[k];
            for( int c = 0; c < m_nr_channels; c++ )
                m_kseeds[c][k] = msc.sigma[c][k] / msc.clustersize[k];
        }
    }

  m_klabels.release();
  m_klabels = klabels.clone();

  // re-update amount of labels
  m_numlabels = (int)m_kseeds[0].size();

}


1779 1780
} // namespace ximgproc
} // namespace cv