天天看點

圖像平均融合

在師兄以前做的基礎上,試着将原來的IplImage風格的變成Mat類型的

Mat LinearBlending( Mat& img1, Mat &img2)
{
     //平均融合
    Mat result=Mat::zeros(img1.rows,img1.cols,img1.type());
    int channels = result.channels();  
    int nRows = result.rows ;  
    int nCols = result.cols*channels;  
    if (img1.isContinuous()&&img2.isContinuous())  
    {  
        nCols *= nRows;  
        nRows = 1;  
    }  
    uchar *ptr1,*ptr2,*r_ptr;
    for(int i=0;i<nRows;++i)
    {
        ptr1=img1.ptr<uchar>(i);
        ptr2=img2.ptr<uchar>(i);
        r_ptr=result.ptr<uchar>(i);
        for(int j=0;j<nCols;j+=3)
        {
            int p1 = (ptr1[j])&&(ptr1[j+1])&&(ptr1[j+2]);//p1=1,灰階!=0,有值;   p1=0,灰階=0
            int p2 = (ptr2[j])&&(ptr2[j+1])&&(ptr2[j+2]);//p2=1,灰階!=0;有值;   p2=0,灰階=0
            if(p1&&p2)
            {
                r_ptr[j] = (ptr1[j]+ptr2[j])*0.5;  //兩幅圖像的像素均不為零,則取平均
                r_ptr[j+1] = (ptr1[j+1]+ptr2[j+1])*0.5;
                r_ptr[j+2] = (ptr1[j+2]+ptr2[j+2])*0.5;
            }
            if((p1==1)&&(p2 ==0))
            {
                r_ptr[j] = ptr1[j]; //有一幅圖像的像素為零,則取不為零的像素
                r_ptr[j+1] = ptr1[j+1];
                r_ptr[j+2] = ptr1[j+2];
            }
            if((p1==0)&&(p2==1))
            {
                r_ptr[j] = ptr2[j];
                r_ptr[j+1] = ptr2[j+1];
                r_ptr[j+2] = ptr2[j+2];
            }
        }
    }

    return result;

}           

考慮到大圖融合時的周遊像素的時間問題,參考

http://blog.csdn.net/xiaowei_cqu/article/details/7771760