map_test.cpp 13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
// Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include <iostream>
vbystricky's avatar
vbystricky committed
39
#include <opencv2/imgcodecs.hpp>
40 41 42
#include <opencv2/highgui.hpp> // OpenCV window I/O
#include <opencv2/imgproc.hpp> // OpenCV image transformations
#include <opencv2/imgproc/types_c.h>
vbystricky's avatar
vbystricky committed
43
#include <opencv2/imgcodecs/imgcodecs_c.h>
44 45 46
#include <opencv2/highgui/highgui_c.h>

#ifdef COMPARE_FEATURES
47
#include <opencv2/xfeatures2d.hpp>
48 49
#include <opencv2/calib3d.hpp>
#include <opencv2/calib3d/calib3d_c.h>
Philipp Hasper's avatar
Philipp Hasper committed
50
using namespace cv::xfeatures2d;
51
#endif
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

#include "opencv2/reg/mapaffine.hpp"
#include "opencv2/reg/mapshift.hpp"
#include "opencv2/reg/mapprojec.hpp"
#include "opencv2/reg/mappergradshift.hpp"
#include "opencv2/reg/mappergradeuclid.hpp"
#include "opencv2/reg/mappergradsimilar.hpp"
#include "opencv2/reg/mappergradaffine.hpp"
#include "opencv2/reg/mappergradproj.hpp"
#include "opencv2/reg/mapperpyramid.hpp"

static const char* DIFF_IM = "Image difference";
static const char* DIFF_REGPIX_IM = "Image difference: pixel registered";

using namespace cv;
using namespace cv::reg;
using namespace std;

70
static void showDifference(const Mat& image1, const Mat& image2, const char* title)
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
{
    Mat img1, img2;
    image1.convertTo(img1, CV_32FC3);
    image2.convertTo(img2, CV_32FC3);
    if(img1.channels() != 1)
        cvtColor(img1, img1, CV_RGB2GRAY);
    if(img2.channels() != 1)
        cvtColor(img2, img2, CV_RGB2GRAY);

    Mat imgDiff;
    img1.copyTo(imgDiff);
    imgDiff -= img2;
    imgDiff /= 2.f;
    imgDiff += 128.f;

    Mat imgSh;
    imgDiff.convertTo(imgSh, CV_8UC3);
    imshow(title, imgSh);
}

91
static void testShift(const Mat& img1)
92 93 94 95 96 97 98 99 100 101
{
    Mat img2;

    // Warp original image
    Vec<double, 2> shift(5., 5.);
    MapShift mapTest(shift);
    mapTest.warp(img1, img2);
    showDifference(img1, img2, DIFF_IM);

    // Register
102
    Ptr<MapperGradShift> mapper = makePtr<MapperGradShift>();
103
    MapperPyramid mappPyr(mapper);
104
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    // Print result
    MapShift* mapShift = dynamic_cast<MapShift*>(mapPtr.get());
    cout << endl << "--- Testing shift mapper ---" << endl;
    cout << Mat(shift) << endl;
    cout << Mat(mapShift->getShift()) << endl;

    // Display registration accuracy
    Mat dest;
    mapShift->inverseWarp(img2, dest);
    showDifference(img1, dest, DIFF_REGPIX_IM);

    waitKey(0);
    cvDestroyWindow(DIFF_IM);
    cvDestroyWindow(DIFF_REGPIX_IM);
}

122
static void testEuclidean(const Mat& img1)
123 124 125 126
{
    Mat img2;

    // Warp original image
Ilya Lavrenov's avatar
Ilya Lavrenov committed
127
    double theta = 3*CV_PI/180;
128 129 130 131 132 133 134 135 136
    double cosT = cos(theta);
    double sinT = sin(theta);
    Matx<double, 2, 2> linTr(cosT, -sinT, sinT, cosT);
    Vec<double, 2> shift(5., 5.);
    MapAffine mapTest(linTr, shift);
    mapTest.warp(img1, img2);
    showDifference(img1, img2, DIFF_IM);

    // Register
137
    Ptr<MapperGradEuclid> mapper = makePtr<MapperGradEuclid>();
138
    MapperPyramid mappPyr(mapper);
139
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

    // Print result
    MapAffine* mapAff = dynamic_cast<MapAffine*>(mapPtr.get());
    cout << endl << "--- Testing Euclidean mapper ---" << endl;
    cout << Mat(linTr) << endl;
    cout << Mat(shift) << endl;
    cout << Mat(mapAff->getLinTr()) << endl;
    cout << Mat(mapAff->getShift()) << endl;

    // Display registration accuracy
    Mat dest;
    mapAff->inverseWarp(img2, dest);
    showDifference(img1, dest, DIFF_REGPIX_IM);

    waitKey(0);
    cvDestroyWindow(DIFF_IM);
    cvDestroyWindow(DIFF_REGPIX_IM);
}

159
static void testSimilarity(const Mat& img1)
160 161 162 163
{
    Mat img2;

    // Warp original image
Ilya Lavrenov's avatar
Ilya Lavrenov committed
164
    double theta = 3*CV_PI/180;
165 166 167 168 169 170 171 172 173 174
    double scale = 0.95;
    double a = scale*cos(theta);
    double b = scale*sin(theta);
    Matx<double, 2, 2> linTr(a, -b, b, a);
    Vec<double, 2> shift(5., 5.);
    MapAffine mapTest(linTr, shift);
    mapTest.warp(img1, img2);
    showDifference(img1, img2, DIFF_IM);

    // Register
175
    Ptr<MapperGradSimilar> mapper = makePtr<MapperGradSimilar>();
176
    MapperPyramid mappPyr(mapper);
177
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

    // Print result
    MapAffine* mapAff = dynamic_cast<MapAffine*>(mapPtr.get());
    cout << endl << "--- Testing similarity mapper ---" << endl;
    cout << Mat(linTr) << endl;
    cout << Mat(shift) << endl;
    cout << Mat(mapAff->getLinTr()) << endl;
    cout << Mat(mapAff->getShift()) << endl;

    // Display registration accuracy
    Mat dest;
    mapAff->inverseWarp(img2, dest);
    showDifference(img1, dest, DIFF_REGPIX_IM);

    waitKey(0);
    cvDestroyWindow(DIFF_IM);
    cvDestroyWindow(DIFF_REGPIX_IM);
}

197
static void testAffine(const Mat& img1)
198 199 200 201 202 203 204 205 206 207 208
{
    Mat img2;

    // Warp original image
    Matx<double, 2, 2> linTr(1., 0.1, -0.01, 1.);
    Vec<double, 2> shift(1., 1.);
    MapAffine mapTest(linTr, shift);
    mapTest.warp(img1, img2);
    showDifference(img1, img2, DIFF_IM);

    // Register
209
    Ptr<MapperGradAffine> mapper = makePtr<MapperGradAffine>();
210
    MapperPyramid mappPyr(mapper);
211
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

    // Print result
    MapAffine* mapAff = dynamic_cast<MapAffine*>(mapPtr.get());
    cout << endl << "--- Testing affine mapper ---" << endl;
    cout << Mat(linTr) << endl;
    cout << Mat(shift) << endl;
    cout << Mat(mapAff->getLinTr()) << endl;
    cout << Mat(mapAff->getShift()) << endl;

    // Display registration accuracy
    Mat dest;
    mapAff->inverseWarp(img2, dest);
    showDifference(img1, dest, DIFF_REGPIX_IM);

    waitKey(0);
    cvDestroyWindow(DIFF_IM);
    cvDestroyWindow(DIFF_REGPIX_IM);
}

231
static void testProjective(const Mat& img1)
232 233 234 235 236 237 238 239 240 241
{
    Mat img2;

    // Warp original image
    Matx<double, 3, 3> projTr(1., 0., 0., 0., 1., 0., 0.0001, 0.0001, 1);
    MapProjec mapTest(projTr);
    mapTest.warp(img1, img2);
    showDifference(img1, img2, DIFF_IM);

    // Register
242
    Ptr<MapperGradProj> mapper = makePtr<MapperGradProj>();
243
    MapperPyramid mappPyr(mapper);
244
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

    // Print result
    MapProjec* mapProj = dynamic_cast<MapProjec*>(mapPtr.get());
    mapProj->normalize();
    cout << endl << "--- Testing projective transformation mapper ---" << endl;
    cout << Mat(projTr) << endl;
    cout << Mat(mapProj->getProjTr()) << endl;

    // Display registration accuracy
    Mat dest;
    mapProj->inverseWarp(img2, dest);
    showDifference(img1, dest, DIFF_REGPIX_IM);

    waitKey(0);
    cvDestroyWindow(DIFF_IM);
    cvDestroyWindow(DIFF_REGPIX_IM);
}

263
#ifdef COMPARE_FEATURES
264 265 266 267
//
// Following an example from
// http:// ramsrigoutham.com/2012/11/22/panorama-image-stitching-in-opencv/
//
268
static void calcHomographyFeature(const Mat& image1, const Mat& image2)
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
{
    static const char* difffeat = "Difference feature registered";

    Mat gray_image1;
    Mat gray_image2;
    // Convert to Grayscale
    if(image1.channels() != 1)
        cvtColor(image1, gray_image1, CV_RGB2GRAY);
    else
        image1.copyTo(gray_image1);
    if(image2.channels() != 1)
        cvtColor(image2, gray_image2, CV_RGB2GRAY);
    else
        image2.copyTo(gray_image2);

284 285 286 287
    //-- Step 1: Detect the keypoints using SIFT or SURF Detector
#ifdef USE_SIFT
    Ptr<Feature2D> features = SIFT::create();
#else
288
    int minHessian = 400;
289 290
    Ptr<Feature2D> features = SURF::create(minHessian);
#endif
291 292 293

    std::vector<KeyPoint> keypoints_object, keypoints_scene;

294 295
    features->detect(gray_image1, keypoints_object);
    features->detect(gray_image2, keypoints_scene);
296 297 298 299 300

    //-- Step 2: Calculate descriptors (feature vectors)

    Mat descriptors_object, descriptors_scene;

301 302
    features->compute(gray_image1, keypoints_object, descriptors_object);
    features->compute(gray_image2, keypoints_scene, descriptors_scene);
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

    //-- Step 3: Matching descriptor vectors using FLANN matcher
    FlannBasedMatcher matcher;
    std::vector<DMatch> matches;
    matcher.match(descriptors_object, descriptors_scene, matches);

    double max_dist = 0; double min_dist = 100;

    //-- Quick calculation of max and min distances between keypoints
    for(int i = 0; i < descriptors_object.rows; i++)
    {
        double dist = matches[i].distance;
        if( dist < min_dist ) min_dist = dist;
        if( dist > max_dist ) max_dist = dist;
    }

    //-- Use only "good" matches (i.e. whose distance is less than 3*min_dist)
    std::vector<DMatch> good_matches;

    for(int i = 0; i < descriptors_object.rows; i++) {
        if(matches[i].distance < 3*min_dist) {
            good_matches.push_back( matches[i]);
        }
    }
    std::vector< Point2f > obj;
    std::vector< Point2f > scene;

    for(size_t i = 0; i < good_matches.size(); i++)
    {
        //-- Get the keypoints from the good matches
        obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
        scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
    }

    // Find the Homography Matrix
    Mat H = findHomography( obj, scene, CV_RANSAC );
    // Use the Homography Matrix to warp the images
    Mat result;
    Mat Hinv = H.inv();
    warpPerspective(image2, result, Hinv, image1.size());

    cout << "--- Feature method\n" << H << endl;
345

346 347 348 349 350 351
    Mat imf1, resf;
    image1.convertTo(imf1, CV_64FC3);
    result.convertTo(resf, CV_64FC3);
    showDifference(imf1, resf, difffeat);
}

352
static void calcHomographyPixel(const Mat& img1, const Mat& img2)
353 354 355 356
{
    static const char* diffpixel = "Difference pixel registered";

    // Register using pixel differences
357
    Ptr<MapperGradProj> mapper = makePtr<MapperGradProj>();
358
    MapperPyramid mappPyr(mapper);
359
    Ptr<Map> mapPtr = mappPyr.calculate(img1, img2);
360 361 362 363 364 365 366 367 368 369 370 371

    // Print result
    MapProjec* mapProj = dynamic_cast<MapProjec*>(mapPtr.get());
    mapProj->normalize();
    cout << "--- Pixel-based method\n" << Mat(mapProj->getProjTr()) << endl;

    // Display registration accuracy
    Mat dest;
    mapProj->inverseWarp(img2, dest);
    showDifference(img1, dest, diffpixel);
}

372
static void comparePixelVsFeature(const Mat& img1_8b, const Mat& img2_8b)
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
{
    static const char* difforig = "Difference non-registered";

    // Show difference of images
    Mat img1, img2;
    img1_8b.convertTo(img1, CV_64FC3);
    img2_8b.convertTo(img2, CV_64FC3);
    showDifference(img1, img2, difforig);
    cout << endl << "--- Comparing feature-based with pixel difference based ---" << endl;

    // Register using SURF keypoints
    calcHomographyFeature(img1_8b, img2_8b);

    // Register using pixel differences
    calcHomographyPixel(img1, img2);

    waitKey(0);
}
391
#endif
392 393 394

int main(void)
{
395
    Mat img1;
396 397 398 399 400 401 402 403 404 405 406 407 408 409
    img1 = imread("home.png", CV_LOAD_IMAGE_UNCHANGED);
    if(!img1.data) {
        cout <<  "Could not open or find file" << endl;
        return -1;
    }
    // Convert to double, 3 channels
    img1.convertTo(img1, CV_64FC3);

    testShift(img1);
    testEuclidean(img1);
    testSimilarity(img1);
    testAffine(img1);
    testProjective(img1);

410
#ifdef COMPARE_FEATURES
411 412 413 414 415 416 417 418 419 420 421 422
    Mat imgcmp1 = imread("LR_05.png", CV_LOAD_IMAGE_UNCHANGED);
    if(!imgcmp1.data) {
        cout <<  "Could not open or find file" << endl;
        return -1;
    }

    Mat imgcmp2 = imread("LR_06.png", CV_LOAD_IMAGE_UNCHANGED);
    if(!imgcmp2.data) {
        cout <<  "Could not open or find file" << endl;
        return -1;
    }
    comparePixelVsFeature(imgcmp1, imgcmp2);
423
#endif
424 425 426

    return 0;
}