bool regionMerge::apply(const imatrix& srcmask,
                          const dmatrix& simMat,
                          const dvector& thresholds,
                          imatrix& destmask) const {
    int i,j;
    const dvector& thrs = thresholds;

    ivector eLab(simMat.rows());
    for (i=0;i<eLab.size();++i)
      eLab.at(i) = i;

    double a;
    for (j=0;j<simMat.rows();++j)
      for (i=0;i<simMat.columns();++i) {
        if (simMat.at(j,i) > (a=max(thrs.at(j),thrs.at(i))) ) {
//          cout<<j<<" "<<i<<" "<<simMat.at(j,i)<<" "<<a<<endl;
          if (eLab.at(j)>eLab.at(i)) {
            eLab.at(j)=eLab.at(i);
          } else {
            eLab.at(i)=eLab.at(j);
          }

        }
      }


    // now correct the labels
    for (j=eLab.size()-1;j>=0;--j) { //todo
      i = j;
      while (eLab.at(i) != i) {
        i=eLab.at(i);
      }
      eLab.at(j) = i;
    }

    destmask.resize(srcmask.size(),0,false,false);
    for (j=0;j<srcmask.rows();++j)
      for (i=0;i<srcmask.columns();++i) {
        destmask.at(j,i) = eLab.at(srcmask.at(j,i));
      }

    return true;
 };
  /*
   * operates on a copy of the given %parameters.
   * @param srcmask source mask.  Each object must be represented by one
   *                              label.
   * @param simMat The similarity matrix.  The size of the matrix must
   *               be at least equal the number of labels plus one.
   * @param destMask resulting mask with merged objects.
   * @return true if apply successful or false otherwise.
   */
  bool regionMerge::apply(const imatrix& srcmask,
                          const dmatrix& simMat,
                          imatrix& destmask) const {
    int i,j;
    ivector eLab(simMat.rows());
    const double thr = getParameters().threshold;

    for (i=0;i<eLab.size();++i) {
      eLab.at(i) = i;
    }

    for (j=0;j<simMat.rows();++j) {
      for (i=0;i<simMat.columns();++i) {
        if (simMat.at(j,i) > thr) {
          if (eLab.at(j)>eLab.at(i)) {
            eLab.at(j)=eLab.at(i);
          } else {
            eLab.at(i)=eLab.at(j);
          }

        }
      }
    }

    // now correct the labels
    for (j=eLab.size()-1;j>=0;--j) {
      i = j;
      while (eLab.at(i) != i) {
        i=eLab.at(i);
      }
      eLab.at(j) = i;
    }

    destmask.resize(srcmask.size(),0,false,false);

    for (j=0;j<srcmask.rows();++j)
      for (i=0;i<srcmask.columns();++i) {
        destmask.at(j,i) = eLab.at(srcmask.at(j,i));
      }

    return true;
  };