OpenCV读取图像时Alpha通道的处理

近日研究OpenCV的templateMatch,发现读取的template如果带有Alpha通道,那么templateMatch无法得到正确的结果,因此,尝试在遇到这种情况时,通过算法合并Alpha通道到BGR通道上,由于目标图像背景为纯黑,所以,这里没做其它的计算。
代码如下:

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description:
 * =====================================================================================
 */
int main ( int argc, char *argv[] )
{
    Mat img =   imread( argv[1], -1 );

    if( img.empty() ) return -1;

    cout << "Image Depth:\t" << depth_string[ img.depth() ] << endl;
    cout << "Image Channels:\t" << img.channels() << endl;
    cout << "Image Dims:\t" << img.dims << endl;
    cout << "Image Size:\t" << img.size() << endl;
    cout << "Image Total:\t" << img.total() << endl;
    cout << "Image is Submatrix:\t" << img.isSubmatrix() << endl;
    cout << "Image Rows:\t" << img.rows << endl;
    cout << "Image Columns:\t" << img.cols << endl;
    cout << "Image is Continuous:\t" << ( img.isContinuous() ? "true" : "false" ) << endl;

    if( img.channels() == 4 )                     /* Should be checked if it is BGRA format */
    {
        Mat _dst;
        Mat _chs[4];

        cout << "Image is BGRA format, convert it to BGR format." << endl;

        split( img, _chs );

        for( int i = 0; i < 4; i ++ )
        {
            multiply( _chs[i], _chs[3], _chs[i] );
        }

        merge( _chs, 3, _dst );

        img =   _dst;
    }

    namedWindow( "Window", WINDOW_AUTOSIZE );
    imshow( "Window", img );

    waitKey( 0 );

    destroyWindow( "Show Image" );

    return 0;
}               /* ----------  end of function main  ---------- */

猜你喜欢

转载自blog.csdn.net/coroutines/article/details/56282914