Opencv2.4.9源码分析——Stitching(六)

版权声明:本文为赵春江原创文章,未经本人允许不得转载。 https://blog.csdn.net/zhaocj/article/details/78944867

6、寻找接缝线

6.1 原理

拼接图像的另一个重要的步骤是找到图像重叠部分内的一条接缝线,该接缝是重叠部分最相似的像素的连线。当确定了接缝线后,在重叠部分,线的一侧只选择该侧的图像部分,线的另一侧只选择这一侧的图像部分,而不是把重叠部分的两幅图像简单融合起来。这么做的目的可以避免图像的模糊及伪像。

目前,常用的寻找接缝线的方法有三种:逐点法、动态规划法和图割法。

逐点法比较简单,它的原理就是重叠部分内的像素距离哪个图像更近,就用哪个图像中的相应像素值。这种方法并不是基于像素值,只是基于距离准则。所以这种方法并不能真正得到最佳的接缝线,寻找的结果比较粗糙原始,仅仅是能够分割重叠部分而已。

动态规划法可以快速的找到最佳的接缝线,并且所需的内存较少,因此该方法很适合在移动终端设备上进行高清晰度的全景拼接。

设图像1和图像2之间有重叠部分,我们需要得到它们之间的最佳接缝,首先定义重叠部分的误差表面函数:

(88)

式中,I1I2表示两幅图像各自的重叠部分,││,||表示范数。

一般来说,接缝线有三个限制条件:一是如果重叠区域是宽大于高,则接缝是横向走向的,而如果重叠区域是宽小于高,则接缝是纵向走向的,也就是要保证接缝线要有一定的长度;二是如果是横向的接缝,则不允许有绝对垂直的接缝线,而如果是纵向的接缝,则不允许有绝对水平的接缝线;三是重叠区域是矩形,接缝线从矩形的一边出发,必须到达与该边平行的另一边结束。

假设重叠区域的宽小于高,则接缝线是垂直的,我们需要横向遍历e值,并且计算所有可能到达当前像素(i, j)的路径的累积最小误差E

扫描二维码关注公众号,回复: 3312501 查看本文章

(89)

式中,min中的三项内容分别表示当前像素与其左上侧、上侧和右上侧的E。在E中最后一行的最小值表明已经到达了最小垂直路径的尽头,那么我们就可以追溯,从而得到最佳路径,即接缝线。

同理,重叠区域的宽大于高也能够做出类似的计算过程。

我们可以看出,动态规划算法非常适用于对式89的求解,这也是该寻找最佳接缝线方法名称的由来。

对于彩色图像,计算式88可以有两种方法:直接法和梯度法。设pq是两个相邻像素,直接法的计算公式为:

(90)

梯度法的计算公式为:

(91)

式中,G表示灰度图像的pq方向上的梯度。

最后一种方法是图割法。它的主要思想是将图像看成是一个有向图G={V, E},V表示节点,E表示边。节点分为两种:普通节点和终端节点。图像的像素可以作为普通节点,图像的聚类结果可以看成是终端节点,即某一聚类中的普通节点会汇聚于一个终端节点,一般图只有两个终端节点:st,也就是说一般图割法只能够把图像分割成两类ST。边指的是节点之间的连接,对于普通节点,只有相邻节点可以连接,该边被称为n-links,而所有普通节点都可与属于它们的终端节点之间有连接,该边被称为t-links。用最大流图割法可以得到哪些普通节点属于终端节点s,那么剩下的普通节点就会属于t

Opencv中所实现的最大流图割算法是基于Boykov和Kolmogorov所提出的算法。该算法是以st为根,以得到的两棵无不相交的搜索树ST为目标,它迭代的重复以下三个阶段:

生长阶段:搜索树ST的生长,直到两棵树生长到了一起,形成了从st的通路(即为流);

增广阶段:该通路被增广,使相连的两棵树又重新分开;

收养阶段:搜索树ST收养孤立的节点(称为孤儿)。

在生长阶段,如果找不到任何一条从st的通路,则迭代结束。在增广阶段,开始孤儿集合是空集,而该阶段结束后,可能会出现一些孤儿。在该阶段,我们需要得到通路上最小的容量值(也称为边的权值),然后所有的容量值都减去该值(即通过流量更新容量值),则该通路上至少会有一个权值为0的边(称为饱和边),假设饱和边上的两个节点为pq,并且在正向通路中是由p流向q,如果pq都属于树S,则q为孤儿,如果pq都属于树T,则p为孤儿。在收养阶段,检查孤儿集合中的所有孤儿的邻域像素,连接那些它们的边的容量值不为0的像素,如果最终可以从该孤儿连通到st,则该孤儿就属于树S或树T,否则由该孤儿组成的树就属于自由节点集,在下次迭代时的生长阶段,树S和树T就通过连接自由节点集中的节点来使两棵树生长发育的。

如何用最大流图割法寻找接缝线呢?接缝线把重叠区域分割成了两个区域,那么我们通过最大流图割法得到树S和树T,即得到了被分割的两个区域,则区域之间的接缝线自然就可以得到。

普通节点之间的初始容量值(即边的权值)也可以通过直接法和梯度法计算得到,它们的计算公式分别与式90和式91相同。终端节点与普通节点之间的初始容量值可以定义为一个很大的值,当重叠区域中的节点只属于图像1或图像2时,节点与相应的终端节点的边赋予该值,其他情况都置为0,表示它们与终端节点无直接连接。

6.2 源码

SeamFinder类是寻找缝的基类,该类内有一个最重要的虚函数是find,它的作用是寻找缝:

virtual void find(const std::vector<Mat> &src, const std::vector<Point> &corners,
                      std::vector<Mat> &masks) = 0;

它的三个输入参数分别为:src表示待拼接的图像,corners表示待拼接图像在最终的全景图像坐标系内的左上角的坐标位置,masks输入时表示上一步得到的映射变换掩码,输出时表示接缝掩码,也就是该参数是要更新输出的,输出时如果像素值更新为0了,则表示该像素是在接缝的另一侧,拼接时是不需要该像素的。

基于SeamFinder类有四个子类,分别对应于四种不同的寻找缝的算法——NoSeamFinder(无需寻找缝)、PairwiseSeamFinder(逐点寻找缝算法)、DpSeamFinder(动态规划寻找缝算法)和GraphCutSeamFinder(图割寻找缝算法)。

我们先来介绍PairwiseSeamFinder类。逐点寻找缝算法又可分为不同的方法,Opencv只实现了Voronoi图方法,实现该方法的类为VoronoiSeamFinder类,它是PairwiseSeamFinder类的子类。VoronoiSeamFinder类的find函数为:
void VoronoiSeamFinder::find(const vector<Size> &sizes, const vector<Point> &corners,
                             vector<Mat> &masks)
{
    LOGLN("Finding seams...");
    if (sizes.size() == 0)    //没有图像,则返回
        return;

#if ENABLE_LOG
    int64 t = getTickCount();    //计时
#endif
    //参数赋值
    sizes_ = sizes;
    corners_ = corners;
    masks_ = masks;
    run();    //调用run函数
    //计时输出
    LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
}

VoronoiSeamFinder类没有实现run函数,因此这里的find函数调用的是它的父类PairwiseSeamFinder类的run函数:

void PairwiseSeamFinder::run()
{
    //遍历图像对
    for (size_t i = 0; i < sizes_.size() - 1; ++i)
    {
        for (size_t j = i + 1; j < sizes_.size(); ++j)
        {
            Rect roi;    //表示图像间的重叠部分
            //如果图像i和图j之间有重叠的区域,则执行findInPair函数
            if (overlapRoi(corners_[i], corners_[j], sizes_[i], sizes_[j], roi))
                findInPair(i, j, roi);
        }
    }
}

findInPair函数表示寻找两幅图像之间的接缝:

void VoronoiSeamFinder::findInPair(size_t first, size_t second, Rect roi)
//first和second表示两幅图像的尺寸大小,roi表示图像间重叠部分
{
    const int gap = 10;
    //分别表示图像first和图像second的重叠部分的掩码,它们要比roi四周多gap个距离
    Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
    Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);

    Size img1 = sizes_[first], img2 = sizes_[second];    //得到两幅图像的尺寸
    Mat mask1 = masks_[first], mask2 = masks_[second];    //得到两幅图像的掩码
    Point tl1 = corners_[first], tl2 = corners_[second];    //得到两幅图像的左上角坐标

    // Cut submasks with some gap
    //遍历重叠部分,得到submask1和submask2
    for (int y = -gap; y < roi.height + gap; ++y)
    {
        for (int x = -gap; x < roi.width + gap; ++x)
        {
            //y1和x1表示重叠部分相对于图像first的坐标
            int y1 = roi.y - tl1.y + y;
            int x1 = roi.x - tl1.x + x;
            //把图像first的掩码赋值给submask1
            //表示当前坐标在图像first内
            if (y1 >= 0 && x1 >= 0 && y1 < img1.height && x1 < img1.width) 
                submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);
            else    //表示当前坐标不在图像first内
                submask1.at<uchar>(y + gap, x + gap) = 0;
            //y2和x2表示重叠部分相对于图像second的坐标
            int y2 = roi.y - tl2.y + y;
            int x2 = roi.x - tl2.x + x;
            //把图像second的掩码赋值给submask2
            //表示当前坐标在图像second内
            if (y2 >= 0 && x2 >= 0 && y2 < img2.height && x2 < img2.width)
                submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);
            else    //表示当前坐标不在图像second内
                submask2.at<uchar>(y + gap, x + gap) = 0;
        }
    }
    //collision表示submask1和submask2交集,roi区域可能有些区域是无效的部分(由于映射的原因),而collision(像素值为1的部分)则是图像first和图像second的真正有意义部分的重叠区域,我们是需要在collision区域内寻找接缝的
    Mat collision = (submask1 != 0) & (submask2 != 0);
    //复制submask1和submask2为unique1和unique2,并且把collision部分的像素清零
    Mat unique1 = submask1.clone(); unique1.setTo(0, collision);
    Mat unique2 = submask2.clone(); unique2.setTo(0, collision);

    Mat dist1, dist2;    //表示距离矩阵
    //分别得到unique1和unique2内为0的像素值与最近的非0值之间的L1距离,显然为0的区域肯定要比collision大
    distanceTransform(unique1 == 0, dist1, CV_DIST_L1, 3);
    distanceTransform(unique2 == 0, dist2, CV_DIST_L1, 3);
    //得到缝矩阵,dist1 < dist2成立,说明离first图像近,则seam内相应的像素为1,否则为0
    Mat seam = dist1 < dist2; 
    //遍历roi内的所有像素
    for (int y = 0; y < roi.height; ++y)
    {
        for (int x = 0; x < roi.width; ++x)
        {
            //如果seam内的像素值为1,说明collision区域内的相应像素离图像first近,所以该点的值选择图像first的像素值,因此需把mask2清零,反之把mask1清零。也就是在重叠部分,哪些区域应该属于图像first,哪些区域属于图像second。
            if (seam.at<uchar>(y + gap, x + gap))
                mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;
            else
                mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;
        }
    }
}

DpSeamFinder类利用动态规划算法寻找缝,它的构造函数为:

DpSeamFinder::DpSeamFinder(CostFunction costFunc) : costFunc_(costFunc) {}

其中CostFunction为:

enum CostFunction { COLOR, COLOR_GRAD };

它表示动态规划寻找接缝的两种不同方法,直接法和梯度法,默认是直接法。

DpSeamFinder类的find函数为:

void DpSeamFinder::find(const vector<Mat> &src, const vector<Point> &corners, vector<Mat> &masks)
{
    LOGLN("Finding seams...");
#if ENABLE_LOG
    int64 t = getTickCount();    //用于计时
#endif

    if (src.size() == 0)    //没有图像,则返回
        return;

    vector<pair<size_t, size_t> > pairs;    //表示图像对

    for (size_t i = 0; i+1 < src.size(); ++i)
        for (size_t j = i+1; j < src.size(); ++j)
            pairs.push_back(make_pair(i, j));    //每两幅图像组成一个图像对
    //根据图像位置(基于左上角坐标),对图像对进行排序
    sort(pairs.begin(), pairs.end(), ImagePairLess(src, corners));
    reverse(pairs.begin(), pairs.end());    //逆序

    for (size_t i = 0; i < pairs.size(); ++i)    //遍历图像对,
    {
        size_t i0 = pairs[i].first, i1 = pairs[i].second;
        //寻找i0和i1这两幅图像的接缝,该函数在后面有介绍
        process(src[i0], src[i1], corners[i0], corners[i1], masks[i0], masks[i1]);
    }

    LOGLN("Finding seams, time: " << ((getTickCount() - t) / getTickFrequency()) << " sec");
}

寻找两幅图像间的接缝:

void DpSeamFinder::process(
        const Mat &image1, const Mat &image2, Point tl1, Point tl2,
        Mat &mask1, Mat &mask2)
//image1和image2分别表示待处理的两幅图像
//tl1和tl2分别表示这两幅图像的左上角坐标
//mask1和mask2分别表示这两幅图像的掩码
{
    CV_Assert(image1.size() == mask1.size());    //确保图像与掩码尺寸相同
    CV_Assert(image2.size() == mask2.size());
    //intersectTl和intersectBr分别表示image1和image2的交集区域(即重叠部分)的左上角和右下角坐标
    Point intersectTl(std::max(tl1.x, tl2.x), std::max(tl1.y, tl2.y));

    Point intersectBr(std::min(tl1.x + image1.cols, tl2.x + image2.cols),
                      std::min(tl1.y + image1.rows, tl2.y + image2.rows));
    //如果if条件成立,则说明image1和image2没有重叠区域,因此退出该函数
    if (intersectTl.x >= intersectBr.x || intersectTl.y >= intersectBr.y)
        return; // there are no conflicts
    //unionTl_和unionBr_分别表示image1和image2的并集区域(即外围最大部分的矩形)的左上角和右下角坐标
    unionTl_ = Point(std::min(tl1.x, tl2.x), std::min(tl1.y, tl2.y));

    unionBr_ = Point(std::max(tl1.x + image1.cols, tl2.x + image2.cols),
                     std::max(tl1.y + image1.rows, tl2.y + image2.rows));
    //得到image1和image2的并集区域的尺寸大小
    unionSize_ = Size(unionBr_.x - unionTl_.x, unionBr_.y - unionTl_.y);
    //定义两幅图像的掩码大小,先清零
    mask1_ = Mat::zeros(unionSize_, CV_8U);
    mask2_ = Mat::zeros(unionSize_, CV_8U);
    //tmp为mask1_中image1的区域
    Mat tmp = mask1_(Rect(tl1.x - unionTl_.x, tl1.y - unionTl_.y, mask1.cols, mask1.rows));
    mask1.copyTo(tmp);    //把image1的掩码mask1赋值给mask1_
    //tmp为mask2_中image2的区域
    tmp = mask2_(Rect(tl2.x - unionTl_.x, tl2.y - unionTl_.y, mask2.cols, mask2.rows));
    mask2.copyTo(tmp);    //把image2的掩码mask2赋值给mask2_

    // find both images contour masks
    //在并集中分别得到边界掩码contour1mask_和contour2mask_
    contour1mask_ = Mat::zeros(unionSize_, CV_8U);    //先清零
    contour2mask_ = Mat::zeros(unionSize_, CV_8U);
    //遍历并集区域
    for (int y = 0; y < unionSize_.height; ++y)
    {
        for (int x = 0; x < unionSize_.width; ++x)
        {
            if (mask1_(y, x) &&
                ((x == 0 || !mask1_(y, x-1)) || (x == unionSize_.width-1 || !mask1_(y, x+1)) ||
                 (y == 0 || !mask1_(y-1, x)) || (y == unionSize_.height-1 || !mask1_(y+1, x))))
            {
                contour1mask_(y, x) = 255;    //得到image1的边界掩码
            }

            if (mask2_(y, x) &&
                ((x == 0 || !mask2_(y, x-1)) || (x == unionSize_.width-1 || !mask2_(y, x+1)) ||
                 (y == 0 || !mask2_(y-1, x)) || (y == unionSize_.height-1 || !mask2_(y+1, x))))
            {
                contour2mask_(y, x) = 255;    //得到image2的边界掩码
            }
        }
    }
    //以下三个函数在后面都有介绍
    findComponents();

    findEdges();

    resolveConflicts(image1, image2, tl1, tl2, mask1, mask2);
}

利用漫水填充法分割图像寻找组件,不同的组件对应于图像的不同区域:

void DpSeamFinder::findComponents()
{
    // label all connected components and get information about them

    ncomps_ = 0;    //表示组件的数量
    labels_.create(unionSize_);    //定义标签的大小
    states_.clear();    //状态清空
    tls_.clear();    //tls表示各种组件的左上角坐标
    brs_.clear();    //brs表示各种组件的右下角坐标
    contours_.clear();    //组件区域的边界
    //遍历两幅图像的并集区域,为labels_赋值
    for (int y = 0; y < unionSize_.height; ++y)
    {
        for (int x = 0; x < unionSize_.width; ++x)
        {
            if (mask1_(y, x) && mask2_(y, x))    //表示两幅图像的公共交集的部分
                labels_(y, x) = numeric_limits<int>::max();
            else if (mask1_(y, x))    //表示只有image1的部分
                labels_(y, x) = numeric_limits<int>::max()-1;
            else if (mask2_(y, x))    //表示只有image2的部分
                labels_(y, x) = numeric_limits<int>::max()-2;
            else    //表示没有任何图像信息
                labels_(y, x) = 0;
        }
    }
    //再次遍历两幅图像的并集区域,
    for (int y = 0; y < unionSize_.height; ++y)
    {
        for (int x = 0; x < unionSize_.width; ++x)
        {
            //表示当前像素是并集区域内有图像信息的
            if (labels_(y, x) >= numeric_limits<int>::max()-2)
            {
                if (labels_(y, x) == numeric_limits<int>::max())    //交集部分
                    states_.push_back(INTERS);    //状态赋值
                else if (labels_(y, x) == numeric_limits<int>::max()-1)    //只有image1部分
                    states_.push_back(FIRST);    //状态赋值
                else if (labels_(y, x) == numeric_limits<int>::max()-2)    //只有image2部分
                    states_.push_back(SECOND);    //状态赋值
                //利用漫水填充算法,从当前像素点出发,填充++ncomps_值
                floodFill(labels_, Point(x, y), ++ncomps_);
                //存入当前像素点,表示当前组件的左上角坐标
                tls_.push_back(Point(x, y)); 
                //表示当前组件的右下角坐标,+1的含义是用于区分左上角坐标
                brs_.push_back(Point(x+1, y+1)); 
                //因为已经得到了一个组件,所以这时需要在contours_内预留一段空间,用于存储当前组件的边界像素
                contours_.push_back(vector<Point>()); 
            }

            if (labels_(y, x))    //表示当前像素属于某幅图像
            {
                int l = labels_(y, x);    //当前标签
                int ci = l-1;    //标签值减1,表示当前组件

                //确定当前组件的左上角和右下角坐标,在双重for循环体内,不断进入该if语句,所以实现了当前组件的左上角和右下角坐标的不断扩展,最终得到准确的值
                tls_[ci].x = std::min(tls_[ci].x, x);
                tls_[ci].y = std::min(tls_[ci].y, y);
                brs_[ci].x = std::max(brs_[ci].x, x+1);
                brs_[ci].y = std::max(brs_[ci].y, y+1);
                //if条件成立,说明当前像素为当前组件的边界
                if ((x == 0 || labels_(y, x-1) != l) || (x == unionSize_.width-1 || labels_(y, x+1) != l) ||
                    (y == 0 || labels_(y-1, x) != l) || (y == unionSize_.height-1 || labels_(y+1, x) != l))
                {
                    contours_[ci].push_back(Point(x, y));    //存入当前组件的边界像素
                }
            }
        }
    }
}

得到组件间的边缘:

void DpSeamFinder::findEdges()
{
    // find edges between components
    //wedges表示边缘权值,即边缘像素的数量,pair中的两个参数表示两个组件的索引
    map<pair<int, int>, int> wedges; // weighted edges
    //遍历组件,初始化wedges为0
    for (int ci = 0; ci < ncomps_-1; ++ci)
    {
        for (int cj = ci+1; cj < ncomps_; ++cj)
        {
            wedges[make_pair(ci, cj)] = 0;
            wedges[make_pair(cj, ci)] = 0;
        }
    }

    for (int ci = 0; ci < ncomps_; ++ci)    //遍历组件
    {
        for (size_t i = 0; i < contours_[ci].size(); ++i)    //遍历当前组件的边界
        {
            int x = contours_[ci][i].x;    //边缘像素坐标
            int y = contours_[ci][i].y;
            int l = ci + 1;    //当前组件的标签
            //if条件成立,表示当前像素为左侧边缘,此时当前组件与其左侧组件间的wedges权值加1
            if (x > 0 && labels_(y, x-1) && labels_(y, x-1) != l)
            {
                wedges[make_pair(ci, labels_(y, x-1)-1)]++; 
                wedges[make_pair(labels_(y, x-1)-1, ci)]++; 
            }
            //if条件成立,表示当前像素为上侧边缘,此时当前组件与其上侧组件间的wedges权值加1
            if (y > 0 && labels_(y-1, x) && labels_(y-1, x) != l)
            {
                wedges[make_pair(ci, labels_(y-1, x)-1)]++; 
                wedges[make_pair(labels_(y-1, x)-1, ci)]++; 
            }
            //if条件成立,表示当前像素为右侧边缘,此时当前组件与其右侧组件间的wedges权值加1
            if (x < unionSize_.width-1 && labels_(y, x+1) && labels_(y, x+1) != l)
            {
                wedges[make_pair(ci, labels_(y, x+1)-1)]++;
                wedges[make_pair(labels_(y, x+1)-1, ci)]++;
            }
            //if条件成立,表示当前像素为下侧边缘,此时当前组件与其下侧组件间的wedges权值加1
            if (y < unionSize_.height-1 && labels_(y+1, x) && labels_(y+1, x) != l)
            {
                wedges[make_pair(ci, labels_(y+1, x)-1)]++;
                wedges[make_pair(labels_(y+1, x)-1, ci)]++;
            }
        }
    }
    //edges_表示两个组件是相邻的,因为它们之间有边界
    edges_.clear();    //清空
    //遍历wedges
    for (int ci = 0; ci < ncomps_-1; ++ci)
    {
        for (int cj = ci+1; cj < ncomps_; ++cj)
        {
            //得到组件ci和cj之间的wedges
            map<pair<int, int>, int>::iterator itr = wedges.find(make_pair(ci, cj));
            if (itr != wedges.end() && itr->second > 0)    //表示ci和cj是相邻的
                edges_.insert(itr->first);    //ci和cj存入edges中
            //得到组件cj和ci之间的wedges
            itr = wedges.find(make_pair(cj, ci));
            if (itr != wedges.end() && itr->second > 0)    //表示cj和ci是相邻的
                edges_.insert(itr->first);    //cj和ci存入edges中
        }
    }
}

具体计算接缝的部分:

void DpSeamFinder::resolveConflicts(
        const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2)
{
    if (costFunc_ == COLOR_GRAD)    //梯度法
        computeGradients(image1, image2);    //调用computeGradients,计算梯度

    // resolve conflicts between components

    bool hasConflict = true;    //标识变量
    while (hasConflict)
    {
        int c1 = 0, c2 = 0;
        hasConflict = false;    //变换标识
        //遍历edges_,得到相连组件
        for (set<pair<int, int> >::iterator itr = edges_.begin(); itr != edges_.end(); ++itr)
        {
            c1 = itr->first;    //得到连接边缘的一个组件
            c2 = itr->second;    //得到连接边缘的另一个组件
            //c1有交集部分,并且它不是与c2组件的交集
            if ((states_[c1] & INTERS) && (states_[c1] & (~INTERS)) != states_[c2])
            {
                hasConflict = true;    //赋值为true
                break;    //退出for循环
            }
        }

        if (hasConflict)
        {
            int l1 = c1+1, l2 = c2+1;    //表示c1和c2的标签
            //表示c1只有一个邻近组件,说明c1不是交集,不需要在该组件寻找接缝线
            if (hasOnlyOneNeighbor(c1)) 
            {
                // if the first components has only one adjacent component
                //遍历c1区域,把标签为l1的像素改为l2,即合并两个组件
                for (int y = tls_[c1].y; y < brs_[c1].y; ++y)
                    for (int x = tls_[c1].x; x < brs_[c1].x; ++x)
                        if (labels_(y, x) == l1)
                            labels_(y, x) = l2;
                //改变组件c1的状态
                states_[c1] = states_[c2] == FIRST ? SECOND : FIRST;
            }
            //表示c1有不止一个邻近组件,说明c1是交集部分,要在该组件寻找接缝线
            else
            {
                // if the first component has more than one adjacent component

                Point p1, p2;    //表示接缝的起点和终点
                //利用getSeamTips函数得到p1和p2,该函数在后面给出介绍
                if (getSeamTips(c1, c2, p1, p2))
                {
                    vector<Point> seam;    //表示接缝
                    bool isHorizontalSeam;    //表示接缝的基本走向
                    //利用estimateSeam函数得到接缝seam,该函数在后面给出介绍
                    if (estimateSeam(image1, image2, tl1, tl2, c1, p1, p2, seam, isHorizontalSeam))
                        //更新标签,该函数在后面给出介绍
                        updateLabelsUsingSeam(c1, c2, seam, isHorizontalSeam);
                }
                //重新为c1的状态赋值
                states_[c1] = states_[c2] == FIRST ? INTERS_SECOND : INTERS_FIRST;
            }

            const int c[] = {c1, c2};    //表示组件
            const int l[] = {l1, l2};    //表示标签

            for (int i = 0; i < 2; ++i)    //遍历c1和c2两个组件
            {
                // update information about the (i+1)-th component
                //得到当前组件的左上角和右下角坐标
                int x0 = tls_[c[i]].x, x1 = brs_[c[i]].x; 
                int y0 = tls_[c[i]].y, y1 = brs_[c[i]].y;
                //重新赋值
                tls_[c[i]] = Point(numeric_limits<int>::max(), numeric_limits<int>::max());
                brs_[c[i]] = Point(numeric_limits<int>::min(), numeric_limits<int>::min());
                contours_[c[i]].clear();    //当前组件的边缘像素清零

                for (int y = y0; y < y1; ++y)    //遍历当前组件
                {
                    for (int x = x0; x < x1; ++x)
                    {
                        if (labels_(y, x) == l[i])
                        {
                            //更新当前组件的区域面积
                            tls_[c[i]].x = std::min(tls_[c[i]].x, x);
                            tls_[c[i]].y = std::min(tls_[c[i]].y, y);
                            brs_[c[i]].x = std::max(brs_[c[i]].x, x+1);
                            brs_[c[i]].y = std::max(brs_[c[i]].y, y+1);

                            if ((x == 0 || labels_(y, x-1) != l[i]) || (x == unionSize_.width-1 || labels_(y, x+1) != l[i]) ||
                                (y == 0 || labels_(y-1, x) != l[i]) || (y == unionSize_.height-1 || labels_(y+1, x) != l[i]))
                            {
                                //给出当前组件的边缘像素
                                contours_[c[i]].push_back(Point(x, y)); 
                            }
                        }
                    }
                }
            }

            // remove edges
            //删除c1和c2所形成的边缘
            edges_.erase(make_pair(c1, c2));
            edges_.erase(make_pair(c2, c1));
        }
    }

    // update masks
    //更新掩码
    int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;    //图像1的左上角坐标
    int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;    //图像2的左上角坐标
    //遍历mask2,更新掩码2
    for (int y = 0; y < mask2.rows; ++y)
    {
        for (int x = 0; x < mask2.cols; ++x)
        {
             int l = labels_(y - dy2, x - dx2);    //当前像素的标签
             //if成立,说明当前像素应该用图像1的内容,所以掩码2清零
             if (l > 0 && (states_[l-1] & FIRST) && mask1.at<uchar>(y - dy2 + dy1, x - dx2 + dx1))
                mask2.at<uchar>(y, x) = 0;
        }
    }
    //遍历mask1,更新掩码1
    for (int y = 0; y < mask1.rows; ++y)
    {
        for (int x = 0; x < mask1.cols; ++x)
        {
             int l = labels_(y - dy1, x - dx1);    //当前像素的标签
             //if成立,说明当前像素应该用图像2的内容,所以掩码1清零
             if (l > 0 && (states_[l-1] & SECOND) && mask2.at<uchar>(y - dy1 + dy2, x - dx1 + dx2))
                mask1.at<uchar>(y, x) = 0;
        }
    }
}

计算彩色图像image1和image2的水平和垂直梯度:

void DpSeamFinder::computeGradients(const Mat &image1, const Mat &image2)
{
    //确保image1和image2是彩色图像
    CV_Assert(image1.channels() == 3 || image1.channels() == 4);
    CV_Assert(image2.channels() == 3 || image2.channels() == 4);
    CV_Assert(costFunction() == COLOR_GRAD);    //确保是梯度法

    Mat gray;
    //把彩色图像image1转换为灰度图像
    if (image1.channels() == 3)
        cvtColor(image1, gray, CV_BGR2GRAY);
    else if (image1.channels() == 4)
        cvtColor(image1, gray, CV_BGRA2GRAY);

    Sobel(gray, gradx1_, CV_32F, 1, 0);    //得到image1的水平梯度gradx1_
    Sobel(gray, grady1_, CV_32F, 0, 1);    //得到image1的垂直梯度grady1_
    //把彩色图像image2转换为灰度图像
    if (image2.channels() == 3)
        cvtColor(image2, gray, CV_BGR2GRAY);
    else if (image2.channels() == 4)
        cvtColor(image2, gray, CV_BGRA2GRAY);

    Sobel(gray, gradx2_, CV_32F, 1, 0);    //得到image2的水平梯度gradx2_
    Sobel(gray, grady2_, CV_32F, 0, 1);    //得到image2的垂直梯度grady2_
}

计算接缝的起点和终点:

bool DpSeamFinder::getSeamTips(int comp1, int comp2, Point &p1, Point &p2)
//comp1和comp2分别表示相邻的组件
//p1和p2分别表示得到返回comp1中,聚类最远的两个聚类中的像素点,即接缝的起点和终点
//返回为true,则说明得到了p1和p2,否则返回false
{
    CV_Assert(states_[comp1] & INTERS);    //确保comp1为图像间的重叠部分

    // find special points

    vector<Point> specialPoints;    //表示一些特殊的点,即靠近其他边界的点
    int l2 = comp2+1;    //表示comp2的标签

    for (size_t i = 0; i < contours_[comp1].size(); ++i)    //遍历comp1的边缘像素
    {
        int x = contours_[comp1][i].x;    //得到当前边缘像素的坐标
        int y = contours_[comp1][i].y;
        //if条件成立,说明当前像素临近并集的边界,并且靠近comp2
        if (closeToContour(y, x, contour1mask_) &&
            closeToContour(y, x, contour2mask_) &&
            ((x > 0 && labels_(y, x-1) == l2) ||
             (y > 0 && labels_(y-1, x) == l2) ||
             (x < unionSize_.width-1 && labels_(y, x+1) == l2) ||
             (y < unionSize_.height-1 && labels_(y+1, x) == l2)))
        {
            specialPoints.push_back(Point(x, y));    //存储这些特殊的点
        }
    }
    //特殊点数量太少,不能形成聚类,则直接返回
    if (specialPoints.size() < 2)
        return false;

    // find clusters

    vector<int> labels;
    //把specialPoints中的相距不大于10个单位的点聚成一类,并赋予相应的标签labels
    cv::partition(specialPoints, labels, ClosePoints(10));
    //得到最大聚类的像素数量
    int nlabels = *max_element(labels.begin(), labels.end()) + 1;
    if (nlabels < 2)    //聚类中的像素数量太少,无法得到中心像素,则直接返回
        return false;

    vector<Point> sum(nlabels);    //表示各个聚类中像素点坐标值之和
    vector<vector<Point> > points(nlabels);    //用于存储各个聚类的像素

    for (size_t i = 0; i < specialPoints.size(); ++i)    //遍历specialPoints
    {
        sum[labels[i]] += specialPoints[i];
        points[labels[i]].push_back(specialPoints[i]);
    }

    // select two most distant clusters

    int idx[2] = {-1,-1};    //表示距离最大的两个聚类的索引
    //表示两个聚类间的最大距离,先初始化为最小值
    double maxDist = -numeric_limits<double>::max();
    //两两聚类遍历,得到距离最大的两个聚类
    for (int i = 0; i < nlabels-1; ++i)
    {
        for (int j = i+1; j < nlabels; ++j)
        {
            //分别表示聚类1和聚类2的特殊点的数量
            double size1 = static_cast<double>(points[i].size()), size2 = static_cast<double>(points[j].size());
            //分别表示聚类1和聚类2的横、纵坐标的均值,代表聚类的中心
            double cx1 = cvRound(sum[i].x / size1), cy1 = cvRound(sum[i].y / size1);
            double cx2 = cvRound(sum[j].x / size2), cy2 = cvRound(sum[j].y / size1);
            //聚类i和聚类j间的距离
            double dist = (cx1 - cx2) * (cx1 - cx2) + (cy1 - cy2) * (cy1 - cy2);
            if (dist > maxDist)
            {
                maxDist = dist;    //更新最大距离
                idx[0] = i;    //更新两个聚类
                idx[1] = j;
            }
        }
    }

    // select two points closest to the clusters' centers

    Point p[2];
    //遍历距离最大的那两个聚类,得到聚类内离中心最近的点
    for (int i = 0; i < 2; ++i)
    {
        double size = static_cast<double>(points[idx[i]].size());    //聚类内的特殊点的数量
        double cx = cvRound(sum[idx[i]].x / size);    //聚类的横坐标的均值
        double cy = cvRound(sum[idx[i]].y / size);    //聚类的纵坐标的均值

        size_t closest = points[idx[i]].size();
        double minDist = numeric_limits<double>::max();    //先设置一个最大值

        for (size_t j = 0; j < points[idx[i]].size(); ++j)    //遍历聚类内的特殊点
        {
            //得到当前特殊点与该聚类中心的距离
            double dist = (points[idx[i]][j].x - cx) * (points[idx[i]][j].x - cx) +
                          (points[idx[i]][j].y - cy) * (points[idx[i]][j].y - cy);
            if (dist < minDist) 
            {
                minDist = dist;    //更新最小距离
                closest = j;    //更新聚类索引
            }
        }

        p[i] = points[idx[i]][closest];    //得到该点
    }

    p1 = p[0];    //得到这两个像素点
    p2 = p[1];
    return true;
}

计算得到接缝:

bool DpSeamFinder::estimateSeam(
        const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp,
        Point p1, Point p2, vector<Point> &seam, bool &isHorizontal)
//image1和image2分别表示重叠的两幅图像
//tl1和tl2分别表示这两幅图像在全景图像中的左上角的坐标
//comp表示这两幅图像的重叠部分,即交集组件
//p1和p2分别表示接缝的起点和终点
//seam表示得到的接缝
//isHorizontal表示接缝的基本走向是否为水平
//如果得到了接缝,该函数返回true,否则返回false
{
    CV_Assert(states_[comp] & INTERS);    //确保comp为交集组件

    Mat_<float> costV, costH;    //表示垂直和水平的代价
    //计算两幅图像间重叠区域的水平和垂直的代价值,该函数在后面给出介绍
    computeCosts(image1, image2, tl1, tl2, comp, costV, costH);

    Rect roi(tls_[comp], brs_[comp]);    //定义重叠区域的矩形形式
    Point src = p1 - roi.tl();    //src表示p1点在roi的绝对位置
    Point dst = p2 - roi.tl();    //dst表示p2点在roi的绝对位置
    int l = comp+1;    //表示comp1的标签

    // estimate seam direction

    bool swapped = false;    //定义一个标签,表示src和dst交换
    //由src和dst构成的矩形如果是宽大于高,则isHorizontal为true,否则为false
    isHorizontal = std::abs(dst.x - src.x) > std::abs(dst.y - src.y);

    if (isHorizontal)    //宽大于高
    {
        if (src.x > dst.x)    //比较横坐标
        {
            std::swap(src, dst);    //交换,使src在dst的左边
            swapped = true;
        }
    }
    else if (src.y > dst.y)    //高大于宽,则比较纵坐标
    {
        swapped = true;
        std::swap(src, dst);    //交换,使src在dst的上边
    }

    // find optimal control

    Mat_<uchar> control = Mat::zeros(roi.size(), CV_8U);    //表示控制量,即接缝的走向
    Mat_<uchar> reachable = Mat::zeros(roi.size(), CV_8U);    //表示已遍历到该像素
    Mat_<float> cost = Mat::zeros(roi.size(), CV_32F);    //表示代价值,即累积最小误差

    reachable(src) = 1;    //从src开始遍历
    cost(src) = 0.f;

    int nsteps;    //表示步长
    pair<float, int> steps[3];    //表示接缝的走向,并计算式89中min中的三个元素

    if (isHorizontal)    //宽大于高,接缝的走向基本上是从左向右
    {
        for (int x = src.x+1; x <= dst.x; ++x)    //遍历重叠部分
        {
            for (int y = 0; y < roi.height; ++y)
            {
                // seam follows along upper side of pixels

                nsteps = 0;    //每次循环,步长都要清零

                if (labels_(y + roi.y, x + roi.x) == l)    //当前像素的标签为l
                {
                    if (reachable(y, x-1))
                        steps[nsteps++] = make_pair(cost(y, x-1) + costH(y, x-1), 1);
                    if (y > 0 && reachable(y-1, x-1))
                        steps[nsteps++] = make_pair(cost(y-1, x-1) + costH(y-1, x-1) + costV(y-1, x), 2);
                    if (y < roi.height-1 && reachable(y+1, x-1))
                        steps[nsteps++] = make_pair(cost(y+1, x-1) + costH(y+1, x-1) + costV(y, x), 3);
                }

                if (nsteps)    //表示该次循环,已经得到了steps变量
                {
                    //在steps数组中,得到最小值,即式89
                    pair<float, int> opt = *min_element(steps, steps + nsteps);
                    cost(y, x) = opt.first;    //当前像素的代价值
                    control(y, x) = (uchar)opt.second;    //当前像素的控制量
                    reachable(y, x) = 255;    //表示已遍历到该点
                }
            }
        }
    }
    else    //高大于宽,接缝的走向基本上是从上向下
    {
        for (int y = src.y+1; y <= dst.y; ++y)    //遍历重叠部分
        {
            for (int x = 0; x < roi.width; ++x)
            {
                // seam follows along left side of pixels

                nsteps = 0;    //每次循环,步长都要清零

                if (labels_(y + roi.y, x + roi.x) == l)    //当前像素的标签为l
                {
                    if (reachable(y-1, x))
                        steps[nsteps++] = make_pair(cost(y-1, x) + costV(y-1, x), 1);
                    if (x > 0 && reachable(y-1, x-1))
                        steps[nsteps++] = make_pair(cost(y-1, x-1) + costV(y-1, x-1) + costH(y, x-1), 2);
                    if (x < roi.width-1 && reachable(y-1, x+1))
                        steps[nsteps++] = make_pair(cost(y-1, x+1) + costV(y-1, x+1) + costH(y, x), 3);
                }

                if (nsteps)    //表示该次循环,已经得到了steps变量
                {
                    //在steps数组中,得到最小值,即式89
                    pair<float, int> opt = *min_element(steps, steps + nsteps);
                    cost(y, x) = opt.first;    //当前像素的代价值
                    control(y, x) = (uchar)opt.second;    //当前像素的控制量
                    reachable(y, x) = 255;    //表示已遍历到该点
                }
            }
        }
    }

    if (!reachable(dst))    //没有遍历到dst点(终点),则直接退出
        return false;

    // restore seam

    Point p = dst;    //接缝的终点
    seam.clear();    //接缝清零
    seam.push_back(p + roi.tl());    //终点放入seam中

    if (isHorizontal)    //宽大于高
    {
        for (; p.x != src.x; seam.push_back(p + roi.tl()))
        {
            //根据控制量,得到接缝的坐标,并把它存放入seam内
            if (control(p) == 2) p.y--;
            else if (control(p) == 3) p.y++;
            p.x--;
        }
    }
    else    //高大于宽
    {
        for (; p.y != src.y; seam.push_back(p + roi.tl()))
        {
            //根据控制量,得到接缝的坐标,并把它存放入seam内
            if (control(p) == 2) p.x--;
            else if (control(p) == 3) p.x++;
            p.y--;
        }
    }

    if (!swapped)    //确保起点为p1,终点为p2
        reverse(seam.begin(), seam.end());

    CV_Assert(seam.front() == p1);    //确保起点为p1,终点为p2
    CV_Assert(seam.back() == p2);
    return true;
}

计算代价的函数,程序并不是直接计算重叠区域相对像素之间的差值平方和,而是根据接缝线的走向,计算两者之间水平方向或垂直方向上相差一个像素之间的差值平方和,即式90,因此代价值分为水平值和垂直值两类的:

void DpSeamFinder::computeCosts(
        const Mat &image1, const Mat &image2, Point tl1, Point tl2,
        int comp, Mat_<float> &costV, Mat_<float> &costH)
{
    CV_Assert(states_[comp] & INTERS);    //确保comp为交集部分

    // compute costs

    float (*diff)(const Mat&, int, int, const Mat&, int, int) = 0;    //定义一个函数指针
    //根据图像类型的不同,diff函数指针指向不同的函数,函数的本质都是比较两幅图像中相对应元素之间的差值,即红、绿、蓝三通道强度差值平方之和
    if (image1.type() == CV_32FC3 && image2.type() == CV_32FC3)
        diff = diffL2Square3<float>;    //三通道
    else if (image1.type() == CV_8UC3 && image2.type() == CV_8UC3)
        diff = diffL2Square3<uchar>;    //三通道
    else if (image1.type() == CV_32FC4 && image2.type() == CV_32FC4)
        diff = diffL2Square4<float>;    //四通道
    else if (image1.type() == CV_8UC4 && image2.type() == CV_8UC4)
        diff = diffL2Square4<uchar>;    //四通道
    else
        CV_Error(CV_StsBadArg, "both images must have CV_32FC3(4) or CV_8UC3(4) type");

    int l = comp+1;    //表示标签
    Rect roi(tls_[comp], brs_[comp]);    //得到comp的矩形形式
    //得到image1和image2左上角的相对坐标
    int dx1 = unionTl_.x - tl1.x, dy1 = unionTl_.y - tl1.y;
    int dx2 = unionTl_.x - tl2.x, dy2 = unionTl_.y - tl2.y;
    //定义一个常数,用来表示无效的值
    const float badRegionCost = normL2(Point3f(255.f, 255.f, 255.f),
                                       Point3f(0.f, 0.f, 0.f));

    costV.create(roi.height, roi.width+1);    //创建costV的大小

    for (int y = roi.y; y < roi.br().y; ++y)    //遍历roi区域
    {
        for (int x = roi.x; x < roi.br().x+1; ++x)
        {
            if (labels_(y, x) == l && x > 0 && labels_(y, x-1) == l)    //当前像素的标签为l
            {
                //在水平方向,计算式90
                float costColor = (diff(image1, y + dy1, x + dx1 - 1, image2, y + dy2, x + dx2) +
                                   diff(image1, y + dy1, x + dx1, image2, y + dy2, x + dx2 - 1)) / 2;
                if (costFunc_ == COLOR)    //直接法
                    costV(y - roi.y, x - roi.x) = costColor;
                else if (costFunc_ == COLOR_GRAD)    //梯度法
                {
                    //得到式91的分母部分
                    float costGrad = std::abs(gradx1_(y + dy1, x + dx1)) + std::abs(gradx1_(y + dy1, x + dx1 - 1)) +
                                     std::abs(gradx2_(y + dy2, x + dx2)) + std::abs(gradx2_(y + dy2, x + dx2 - 1)) + 1.f;
                    costV(y - roi.y, x - roi.x) = costColor / costGrad;    //式91
                }
            }
            else
                costV(y - roi.y, x - roi.x) = badRegionCost;    //无效的值
        }
    }

    costH.create(roi.height+1, roi.width);    //创建costV的大小

    for (int y = roi.y; y < roi.br().y+1; ++y)    //遍历roi区域
    {
        for (int x = roi.x; x < roi.br().x; ++x)
        {
            if (labels_(y, x) == l && y > 0 && labels_(y-1, x) == l)    //当前像素的标签为l
            {
                //在垂直方向,计算式90
                float costColor = (diff(image1, y + dy1 - 1, x + dx1, image2, y + dy2, x + dx2) +
                                   diff(image1, y + dy1, x + dx1, image2, y + dy2 - 1, x + dx2)) / 2;
                if (costFunc_ == COLOR)    //直接法
                    costH(y - roi.y, x - roi.x) = costColor;
                else if (costFunc_ == COLOR_GRAD)        //梯度法
                {
                    //得到式91的分母部分
                    float costGrad = std::abs(grady1_(y + dy1, x + dx1)) + std::abs(grady1_(y + dy1 - 1, x + dx1)) +
                                     std::abs(grady2_(y + dy2, x + dx2)) + std::abs(grady2_(y + dy2 - 1, x + dx2)) + 1.f;
                    costH(y - roi.y, x - roi.x) = costColor / costGrad;    //式91
                }
            }
            else
                costH(y - roi.y, x - roi.x) = badRegionCost;    //无效的值
        }
    }
}

利用接缝来进行更新标签:

void DpSeamFinder::updateLabelsUsingSeam(
        int comp1, int comp2, const vector<Point> &seam, bool isHorizontalSeam)
{
    //表示comp1的掩码,先清零
    Mat_<int> mask = Mat::zeros(brs_[comp1].y - tls_[comp1].y,
                                brs_[comp1].x - tls_[comp1].x, CV_32S);
    //把comp1中的边缘的掩码赋值为255
    for (size_t i = 0; i < contours_[comp1].size(); ++i)
        mask(contours_[comp1][i] - tls_[comp1]) = 255;
    //把comp1中的接缝的掩码赋值为255
    for (size_t i = 0; i < seam.size(); ++i)
        mask(seam[i] - tls_[comp1]) = 255;

    // find connected components after seam carving

    int l1 = comp1+1, l2 = comp2+1;    //得到两个组件的标签

    int ncomps = 0;    //表示组件数量
    //在mask1中,对除了边缘和接缝以为的区域利用漫水填充算法进行分割
    for (int y = 0; y < mask.rows; ++y)
        for (int x = 0; x < mask.cols; ++x)
            if (!mask(y, x) && labels_(y + tls_[comp1].y, x + tls_[comp1].x) == l1)
                floodFill(mask, Point(x, y), ++ncomps);

    for (size_t i = 0; i < contours_[comp1].size(); ++i)    //遍历comp1组件边缘像素
    {
        int x = contours_[comp1][i].x - tls_[comp1].x;    //相对坐标
        int y = contours_[comp1][i].y - tls_[comp1].y;

        bool ok = false;    //标识变量
        static const int dx[] = {-1, +1, 0, 0, -1, +1, -1, +1};    //表示8邻域
        static const int dy[] = {0, 0, -1, +1, -1, -1, +1, +1};

        for (int j = 0; j < 8; ++j)    //遍历当前像素的8邻域
        {
            int c = x + dx[j];
            int r = y + dy[j];
            //表示当前像素的8邻域属于由上一步漫水填充算法得到的分割区域
            if (c >= 0 && c < mask.cols && r >= 0 && r < mask.rows &&
                mask(r, c) && mask(r, c) != 255)
            {
                ok = true;    //赋值
                mask(y, x) = mask(r, c);    //属于同一个分割区域
            }
        }

        if (!ok)
            mask(y, x) = 0;    //表示当前像素为掩码像素
    }

    if (isHorizontalSeam)    //宽大于高
    {
        for (size_t i = 0; i < seam.size(); ++i)    //遍历接缝
        {
            int x = seam[i].x - tls_[comp1].x;    //相对坐标
            int y = seam[i].y - tls_[comp1].y;
            //当前像素的下一行像素的掩码不为0或255
            if (y < mask.rows-1 && mask(y+1, x) && mask(y+1, x) != 255)
                mask(y, x) = mask(y+1, x);    //赋值
            else
                mask(y, x) = 0;
        }
    }
    else    //高大于宽
    {
        for (size_t i = 0; i < seam.size(); ++i)    //遍历接缝
        {
            int x = seam[i].x - tls_[comp1].x;    //相对坐标
            int y = seam[i].y - tls_[comp1].y;
            //当前像素的右边像素的掩码不为0或255
            if (x < mask.cols-1 && mask(y, x+1) && mask(y, x+1) != 255)
                mask(y, x) = mask(y, x+1);    //赋值
            else
                mask(y, x) = 0;
        }
    }

    // find new components connected with the second component and
    // with other components except the ones we are working with

    map<int, int> connect2;    //表示与第2个组件相邻
    map<int, int> connectOther;    //表示与其他组件相邻

    for (int i = 1; i <= ncomps; ++i)    //遍历分割区域
    {
        connect2.insert(make_pair(i, 0));    //初始化
        connectOther.insert(make_pair(i, 0));
    }

    for (size_t i = 0; i < contours_[comp1].size(); ++i)    //遍历comp1组件的边缘像素
    {
        int x = contours_[comp1][i].x;    //当前像素的相对坐标
        int y = contours_[comp1][i].y;
        //当前像素的4邻域范围内只要有一个像素的标签为l2
        if ((x > 0 && labels_(y, x-1) == l2) ||
            (y > 0 && labels_(y-1, x) == l2) ||
            (x < unionSize_.width-1 && labels_(y, x+1) == l2) ||
            (y < unionSize_.height-1 && labels_(y+1, x) == l2))
        {
            //记录该像素,并且数量累计
            connect2[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;
        }
        //当前像素的4邻域范围内只要有一个像素的标签为其他值
        if ((x > 0 && labels_(y, x-1) != l1 && labels_(y, x-1) != l2) ||
            (y > 0 && labels_(y-1, x) != l1 && labels_(y-1, x) != l2) ||
            (x < unionSize_.width-1 && labels_(y, x+1) != l1 && labels_(y, x+1) != l2) ||
            (y < unionSize_.height-1 && labels_(y+1, x) != l1 && labels_(y+1, x) != l2))
        {
            //记录该像素,并且数量累计
            connectOther[mask(y - tls_[comp1].y, x - tls_[comp1].x)]++;
        }
    }

    vector<int> isAdjComp(ncomps + 1, 0);    //表示邻近组件
    //遍历connect2内的像素
    for (map<int, int>::iterator itr = connect2.begin(); itr != connect2.end(); ++itr)
    {
        //comp1组件内边缘像素的数量
        double len = static_cast<double>(contours_[comp1].size());
        //通过比较connect2和connectOther的数量来为isAdjComp赋值
        isAdjComp[itr->first] = itr->second / len > 0.05 && connectOther.find(itr->first)->second / len < 0.1;
    }

    // update labels
    //更新标签
    for (int y = 0; y < mask.rows; ++y)
        for (int x = 0; x < mask.cols; ++x)
            if (mask(y, x) && isAdjComp[mask(y, x)])
                labels_(y + tls_[comp1].y, x + tls_[comp1].x) = l2;
}

GraphCutSeamFinder类为图割法实现类,它的构造函数为:

GraphCutSeamFinder::GraphCutSeamFinder(int cost_type, float terminal_cost, float bad_region_penalty)
    : impl_(new Impl(cost_type, terminal_cost, bad_region_penalty)) {}
//cost_type表示图割法的类型,直接法还是梯度法,默认为梯度法
//terminal_cost表示终端节点与普通节点之间的初始边权值,默认值为10000
//bad_region_penalty表示图中无效边的权值,默认值为1000

它主要实例化了impl_类为Impl,而GraphCutSeamFinder类中的find函数为:

void GraphCutSeamFinder::find(const vector<Mat> &src, const vector<Point> &corners,
                              vector<Mat> &masks)
{
    impl_->find(src, corners, masks);
}

所以对于GraphCutSeamFinder类,重点应该了解它内部的Impl类。

Impl类的find函数:

void GraphCutSeamFinder::Impl::find(const vector<Mat> &src, const vector<Point> &corners,
                                    vector<Mat> &masks)
{
    // Compute gradients
    //计算梯度
    dx_.resize(src.size());    //表示水平梯度
    dy_.resize(src.size());    //表示垂直梯度
    Mat dx, dy;    //表示当前图像的水平梯度和垂直梯度
    for (size_t i = 0; i < src.size(); ++i)    //遍历所有待拼接的图像
    {
        CV_Assert(src[i].channels() == 3);    //确保图像是三通道的彩色图像
        Sobel(src[i], dx, CV_32F, 1, 0);    //得到当前图像的红绿蓝各个通道的水平梯度dx
        Sobel(src[i], dy, CV_32F, 0, 1);    //得到当前图像的红绿蓝各个通道的垂直梯度dy
        dx_[i].create(src[i].size(), CV_32F);    //定义大小
        dy_[i].create(src[i].size(), CV_32F);    //定义大小
        for (int y = 0; y < src[i].rows; ++y)    //遍历当前图像的行
        {
            const Point3f* dx_row = dx.ptr<Point3f>(y);    //当前图像水平梯度行指针
            const Point3f* dy_row = dy.ptr<Point3f>(y);    //当前图像垂直梯度行指针
            float* dx_row_ = dx_[i].ptr<float>(y);    //所有图像的水平梯度行指针
            float* dy_row_ = dy_[i].ptr<float>(y);    //所有图像的垂直梯度行指针
            for (int x = 0; x < src[i].cols; ++x)    //遍历当前行的每个元素
            {
                dx_row_[x] = normL2(dx_row[x]);    //三通道水平梯度平方和
                dy_row_[x] = normL2(dy_row[x]);    //三通道垂直梯度平方和
            }
        }
    }
    PairwiseSeamFinder::find(src, corners, masks);    //调用find函数
}

PairwiseSeamFinder类中的find函数主要是调用了run函数,而run函数在前面已给出介绍,它实际又调用了findInPair函数:

void GraphCutSeamFinder::Impl::findInPair(size_t first, size_t second, Rect roi)
{
    Mat img1 = images_[first], img2 = images_[second];    //表示相交的两幅图像
    Mat dx1 = dx_[first], dx2 = dx_[second];    //表示这两幅图像的水平梯度
    Mat dy1 = dy_[first], dy2 = dy_[second];    //表示这两幅图像的垂直梯度
    Mat mask1 = masks_[first], mask2 = masks_[second];    //表示这两幅图像的掩码
    Point tl1 = corners_[first], tl2 = corners_[second];    //表示这两幅图像的左上角坐标

    const int gap = 10;
    //分别定义这两幅图像相应的子图像,它们的面积要大一些
    Mat subimg1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
    Mat subimg2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32FC3);
    Mat submask1(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
    Mat submask2(roi.height + 2 * gap, roi.width + 2 * gap, CV_8U);
    Mat subdx1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
    Mat subdy1(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
    Mat subdx2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);
    Mat subdy2(roi.height + 2 * gap, roi.width + 2 * gap, CV_32F);

    // Cut subimages and submasks with some gap
    for (int y = -gap; y < roi.height + gap; ++y)    //遍历重叠区域
    {
        for (int x = -gap; x < roi.width + gap; ++x)
        {
            int y1 = roi.y - tl1.y + y;    //当前像素在图像1中的坐标
            int x1 = roi.x - tl1.x + x;
            if (y1 >= 0 && x1 >= 0 && y1 < img1.rows && x1 < img1.cols)
            //属于图像1,则赋值相应的值
            {
                subimg1.at<Point3f>(y + gap, x + gap) = img1.at<Point3f>(y1, x1);
                submask1.at<uchar>(y + gap, x + gap) = mask1.at<uchar>(y1, x1);
                subdx1.at<float>(y + gap, x + gap) = dx1.at<float>(y1, x1);
                subdy1.at<float>(y + gap, x + gap) = dy1.at<float>(y1, x1);
            }
            else    //不属于图像1,则赋值为0
            {
                subimg1.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
                submask1.at<uchar>(y + gap, x + gap) = 0;
                subdx1.at<float>(y + gap, x + gap) = 0.f;
                subdy1.at<float>(y + gap, x + gap) = 0.f;
            }

            int y2 = roi.y - tl2.y + y;    //当前像素在图像2中的坐标
            int x2 = roi.x - tl2.x + x;
            if (y2 >= 0 && x2 >= 0 && y2 < img2.rows && x2 < img2.cols)
            //属于图像2,则赋值相应的值
            {
                subimg2.at<Point3f>(y + gap, x + gap) = img2.at<Point3f>(y2, x2);
                submask2.at<uchar>(y + gap, x + gap) = mask2.at<uchar>(y2, x2);
                subdx2.at<float>(y + gap, x + gap) = dx2.at<float>(y2, x2);
                subdy2.at<float>(y + gap, x + gap) = dy2.at<float>(y2, x2);
            }
            else    //不属于图像1,则赋值为0
            {
                subimg2.at<Point3f>(y + gap, x + gap) = Point3f(0, 0, 0);
                submask2.at<uchar>(y + gap, x + gap) = 0;
                subdx2.at<float>(y + gap, x + gap) = 0.f;
                subdy2.at<float>(y + gap, x + gap) = 0.f;
            }
        }
    }
    //表示普通节点数量
    const int vertex_count = (roi.height + 2 * gap) * (roi.width + 2 * gap);
    //表示边数量
    const int edge_count = (roi.height - 1 + 2 * gap) * (roi.width + 2 * gap) +
                           (roi.width - 1 + 2 * gap) * (roi.height + 2 * gap);
    GCGraph<float> graph(vertex_count, edge_count);    //定义图割变量

    switch (cost_type_)    //根据不同的方法,调用不同的函数
    {
    case GraphCutSeamFinder::COST_COLOR:    //直接法
        setGraphWeightsColor(subimg1, subimg2, submask1, submask2, graph);
        break;
    case GraphCutSeamFinder::COST_COLOR_GRAD:    //梯度法
        setGraphWeightsColorGrad(subimg1, subimg2, subdx1, subdx2, subdy1, subdy2,
                                 submask1, submask2, graph);
        break;
    default:    //目前只实现了上述那两种算法
        CV_Error(CV_StsBadArg, "unsupported pixel similarity measure");
    }

    graph.maxFlow();    //得到最大流

    for (int y = 0; y < roi.height; ++y)    //遍历重叠区域,更新掩码
    {
        for (int x = 0; x < roi.width; ++x)
        {
            //当前像素属于终端节点s
            if (graph.inSourceSegment((y + gap) * (roi.width + 2 * gap) + x + gap))
            {
                if (mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x))
                    mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x) = 0;    //掩码图像2
            }
            else    //当前像素属于终端节点t
            {
                if (mask2.at<uchar>(roi.y - tl2.y + y, roi.x - tl2.x + x))
                    mask1.at<uchar>(roi.y - tl1.y + y, roi.x - tl1.x + x) = 0;    //掩码图像1
            }
        }
    }
}

图割中的直接法:

void GraphCutSeamFinder::Impl::setGraphWeightsColor(const Mat &img1, const Mat &img2,
                                                    const Mat &mask1, const Mat &mask2, GCGraph<float> &graph)
{
    const Size img_size = img1.size();    //得到重叠区域的尺寸

    // Set terminal weights
    for (int y = 0; y < img_size.height; ++y)    //遍历重叠区域
    {
        for (int x = 0; x < img_size.width; ++x)
        {
            int v = graph.addVtx();    //为图添加普通节点
            //为普通节点与两个终端节点添加边,即定义其初始权值
            graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,
                                    mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);
        }
    }

    // Set regular edge weights
    const float weight_eps = 1.f;    //设置一个规则边权值
    for (int y = 0; y < img_size.height; ++y)    //遍历重叠区域
    {
        for (int x = 0; x < img_size.width; ++x)
        {
            int v = y * img_size.width + x;    //表示当前普通节点,即当前像素
            if (x < img_size.width - 1)
            {
                //计算当前像素与其右侧像素的边的权值,式90的分子部分
                float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
                               normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1)) +
                               weight_eps;
                //如果当前像素和其右侧像素是被mask1和mask2掩码掉的,则该边无效
                if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
                    !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
                    weight += bad_region_penalty_;    //赋于一个较大的值
                //为当前像素与其右侧像素之间的边赋予初始权值,权值是双向的
                graph.addEdges(v, v + 1, weight, weight);
            }
            if (y < img_size.height - 1)
            {
                //计算当前像素与其下侧像素的边的权值,式90的分子部分
                float weight = normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
                               normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x)) +
                               weight_eps;
                //如果当前像素和其下侧像素是被mask1和mask2掩码掉的,则该边无效
                if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
                    !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
                    weight += bad_region_penalty_;    //赋于一个较大的值
                //为当前像素与其下侧像素之间的边赋予初始权值,权值是双向的
                graph.addEdges(v, v + img_size.width, weight, weight);
            }
        }
    }
}

图割中的梯度法:

void GraphCutSeamFinder::Impl::setGraphWeightsColorGrad(
        const Mat &img1, const Mat &img2, const Mat &dx1, const Mat &dx2,
        const Mat &dy1, const Mat &dy2, const Mat &mask1, const Mat &mask2,
        GCGraph<float> &graph)
{
    const Size img_size = img1.size();    //得到重叠区域的尺寸

    // Set terminal weights
    for (int y = 0; y < img_size.height; ++y)    //遍历重叠区域
    {
        for (int x = 0; x < img_size.width; ++x)
        {
            int v = graph.addVtx();    //为图添加普通节点
            //为普通节点与两个终端节点添加边,即定义其初始权值
            graph.addTermWeights(v, mask1.at<uchar>(y, x) ? terminal_cost_ : 0.f,
                                    mask2.at<uchar>(y, x) ? terminal_cost_ : 0.f);
        }
    }

    // Set regular edge weights
    const float weight_eps = 1.f;    //设置一个规则边权值
    for (int y = 0; y < img_size.height; ++y)    //遍历重叠区域
    {
        for (int x = 0; x < img_size.width; ++x)
        {
            int v = y * img_size.width + x;    //表示当前普通节点,即当前像素
            if (x < img_size.width - 1)
            {
                //计算当前像素与其右侧像素的梯度,即式91的分母部分
                float grad = dx1.at<float>(y, x) + dx1.at<float>(y, x + 1) +
                             dx2.at<float>(y, x) + dx2.at<float>(y, x + 1) + weight_eps;
                //计算当前像素与其右侧像素的边权值,即式91
                float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
                                normL2(img1.at<Point3f>(y, x + 1), img2.at<Point3f>(y, x + 1))) / grad +
                               weight_eps;
                //如果当前像素和其右侧像素是被mask1和mask2掩码掉的,则该边无效
                if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y, x + 1) ||
                    !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y, x + 1))
                    weight += bad_region_penalty_;
                //为当前像素与其右侧像素之间赋予权值,权值是双向的
                graph.addEdges(v, v + 1, weight, weight);
            }
            if (y < img_size.height - 1)
            {
                //计算当前像素与其下侧像素的梯度,即式91的分母部分
                float grad = dy1.at<float>(y, x) + dy1.at<float>(y + 1, x) +
                             dy2.at<float>(y, x) + dy2.at<float>(y + 1, x) + weight_eps;
                //计算当前像素与其下侧像素的边权值,即式91
                float weight = (normL2(img1.at<Point3f>(y, x), img2.at<Point3f>(y, x)) +
                                normL2(img1.at<Point3f>(y + 1, x), img2.at<Point3f>(y + 1, x))) / grad +
                               weight_eps;
                //如果当前像素和其下侧像素是被mask1和mask2掩码掉的,则该边无效
                if (!mask1.at<uchar>(y, x) || !mask1.at<uchar>(y + 1, x) ||
                    !mask2.at<uchar>(y, x) || !mask2.at<uchar>(y + 1, x))
                    weight += bad_region_penalty_;    //赋于一个较大的值
                //为当前像素与其下侧像素之间赋予权值,权值是双向的
                graph.addEdges(v, v + img_size.width, weight, weight);
            }
        }
    }
}

关于图割算法的源码解析这里就不再介绍,详细内容可以参看下面这些网文:

http://blog.csdn.net/u011574296/article/details/52983211

http://www.voidcn.com/article/p-tsizwupq-h.html

http://www.myexception.cn/go/1895078.html

6.3 应用

下面我们给出寻找接缝线的应用:

#include "opencv2/core/core.hpp"
#include "highgui.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/legacy/legacy.hpp"

#include "opencv2/stitching/detail/autocalib.hpp"
#include "opencv2/stitching/detail/blenders.hpp"
#include "opencv2/stitching/detail/camera.hpp"
#include "opencv2/stitching/detail/exposure_compensate.hpp"
#include "opencv2/stitching/detail/matchers.hpp"
#include "opencv2/stitching/detail/motion_estimators.hpp"
#include "opencv2/stitching/detail/seam_finders.hpp"
#include "opencv2/stitching/detail/util.hpp"
#include "opencv2/stitching/detail/warpers.hpp"
#include "opencv2/stitching/warpers.hpp"

#include <iostream>
#include <fstream> 
#include <string>
#include <iomanip> 
using namespace cv;
using namespace std;
using namespace detail;

int main(int argc, char** argv)
{   
   vector<Mat> imgs;    //输入图像
   Mat img = imread("1.jpg");
   imgs.push_back(img);
   img = imread("2.jpg");
   imgs.push_back(img);

   Ptr<FeaturesFinder> finder;    //特征检测
   finder = new SurfFeaturesFinder();
   vector<ImageFeatures> features(2);
   (*finder)(imgs[0], features[0]);
   (*finder)(imgs[1], features[1]);

   vector<MatchesInfo> pairwise_matches;    //特征匹配
   BestOf2NearestMatcher matcher(false, 0.3f, 6, 6);
   matcher(features, pairwise_matches);

   HomographyBasedEstimator estimator;    //相机参数评估
   vector<CameraParams> cameras;
   estimator(features, pairwise_matches, cameras);
   for (size_t i = 0; i < cameras.size(); ++i)
   {
      Mat R;
      cameras[i].R.convertTo(R, CV_32F);
      cameras[i].R = R;
   }

   Ptr<detail::BundleAdjusterBase> adjuster;    //光束平差法,精确化相机参数
   adjuster = new detail::BundleAdjusterReproj();
   adjuster->setConfThresh(1);
   (*adjuster)(features, pairwise_matches, cameras);

   vector<Mat> rmats;
   for (size_t i = 0; i < cameras.size(); ++i)
      rmats.push_back(cameras[i].R.clone());
   waveCorrect(rmats, WAVE_CORRECT_HORIZ);    //波形校正
   for (size_t i = 0; i < cameras.size(); ++i)
      cameras[i].R = rmats[i];

   //图像映射变换
   vector<Point> corners(2);
   vector<Mat> masks_warped(2);
   vector<Mat> images_warped(2);
   vector<Mat> masks(2);
   for (int i = 0; i < 2; ++i)
   {
      masks[i].create(imgs[i].size(), CV_8U);
      masks[i].setTo(Scalar::all(255));
   }
   Ptr<WarperCreator> warper_creator;
   warper_creator = new cv::PlaneWarper();
   Ptr<RotationWarper> warper = warper_creator->create(static_cast<float>(cameras[0].focal));
   for (int i = 0; i < 2; ++i)
   {
      Mat_<float> K;
      cameras[i].K().convertTo(K, CV_32F); 
      corners[i] = warper->warp(imgs[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]);
      warper->warp(masks[i], K, cameras[i].R, INTER_NEAREST, BORDER_CONSTANT, masks_warped[i]);
   }
	
   //曝光补偿
   Ptr<ExposureCompensator> compensator = 
                     ExposureCompensator::createDefault(ExposureCompensator::GAIN);
   compensator->feed(corners, images_warped, masks_warped);
   for(int i=0;i<2;++i)
   {
      compensator->apply(i, corners[i], images_warped[i], masks_warped[i]);
   }

   Ptr<SeamFinder> seam_finder;    //定义接缝线寻找器
   //seam_finder = new NoSeamFinder();    //无需寻找接缝线
   //seam_finder = new VoronoiSeamFinder();    //逐点法
   //seam_finder = new DpSeamFinder(DpSeamFinder::COLOR);    //动态规范法
   //seam_finder = new DpSeamFinder(DpSeamFinder::COLOR_GRAD);
   //图割法
   //seam_finder = new GraphCutSeamFinder(GraphCutSeamFinder::COST_COLOR);
   seam_finder = new GraphCutSeamFinder(GraphCutSeamFinder::COST_COLOR_GRAD);

   vector<Mat> images_warped_f(2);
   for (int i = 0; i < 2; ++i)    //图像数据类型转换
      images_warped[i].convertTo(images_warped_f[i], CV_32F);
   //得到接缝线的掩码图像masks_warped
   seam_finder->find(images_warped_f, corners, masks_warped); 

   //通过canny边缘检测,得到掩码边界,其中有一条边界就是接缝线
   for(int k=0;k<2;k++)
      Canny(masks_warped[k], masks_warped[k], 3, 9,3 ); 

   //为了使接缝线看得更清楚,这里使用了膨胀运算来加粗边界线
   vector<Mat> dilate_img(2);  
   Mat element = getStructuringElement(MORPH_RECT, Size(10, 10));    //定义结构元素
    
   for(int k =0; k<2;k++)    //遍历两幅图像
   {
      dilate(masks_warped[k], dilate_img[k],element);    //膨胀运算
      //在映射变换图上画出接缝线,在这里只是为了呈现出的一种效果,所以并没有区分接缝线和其他掩码边界
      for(int y = 0; y < images_warped[k].rows; y++)
      {
         for(int x = 0; x < images_warped[k].cols; x++)
         {
            if(dilate_img[k].at<uchar>(y, x) == 255)    //掩码边界
            {
               images_warped[k].at<Vec3b>(y, x)[0]=255;
               images_warped[k].at<Vec3b>(y, x)[1]=0;
               images_warped[k].at<Vec3b>(y, x)[2]=255;
            }				
         }
      }
   }

   imwrite("seam1.jpg", images_warped[0]);    //存储图像
   imwrite("seam2.jpg", images_warped[1]);

   return 0;
}

最终得到的结果为:

      

图13 接缝线





















猜你喜欢

转载自blog.csdn.net/zhaocj/article/details/78944867