Tuesday, February 26, 2013

OpenCV combine two images

In computer vision community, developer always face one basic task to visualize the correspondences between two frames, and the easier solution might be combine two images into one single image.

In this blog, I will give a convenient and easy to understand solution to solve this problem. Of course, so far, this is just a simple starting point, you could extent it to make more robust.

The code would be as follow:


struct myexception : public std::exception{
    std::string s;
    myexception(std::string ss):s(ss){}
    virtual const char* what() const throw() {return s.c_str();}
    ~myexception() throw(){}
};



// combine two identical size images into one big image
void combineTwoImages(cv::Mat &dst, const cv::Mat img1, const cv::Mat img2){
    if (img1.cols != img2.cols || img1.rows != img2.rows) {
        throw myexception("img1 and img2 should be identical size");
    }
    int rows = img1.rows;
    int cols = img1.cols;
    dst = cvCreateMat(rows, 2 * cols, img1.type());
    cv::Mat tmp = dst(cv::Rect(0, 0, cols, rows));
    img1.copyTo(tmp);
    tmp = dst(cv::Rect(cols, 0, cols, rows));
    img2.copyTo(tmp);
}


As you could notice, this code would only work for identical size case, you would extent it to handle two arbitrary size images as well.

PS: cv::Rect(x, y, _width, _height)

Hope this would be helpful.

No comments:

Post a Comment

prettify