oneway.cpp 79.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 *  cvoneway.cpp
 *  one_way_sample
 *
 *  Created by Victor  Eruhimov on 3/23/10.
 *  Copyright 2010 Argus Corp. All rights reserved.
 *
 */

#include "precomp.hpp"
11 12 13 14
#include "opencv2/opencv_modules.hpp"
#ifdef HAVE_OPENCV_HIGHGUI
#  include "opencv2/highgui/highgui.hpp"
#endif
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
15
#include <stdio.h>
16 17

namespace cv{
18

19 20 21 22 23 24 25 26 27 28 29
    inline int round(float value)
    {
        if(value > 0)
        {
            return int(value + 0.5f);
        }
        else
        {
            return int(value - 0.5f);
        }
    }
30

31 32 33 34 35
    inline CvRect resize_rect(CvRect rect, float alpha)
    {
        return cvRect(rect.x + round((float)(0.5*(1 - alpha)*rect.width)), rect.y + round((float)(0.5*(1 - alpha)*rect.height)),
                      round(rect.width*alpha), round(rect.height*alpha));
    }
36

37
    CvMat* ConvertImageToMatrix(IplImage* patch);
38

39 40 41 42 43 44 45 46
    class CvCameraPose
        {
        public:
            CvCameraPose()
            {
                m_rotation = cvCreateMat(1, 3, CV_32FC1);
                m_translation = cvCreateMat(1, 3, CV_32FC1);
            };
47

48 49 50 51 52
            ~CvCameraPose()
            {
                cvReleaseMat(&m_rotation);
                cvReleaseMat(&m_translation);
            };
53

54 55 56 57 58
            void SetPose(CvMat* rotation, CvMat* translation)
            {
                cvCopy(rotation, m_rotation);
                cvCopy(translation, m_translation);
            };
59

60 61
            CvMat* GetRotation() {return m_rotation;};
            CvMat* GetTranslation() {return m_translation;};
62

63 64 65 66
        protected:
            CvMat* m_rotation;
            CvMat* m_translation;
        };
67

68 69 70 71 72
    // AffineTransformPatch: generates an affine transformed image patch.
    // - src: source image (roi is supported)
    // - dst: output image. ROI of dst image should be 2 times smaller than ROI of src.
    // - pose: parameters of an affine transformation
    void AffineTransformPatch(IplImage* src, IplImage* dst, CvAffinePose pose);
73

74 75 76 77 78
    // GenerateAffineTransformFromPose: generates an affine transformation matrix from CvAffinePose instance
    // - size: the size of image patch
    // - pose: affine transformation
    // - transform: 2x3 transformation matrix
    void GenerateAffineTransformFromPose(CvSize size, CvAffinePose pose, CvMat* transform);
79

80 81
    // Generates a random affine pose
    CvAffinePose GenRandomAffinePose();
82 83


84 85
    const static int num_mean_components = 500;
    const static float noise_intensity = 0.15f;
86 87


88 89 90 91
    static inline CvPoint rect_center(CvRect rect)
    {
        return cvPoint(rect.x + rect.width/2, rect.y + rect.height/2);
    }
92 93 94 95 96 97 98

    // static void homography_transform(IplImage* frontal, IplImage* result, CvMat* homography)
    // {
    //     cvWarpPerspective(frontal, result, homography);
    // }

    static CvAffinePose perturbate_pose(CvAffinePose pose, float noise)
99 100 101 102
    {
        // perturbate the matrix
        float noise_mult_factor = 1 + (0.5f - float(rand())/RAND_MAX)*noise;
        float noise_add_factor = noise_mult_factor - 1;
103

104 105 106 107 108
        CvAffinePose pose_pert = pose;
        pose_pert.phi += noise_add_factor;
        pose_pert.theta += noise_mult_factor;
        pose_pert.lambda1 *= noise_mult_factor;
        pose_pert.lambda2 *= noise_mult_factor;
109

110 111
        return pose_pert;
    }
112 113

    static void generate_mean_patch(IplImage* frontal, IplImage* result, CvAffinePose pose, int pose_count, float noise)
114 115 116 117
    {
        IplImage* sum = cvCreateImage(cvSize(result->width, result->height), IPL_DEPTH_32F, 1);
        IplImage* workspace = cvCloneImage(result);
        IplImage* workspace_float = cvCloneImage(sum);
118

119 120 121 122
        cvSetZero(sum);
        for(int i = 0; i < pose_count; i++)
        {
            CvAffinePose pose_pert = perturbate_pose(pose, noise);
123

124 125 126 127
            AffineTransformPatch(frontal, workspace, pose_pert);
            cvConvertScale(workspace, workspace_float);
            cvAdd(sum, workspace_float, sum);
        }
128

129
        cvConvertScale(sum, result, 1.0f/pose_count);
130

131 132 133 134
        cvReleaseImage(&workspace);
        cvReleaseImage(&sum);
        cvReleaseImage(&workspace_float);
    }
135 136 137 138 139 140 141 142 143 144

    // static void generate_mean_patch_fast(IplImage* /*frontal*/, IplImage* /*result*/, CvAffinePose /*pose*/,
    //                               CvMat* /*pca_hr_avg*/, CvMat* /*pca_hr_eigenvectors*/, const OneWayDescriptor* /*pca_descriptors*/)
    // {
    //     /*for(int i = 0; i < pca_hr_eigenvectors->cols; i++)
    //     {

    //     }*/
    // }

145 146
    void readPCAFeatures(const char *filename, CvMat** avg, CvMat** eigenvectors, const char *postfix = "");
    void readPCAFeatures(const FileNode &fn, CvMat** avg, CvMat** eigenvectors, const char* postfix = "");
147 148 149 150 151 152
    void savePCAFeatures(FileStorage &fs, const char* postfix, CvMat* avg, CvMat* eigenvectors);
    void calcPCAFeatures(vector<IplImage*>& patches, FileStorage &fs, const char* postfix, CvMat** avg,
                         CvMat** eigenvectors);
    void loadPCAFeatures(const char* path, const char* images_list, vector<IplImage*>& patches, CvSize patch_size);
    void generatePCAFeatures(const char* path, const char* img_filename, FileStorage& fs, const char* postfix,
                             CvSize patch_size, CvMat** avg, CvMat** eigenvectors);
153

154 155 156 157
    void eigenvector2image(CvMat* eigenvector, IplImage* img);

    void FindOneWayDescriptor(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch, int& desc_idx, int& pose_idx, float& distance,
                              CvMat* avg = 0, CvMat* eigenvalues = 0);
158

159 160 161
    void FindOneWayDescriptor(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch, int n,
                              std::vector<int>& desc_idxs, std::vector<int>&  pose_idxs, std::vector<float>& distances,
                              CvMat* avg = 0, CvMat* eigenvalues = 0);
162

163
    void FindOneWayDescriptor(cv::flann::Index* m_pca_descriptors_tree, CvSize patch_size, int m_pca_dim_low, int m_pose_count, IplImage* patch, int& desc_idx, int& pose_idx, float& distance,
164
                              CvMat* avg = 0, CvMat* eigenvalues = 0);
165

166 167 168 169
    void FindOneWayDescriptorEx(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch,
                                float scale_min, float scale_max, float scale_step,
                                int& desc_idx, int& pose_idx, float& distance, float& scale,
                                CvMat* avg, CvMat* eigenvectors);
170

171 172 173 174 175
    void FindOneWayDescriptorEx(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch,
                                float scale_min, float scale_max, float scale_step,
                                int n, std::vector<int>& desc_idxs, std::vector<int>& pose_idxs,
                                std::vector<float>& distances, std::vector<float>& scales,
                                CvMat* avg, CvMat* eigenvectors);
176

177
    void FindOneWayDescriptorEx(cv::flann::Index* m_pca_descriptors_tree, CvSize patch_size, int m_pca_dim_low, int m_pose_count, IplImage* patch,
178 179 180
                                float scale_min, float scale_max, float scale_step,
                                int& desc_idx, int& pose_idx, float& distance, float& scale,
                                CvMat* avg, CvMat* eigenvectors);
181

182 183 184 185 186 187 188 189 190
    inline CvRect fit_rect_roi_fixedsize(CvRect rect, CvRect roi)
    {
        CvRect fit = rect;
        fit.x = MAX(fit.x, roi.x);
        fit.y = MAX(fit.y, roi.y);
        fit.x = MIN(fit.x, roi.x + roi.width - fit.width - 1);
        fit.y = MIN(fit.y, roi.y + roi.height - fit.height - 1);
        return(fit);
    }
191

192 193 194 195 196
    inline CvRect fit_rect_fixedsize(CvRect rect, IplImage* img)
    {
        CvRect roi = cvGetImageROI(img);
        return fit_rect_roi_fixedsize(rect, roi);
    }
197

198 199 200 201 202 203 204 205 206 207 208 209
    OneWayDescriptor::OneWayDescriptor()
    {
        m_pose_count = 0;
        m_samples = 0;
        m_input_patch = 0;
        m_train_patch = 0;
        m_pca_coeffs = 0;
        m_affine_poses = 0;
        m_transforms = 0;
        m_pca_dim_low = 100;
        m_pca_dim_high = 100;
    }
210

211 212 213 214 215 216 217 218 219 220 221 222 223
    OneWayDescriptor::~OneWayDescriptor()
    {
        if(m_pose_count)
        {
            for(int i = 0; i < m_pose_count; i++)
            {
                cvReleaseImage(&m_samples[i]);
                cvReleaseMat(&m_pca_coeffs[i]);
            }
            cvReleaseImage(&m_input_patch);
            cvReleaseImage(&m_train_patch);
            delete []m_samples;
            delete []m_pca_coeffs;
224

225 226 227 228 229 230
            if(!m_transforms)
            {
                delete []m_affine_poses;
            }
        }
    }
231

232 233 234 235 236 237
    void OneWayDescriptor::Allocate(int pose_count, CvSize size, int nChannels)
    {
        m_pose_count = pose_count;
        m_samples = new IplImage* [m_pose_count];
        m_pca_coeffs = new CvMat* [m_pose_count];
        m_patch_size = cvSize(size.width/2, size.height/2);
238

239 240 241 242
        if(!m_transforms)
        {
            m_affine_poses = new CvAffinePose[m_pose_count];
        }
243

244 245 246 247 248 249
        int length = m_pca_dim_low;//roi.width*roi.height;
        for(int i = 0; i < m_pose_count; i++)
        {
            m_samples[i] = cvCreateImage(cvSize(size.width/2, size.height/2), IPL_DEPTH_32F, nChannels);
            m_pca_coeffs[i] = cvCreateMat(1, length, CV_32FC1);
        }
250

251 252 253
        m_input_patch = cvCreateImage(GetPatchSize(), IPL_DEPTH_8U, 1);
        m_train_patch = cvCreateImage(GetInputPatchSize(), IPL_DEPTH_8U, 1);
    }
254 255 256 257 258 259 260 261 262 263 264 265 266 267

    // static void cvmSet2DPoint(CvMat* matrix, int row, int col, CvPoint2D32f point)
    // {
    //     cvmSet(matrix, row, col, point.x);
    //     cvmSet(matrix, row, col + 1, point.y);
    // }

    // static void cvmSet3DPoint(CvMat* matrix, int row, int col, CvPoint3D32f point)
    // {
    //     cvmSet(matrix, row, col, point.x);
    //     cvmSet(matrix, row, col + 1, point.y);
    //     cvmSet(matrix, row, col + 2, point.z);
    // }

268 269 270 271 272 273 274 275 276
    CvAffinePose GenRandomAffinePose()
    {
        const float scale_min = 0.8f;
        const float scale_max = 1.2f;
        CvAffinePose pose;
        pose.theta = float(rand())/RAND_MAX*120 - 60;
        pose.phi = float(rand())/RAND_MAX*360;
        pose.lambda1 = scale_min + float(rand())/RAND_MAX*(scale_max - scale_min);
        pose.lambda2 = scale_min + float(rand())/RAND_MAX*(scale_max - scale_min);
277

278 279
        return pose;
    }
280

281 282 283 284 285 286 287
    void GenerateAffineTransformFromPose(CvSize size, CvAffinePose pose, CvMat* transform)
    {
        CvMat* temp = cvCreateMat(3, 3, CV_32FC1);
        CvMat* final = cvCreateMat(3, 3, CV_32FC1);
        cvmSet(temp, 2, 0, 0.0f);
        cvmSet(temp, 2, 1, 0.0f);
        cvmSet(temp, 2, 2, 1.0f);
288

289 290
        CvMat rotation;
        cvGetSubRect(temp, &rotation, cvRect(0, 0, 3, 2));
291

292 293
        cv2DRotationMatrix(cvPoint2D32f(size.width/2, size.height/2), pose.phi, 1.0, &rotation);
        cvCopy(temp, final);
294

295 296 297 298 299 300 301
        cvmSet(temp, 0, 0, pose.lambda1);
        cvmSet(temp, 0, 1, 0.0f);
        cvmSet(temp, 1, 0, 0.0f);
        cvmSet(temp, 1, 1, pose.lambda2);
        cvmSet(temp, 0, 2, size.width/2*(1 - pose.lambda1));
        cvmSet(temp, 1, 2, size.height/2*(1 - pose.lambda2));
        cvMatMul(temp, final, final);
302

303 304
        cv2DRotationMatrix(cvPoint2D32f(size.width/2, size.height/2), pose.theta - pose.phi, 1.0, &rotation);
        cvMatMul(temp, final, final);
305

306 307
        cvGetSubRect(final, &rotation, cvRect(0, 0, 3, 2));
        cvCopy(&rotation, transform);
308

309 310 311
        cvReleaseMat(&temp);
        cvReleaseMat(&final);
    }
312

313 314 315
    void AffineTransformPatch(IplImage* src, IplImage* dst, CvAffinePose pose)
    {
        CvRect src_large_roi = cvGetImageROI(src);
316

317 318 319 320
        IplImage* temp = cvCreateImage(cvSize(src_large_roi.width, src_large_roi.height), IPL_DEPTH_32F, src->nChannels);
        cvSetZero(temp);
        IplImage* temp2 = cvCloneImage(temp);
        CvMat* rotation_phi = cvCreateMat(2, 3, CV_32FC1);
321

322 323
        CvSize new_size = cvSize(cvRound(temp->width*pose.lambda1), cvRound(temp->height*pose.lambda2));
        IplImage* temp3 = cvCreateImage(new_size, IPL_DEPTH_32F, src->nChannels);
324

325 326
        cvConvertScale(src, temp);
        cvResetImageROI(temp);
327 328


329 330
        cv2DRotationMatrix(cvPoint2D32f(temp->width/2, temp->height/2), pose.phi, 1.0, rotation_phi);
        cvWarpAffine(temp, temp2, rotation_phi);
331

332
        cvSetZero(temp);
333

334
        cvResize(temp2, temp3);
335

336 337
        cv2DRotationMatrix(cvPoint2D32f(temp3->width/2, temp3->height/2), pose.theta - pose.phi, 1.0, rotation_phi);
        cvWarpAffine(temp3, temp, rotation_phi);
338

339 340 341 342
        cvSetImageROI(temp, cvRect(temp->width/2 - src_large_roi.width/4, temp->height/2 - src_large_roi.height/4,
                                   src_large_roi.width/2, src_large_roi.height/2));
        cvConvertScale(temp, dst);
        cvReleaseMat(&rotation_phi);
343

344 345 346 347
        cvReleaseImage(&temp3);
        cvReleaseImage(&temp2);
        cvReleaseImage(&temp);
    }
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    void OneWayDescriptor::GenerateSamples(int pose_count, IplImage* frontal, int norm)
    {
        /*    if(m_transforms)
         {
         GenerateSamplesWithTransforms(pose_count, frontal);
         return;
         }
         */
        CvRect roi = cvGetImageROI(frontal);
        IplImage* patch_8u = cvCreateImage(cvSize(roi.width/2, roi.height/2), frontal->depth, frontal->nChannels);
        for(int i = 0; i < pose_count; i++)
        {
            if(!m_transforms)
            {
                m_affine_poses[i] = GenRandomAffinePose();
            }
            //AffineTransformPatch(frontal, patch_8u, m_affine_poses[i]);
            generate_mean_patch(frontal, patch_8u, m_affine_poses[i], num_mean_components, noise_intensity);
367

368 369 370 371 372 373 374
            double scale = 1.0f;
            if(norm)
            {
                double sum = cvSum(patch_8u).val[0];
                scale = 1/sum;
            }
            cvConvertScale(patch_8u, m_samples[i], scale);
375

376 377 378 379 380 381 382 383 384 385 386 387
#if 0
            double maxval;
            cvMinMaxLoc(m_samples[i], 0, &maxval);
            IplImage* test = cvCreateImage(cvSize(roi.width/2, roi.height/2), IPL_DEPTH_8U, 1);
            cvConvertScale(m_samples[i], test, 255.0/maxval);
            cvNamedWindow("1", 1);
            cvShowImage("1", test);
            cvWaitKey(0);
#endif
        }
        cvReleaseImage(&patch_8u);
    }
388

389 390 391 392 393 394 395 396 397
    void OneWayDescriptor::GenerateSamplesFast(IplImage* frontal, CvMat* pca_hr_avg,
                                               CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors)
    {
        CvRect roi = cvGetImageROI(frontal);
        if(roi.width != GetInputPatchSize().width || roi.height != GetInputPatchSize().height)
        {
            cvResize(frontal, m_train_patch);
            frontal = m_train_patch;
        }
398

399 400 401 402
        CvMat* pca_coeffs = cvCreateMat(1, pca_hr_eigenvectors->cols, CV_32FC1);
        double maxval;
        cvMinMaxLoc(frontal, 0, &maxval);
        CvMat* frontal_data = ConvertImageToMatrix(frontal);
403

404 405 406 407 408 409 410 411 412 413 414
        double sum = cvSum(frontal_data).val[0];
        cvConvertScale(frontal_data, frontal_data, 1.0f/sum);
        cvProjectPCA(frontal_data, pca_hr_avg, pca_hr_eigenvectors, pca_coeffs);
        for(int i = 0; i < m_pose_count; i++)
        {
            cvSetZero(m_samples[i]);
            for(int j = 0; j < m_pca_dim_high; j++)
            {
                double coeff = cvmGet(pca_coeffs, 0, j);
                IplImage* patch = pca_descriptors[j + 1].GetPatch(i);
                cvAddWeighted(m_samples[i], 1.0, patch, coeff, 0, m_samples[i]);
415

416 417 418 419 420 421 422 423 424 425 426
#if 0
                printf("coeff%d = %f\n", j, coeff);
                IplImage* test = cvCreateImage(cvSize(12, 12), IPL_DEPTH_8U, 1);
                double maxval;
                cvMinMaxLoc(patch, 0, &maxval);
                cvConvertScale(patch, test, 255.0/maxval);
                cvNamedWindow("1", 1);
                cvShowImage("1", test);
                cvWaitKey(0);
#endif
            }
427

428
            cvAdd(pca_descriptors[0].GetPatch(i), m_samples[i], m_samples[i]);
429 430
            double sm = cvSum(m_samples[i]).val[0];
            cvConvertScale(m_samples[i], m_samples[i], 1.0/sm);
431

432 433 434 435 436 437 438 439 440 441
#if 0
            IplImage* test = cvCreateImage(cvSize(12, 12), IPL_DEPTH_8U, 1);
            /*        IplImage* temp1 = cvCreateImage(cvSize(12, 12), IPL_DEPTH_32F, 1);
             eigenvector2image(pca_hr_avg, temp1);
             IplImage* test = cvCreateImage(cvSize(12, 12), IPL_DEPTH_8U, 1);
             cvAdd(m_samples[i], temp1, temp1);
             cvMinMaxLoc(temp1, 0, &maxval);
             cvConvertScale(temp1, test, 255.0/maxval);*/
            cvMinMaxLoc(m_samples[i], 0, &maxval);
            cvConvertScale(m_samples[i], test, 255.0/maxval);
442

443 444 445 446 447 448 449
            cvNamedWindow("1", 1);
            cvShowImage("1", frontal);
            cvNamedWindow("2", 1);
            cvShowImage("2", test);
            cvWaitKey(0);
#endif
        }
450

451 452 453
        cvReleaseMat(&pca_coeffs);
        cvReleaseMat(&frontal_data);
    }
454

455 456 457 458 459 460
    void OneWayDescriptor::SetTransforms(CvAffinePose* poses, CvMat** transforms)
    {
        if(m_affine_poses)
        {
            delete []m_affine_poses;
        }
461

462 463 464
        m_affine_poses = poses;
        m_transforms = transforms;
    }
465

466 467 468 469 470
    void OneWayDescriptor::Initialize(int pose_count, IplImage* frontal, const char* feature_name, int norm)
    {
        m_feature_name = std::string(feature_name);
        CvRect roi = cvGetImageROI(frontal);
        m_center = rect_center(roi);
471

472
        Allocate(pose_count, cvSize(roi.width, roi.height), frontal->nChannels);
473

474 475
        GenerateSamples(pose_count, frontal, norm);
    }
476

477 478 479 480 481 482 483 484 485 486 487
    void OneWayDescriptor::InitializeFast(int pose_count, IplImage* frontal, const char* feature_name,
                                          CvMat* pca_hr_avg, CvMat* pca_hr_eigenvectors, OneWayDescriptor* pca_descriptors)
    {
        if(pca_hr_avg == 0)
        {
            Initialize(pose_count, frontal, feature_name, 1);
            return;
        }
        m_feature_name = std::string(feature_name);
        CvRect roi = cvGetImageROI(frontal);
        m_center = rect_center(roi);
488

489
        Allocate(pose_count, cvSize(roi.width, roi.height), frontal->nChannels);
490

491 492
        GenerateSamplesFast(frontal, pca_hr_avg, pca_hr_eigenvectors, pca_descriptors);
    }
493

494 495 496 497 498 499 500
    void OneWayDescriptor::InitializePCACoeffs(CvMat* avg, CvMat* eigenvectors)
    {
        for(int i = 0; i < m_pose_count; i++)
        {
            ProjectPCASample(m_samples[i], avg, eigenvectors, m_pca_coeffs[i]);
        }
    }
501

502 503 504 505 506 507 508 509 510 511
    void OneWayDescriptor::ProjectPCASample(IplImage* patch, CvMat* avg, CvMat* eigenvectors, CvMat* pca_coeffs) const
    {
        CvMat* patch_mat = ConvertImageToMatrix(patch);
        //    CvMat eigenvectorsr;
        //    cvGetSubRect(eigenvectors, &eigenvectorsr, cvRect(0, 0, eigenvectors->cols, pca_coeffs->cols));
        CvMat* temp = cvCreateMat(1, eigenvectors->cols, CV_32FC1);
        cvProjectPCA(patch_mat, avg, eigenvectors, temp);
        CvMat temp1;
        cvGetSubRect(temp, &temp1, cvRect(0, 0, pca_coeffs->cols, 1));
        cvCopy(&temp1, pca_coeffs);
512

513 514 515
        cvReleaseMat(&temp);
        cvReleaseMat(&patch_mat);
    }
516

517 518 519 520 521 522 523 524 525 526 527
    void OneWayDescriptor::EstimatePosePCA(CvArr* patch, int& pose_idx, float& distance, CvMat* avg, CvMat* eigenvectors) const
    {
        if(avg == 0)
        {
            // do not use pca
            if (!CV_IS_MAT(patch))
            {
                EstimatePose((IplImage*)patch, pose_idx, distance);
            }
            else
            {
528

529 530 531 532 533 534 535 536 537 538 539 540 541 542
            }
            return;
        }
        CvRect roi={0,0,0,0};
        if (!CV_IS_MAT(patch))
        {
            roi = cvGetImageROI((IplImage*)patch);
            if(roi.width != GetPatchSize().width || roi.height != GetPatchSize().height)
            {
                cvResize(patch, m_input_patch);
                patch = m_input_patch;
                roi = cvGetImageROI((IplImage*)patch);
            }
        }
543

544
        CvMat* pca_coeffs = cvCreateMat(1, m_pca_dim_low, CV_32FC1);
545

546 547 548 549 550 551 552 553 554 555 556 557
        if (CV_IS_MAT(patch))
        {
            cvCopy((CvMat*)patch, pca_coeffs);
        }
        else
        {
            IplImage* patch_32f = cvCreateImage(cvSize(roi.width, roi.height), IPL_DEPTH_32F, 1);
            double sum = cvSum(patch).val[0];
            cvConvertScale(patch, patch_32f, 1.0f/sum);
            ProjectPCASample(patch_32f, avg, eigenvectors, pca_coeffs);
            cvReleaseImage(&patch_32f);
        }
558 559


560 561
        distance = 1e10;
        pose_idx = -1;
562

563 564 565
        for(int i = 0; i < m_pose_count; i++)
        {
            double dist = cvNorm(m_pca_coeffs[i], pca_coeffs);
566 567 568 569 570 571 572 573 574 575
            //      float dist = 0;
            //      float data1, data2;
            //      //CvMat* pose_pca_coeffs = m_pca_coeffs[i];
            //      for (int x=0; x < pca_coeffs->width; x++)
            //          for (int y =0 ; y < pca_coeffs->height; y++)
            //          {
            //              data1 = ((float*)(pca_coeffs->data.ptr + pca_coeffs->step*x))[y];
            //              data2 = ((float*)(m_pca_coeffs[i]->data.ptr + m_pca_coeffs[i]->step*x))[y];
            //              dist+=(data1-data2)*(data1-data2);
            //          }
576
            ////#if 1
577 578 579 580
            //      for (int j = 0; j < m_pca_dim_low; j++)
            //      {
            //          dist += (pose_pca_coeffs->data.fl[j]- pca_coeffs->data.fl[j])*(pose_pca_coeffs->data.fl[j]- pca_coeffs->data.fl[j]);
            //      }
581
            //#else
582 583 584 585 586 587 588 589 590 591 592
            //      for (int j = 0; j <= m_pca_dim_low - 4; j += 4)
            //      {
            //          dist += (pose_pca_coeffs->data.fl[j]- pca_coeffs->data.fl[j])*
            //              (pose_pca_coeffs->data.fl[j]- pca_coeffs->data.fl[j]);
            //          dist += (pose_pca_coeffs->data.fl[j+1]- pca_coeffs->data.fl[j+1])*
            //              (pose_pca_coeffs->data.fl[j+1]- pca_coeffs->data.fl[j+1]);
            //          dist += (pose_pca_coeffs->data.fl[j+2]- pca_coeffs->data.fl[j+2])*
            //              (pose_pca_coeffs->data.fl[j+2]- pca_coeffs->data.fl[j+2]);
            //          dist += (pose_pca_coeffs->data.fl[j+3]- pca_coeffs->data.fl[j+3])*
            //              (pose_pca_coeffs->data.fl[j+3]- pca_coeffs->data.fl[j+3]);
            //      }
593 594 595 596 597 598 599
            //#endif
            if(dist < distance)
            {
                distance = (float)dist;
                pose_idx = i;
            }
        }
600

601 602
        cvReleaseMat(&pca_coeffs);
    }
603

604 605 606 607
    void OneWayDescriptor::EstimatePose(IplImage* patch, int& pose_idx, float& distance) const
    {
        distance = 1e10;
        pose_idx = -1;
608

609 610 611 612
        CvRect roi = cvGetImageROI(patch);
        IplImage* patch_32f = cvCreateImage(cvSize(roi.width, roi.height), IPL_DEPTH_32F, patch->nChannels);
        double sum = cvSum(patch).val[0];
        cvConvertScale(patch, patch_32f, 1/sum);
613

614 615 616 617 618 619 620 621 622
        for(int i = 0; i < m_pose_count; i++)
        {
            if(m_samples[i]->width != patch_32f->width || m_samples[i]->height != patch_32f->height)
            {
                continue;
            }
            double dist = cvNorm(m_samples[i], patch_32f);
            //float dist = 0.0f;
            //float i1,i2;
623

624
            //for (int y = 0; y<patch_32f->height; y++)
625 626 627 628 629 630 631
            //  for (int x = 0; x< patch_32f->width; x++)
            //  {
            //      i1 = ((float*)(m_samples[i]->imageData + m_samples[i]->widthStep*y))[x];
            //      i2 = ((float*)(patch_32f->imageData + patch_32f->widthStep*y))[x];
            //      dist+= (i1-i2)*(i1-i2);
            //  }

632 633 634 635 636
            if(dist < distance)
            {
                distance = (float)dist;
                pose_idx = i;
            }
637

638 639 640 641 642 643 644 645
#if 0
            IplImage* img1 = cvCreateImage(cvSize(roi.width, roi.height), IPL_DEPTH_8U, 1);
            IplImage* img2 = cvCreateImage(cvSize(roi.width, roi.height), IPL_DEPTH_8U, 1);
            double maxval;
            cvMinMaxLoc(m_samples[i], 0, &maxval);
            cvConvertScale(m_samples[i], img1, 255.0/maxval);
            cvMinMaxLoc(patch_32f, 0, &maxval);
            cvConvertScale(patch_32f, img2, 255.0/maxval);
646

647 648 649 650 651 652 653 654
            cvNamedWindow("1", 1);
            cvShowImage("1", img1);
            cvNamedWindow("2", 1);
            cvShowImage("2", img2);
            printf("Distance = %f\n", dist);
            cvWaitKey(0);
#endif
        }
655

656 657
        cvReleaseImage(&patch_32f);
    }
658

659 660 661 662 663
    void OneWayDescriptor::Save(const char* path)
    {
        for(int i = 0; i < m_pose_count; i++)
        {
            char buf[1024];
664
            sprintf(buf, "%s/patch_%04d.png", path, i);
665
            IplImage* patch = cvCreateImage(cvSize(m_samples[i]->width, m_samples[i]->height), IPL_DEPTH_8U, m_samples[i]->nChannels);
666

667 668 669
            double maxval;
            cvMinMaxLoc(m_samples[i], 0, &maxval);
            cvConvertScale(m_samples[i], patch, 255/maxval);
670

671
#ifdef HAVE_OPENCV_HIGHGUI
672
            cvSaveImage(buf, patch);
673 674 675
#else
            CV_Error(CV_StsNotImplemented, "OpenCV has been compiled without image I/O support");
#endif
676

677 678 679
            cvReleaseImage(&patch);
        }
    }
680

681 682 683
    void OneWayDescriptor::Write(CvFileStorage* fs, const char* name)
    {
        CvMat* mat = cvCreateMat(m_pose_count, m_samples[0]->width*m_samples[0]->height, CV_32FC1);
684

685 686 687 688 689 690 691 692 693 694 695 696
        // prepare data to write as a single matrix
        for(int i = 0; i < m_pose_count; i++)
        {
            for(int y = 0; y < m_samples[i]->height; y++)
            {
                for(int x = 0; x < m_samples[i]->width; x++)
                {
                    float val = *((float*)(m_samples[i]->imageData + m_samples[i]->widthStep*y) + x);
                    cvmSet(mat, i, y*m_samples[i]->width + x, val);
                }
            }
        }
697

698
        cvWrite(fs, name, mat);
699

700 701
        cvReleaseMat(&mat);
    }
702

703
    int OneWayDescriptor::ReadByName(const FileNode &parent, const char* name)
704
    {
705
        CvMat* mat = reinterpret_cast<CvMat*> (parent[name].readObj ());
706 707 708 709
        if(!mat)
        {
            return 0;
        }
710 711


712 713 714 715 716 717 718 719 720 721 722
        for(int i = 0; i < m_pose_count; i++)
        {
            for(int y = 0; y < m_samples[i]->height; y++)
            {
                for(int x = 0; x < m_samples[i]->width; x++)
                {
                    float val = (float)cvmGet(mat, i, y*m_samples[i]->width + x);
                    *((float*)(m_samples[i]->imageData + y*m_samples[i]->widthStep) + x) = val;
                }
            }
        }
723

724 725 726
        cvReleaseMat(&mat);
        return 1;
    }
727 728 729 730 731

    int OneWayDescriptor::ReadByName(CvFileStorage* fs, CvFileNode* parent, const char* name)
    {
        return ReadByName (FileNode (fs, parent), name);
    }
732

733 734 735 736
    IplImage* OneWayDescriptor::GetPatch(int index)
    {
        return m_samples[index];
    }
737

738 739 740 741
    CvAffinePose OneWayDescriptor::GetPose(int index) const
    {
        return m_affine_poses[index];
    }
742

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    void FindOneWayDescriptor(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch, int& desc_idx, int& pose_idx, float& distance,
                              CvMat* avg, CvMat* eigenvectors)
    {
        desc_idx = -1;
        pose_idx = -1;
        distance = 1e10;
        //--------
        //PCA_coeffs precalculating
        int m_pca_dim_low = descriptors[0].GetPCADimLow();
        CvMat* pca_coeffs = cvCreateMat(1, m_pca_dim_low, CV_32FC1);
        int patch_width = descriptors[0].GetPatchSize().width;
        int patch_height = descriptors[0].GetPatchSize().height;
        if (avg)
        {
            CvRect _roi = cvGetImageROI((IplImage*)patch);
            IplImage* test_img = cvCreateImage(cvSize(patch_width,patch_height), IPL_DEPTH_8U, 1);
            if(_roi.width != patch_width|| _roi.height != patch_height)
            {
761

762 763 764 765 766 767 768 769 770 771
                cvResize(patch, test_img);
                _roi = cvGetImageROI(test_img);
            }
            else
            {
                cvCopy(patch,test_img);
            }
            IplImage* patch_32f = cvCreateImage(cvSize(_roi.width, _roi.height), IPL_DEPTH_32F, 1);
            double sum = cvSum(test_img).val[0];
            cvConvertScale(test_img, patch_32f, 1.0f/sum);
772

773 774 775 776 777 778 779 780 781 782 783
            //ProjectPCASample(patch_32f, avg, eigenvectors, pca_coeffs);
            //Projecting PCA
            CvMat* patch_mat = ConvertImageToMatrix(patch_32f);
            CvMat* temp = cvCreateMat(1, eigenvectors->cols, CV_32FC1);
            cvProjectPCA(patch_mat, avg, eigenvectors, temp);
            CvMat temp1;
            cvGetSubRect(temp, &temp1, cvRect(0, 0, pca_coeffs->cols, 1));
            cvCopy(&temp1, pca_coeffs);
            cvReleaseMat(&temp);
            cvReleaseMat(&patch_mat);
            //End of projecting
784

785 786 787
            cvReleaseImage(&patch_32f);
            cvReleaseImage(&test_img);
        }
788

789
        //--------
790 791 792



793 794 795 796
        for(int i = 0; i < desc_count; i++)
        {
            int _pose_idx = -1;
            float _distance = 0;
797

798 799 800 801 802 803 804 805 806 807 808 809
#if 0
            descriptors[i].EstimatePose(patch, _pose_idx, _distance);
#else
            if (!avg)
            {
                descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
            }
            else
            {
                descriptors[i].EstimatePosePCA(pca_coeffs, _pose_idx, _distance, avg, eigenvectors);
            }
#endif
810

811 812 813 814 815 816 817 818 819
            if(_distance < distance)
            {
                desc_idx = i;
                pose_idx = _pose_idx;
                distance = _distance;
            }
        }
        cvReleaseMat(&pca_coeffs);
    }
820

821
#if defined(_KDTREE)
822

823
    void FindOneWayDescriptor(cv::flann::Index* m_pca_descriptors_tree, CvSize patch_size, int m_pca_dim_low, int m_pose_count, IplImage* patch, int& desc_idx, int& pose_idx, float& distance,
824 825 826 827 828 829 830 831 832 833 834 835
                              CvMat* avg, CvMat* eigenvectors)
    {
        desc_idx = -1;
        pose_idx = -1;
        distance = 1e10;
        //--------
        //PCA_coeffs precalculating
        CvMat* pca_coeffs = cvCreateMat(1, m_pca_dim_low, CV_32FC1);
        int patch_width = patch_size.width;
        int patch_height = patch_size.height;
        //if (avg)
        //{
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        CvRect _roi = cvGetImageROI((IplImage*)patch);
        IplImage* test_img = cvCreateImage(cvSize(patch_width,patch_height), IPL_DEPTH_8U, 1);
        if(_roi.width != patch_width|| _roi.height != patch_height)
        {

            cvResize(patch, test_img);
            _roi = cvGetImageROI(test_img);
        }
        else
        {
            cvCopy(patch,test_img);
        }
        IplImage* patch_32f = cvCreateImage(cvSize(_roi.width, _roi.height), IPL_DEPTH_32F, 1);
        float sum = cvSum(test_img).val[0];
        cvConvertScale(test_img, patch_32f, 1.0f/sum);

        //ProjectPCASample(patch_32f, avg, eigenvectors, pca_coeffs);
        //Projecting PCA
        CvMat* patch_mat = ConvertImageToMatrix(patch_32f);
        CvMat* temp = cvCreateMat(1, eigenvectors->cols, CV_32FC1);
        cvProjectPCA(patch_mat, avg, eigenvectors, temp);
        CvMat temp1;
        cvGetSubRect(temp, &temp1, cvRect(0, 0, pca_coeffs->cols, 1));
        cvCopy(&temp1, pca_coeffs);
        cvReleaseMat(&temp);
        cvReleaseMat(&patch_mat);
        //End of projecting

        cvReleaseImage(&patch_32f);
        cvReleaseImage(&test_img);
        //  }

868
        //--------
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906

        //float* target = new float[m_pca_dim_low];
        //::cvflann::KNNResultSet res(1,pca_coeffs->data.fl,m_pca_dim_low);
        //::cvflann::SearchParams params;
        //params.checks = -1;

        //int maxDepth = 1000000;
        //int neighbors_count = 1;
        //int* neighborsIdx = new int[neighbors_count];
        //float* distances = new float[neighbors_count];
        //if (m_pca_descriptors_tree->findNearest(pca_coeffs->data.fl,neighbors_count,maxDepth,neighborsIdx,0,distances) > 0)
        //{
        //  desc_idx = neighborsIdx[0] / m_pose_count;
        //  pose_idx = neighborsIdx[0] % m_pose_count;
        //  distance = distances[0];
        //}
        //delete[] neighborsIdx;
        //delete[] distances;

        cv::Mat m_object(1, m_pca_dim_low, CV_32F);
        cv::Mat m_indices(1, 1, CV_32S);
        cv::Mat m_dists(1, 1, CV_32F);

        float* object_ptr = m_object.ptr<float>(0);
        for (int i=0;i<m_pca_dim_low;i++)
        {
            object_ptr[i] = pca_coeffs->data.fl[i];
        }

        m_pca_descriptors_tree->knnSearch(m_object, m_indices, m_dists, 1, cv::flann::SearchParams(-1) );

        desc_idx = ((int*)(m_indices.ptr<int>(0)))[0] / m_pose_count;
        pose_idx = ((int*)(m_indices.ptr<int>(0)))[0] % m_pose_count;
        distance = ((float*)(m_dists.ptr<float>(0)))[0];

        //  delete[] target;


907 908 909 910 911 912 913 914
        //    for(int i = 0; i < desc_count; i++)
        //    {
        //        int _pose_idx = -1;
        //        float _distance = 0;
        //
        //#if 0
        //        descriptors[i].EstimatePose(patch, _pose_idx, _distance);
        //#else
915 916 917 918 919 920 921 922
        //      if (!avg)
        //      {
        //          descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
        //      }
        //      else
        //      {
        //          descriptors[i].EstimatePosePCA(pca_coeffs, _pose_idx, _distance, avg, eigenvectors);
        //      }
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
        //#endif
        //
        //        if(_distance < distance)
        //        {
        //            desc_idx = i;
        //            pose_idx = _pose_idx;
        //            distance = _distance;
        //        }
        //    }
        cvReleaseMat(&pca_coeffs);
    }
#endif
    //**
    void FindOneWayDescriptor(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch, int n,
                              std::vector<int>& desc_idxs, std::vector<int>&  pose_idxs, std::vector<float>& distances,
                              CvMat* avg, CvMat* eigenvectors)
    {
        for (int i=0;i<n;i++)
        {
            desc_idxs[i] = -1;
            pose_idxs[i] = -1;
            distances[i] = 1e10;
        }
        //--------
        //PCA_coeffs precalculating
        int m_pca_dim_low = descriptors[0].GetPCADimLow();
        CvMat* pca_coeffs = cvCreateMat(1, m_pca_dim_low, CV_32FC1);
        int patch_width = descriptors[0].GetPatchSize().width;
        int patch_height = descriptors[0].GetPatchSize().height;
        if (avg)
        {
            CvRect _roi = cvGetImageROI((IplImage*)patch);
            IplImage* test_img = cvCreateImage(cvSize(patch_width,patch_height), IPL_DEPTH_8U, 1);
            if(_roi.width != patch_width|| _roi.height != patch_height)
            {
958

959 960 961 962 963 964 965 966 967 968
                cvResize(patch, test_img);
                _roi = cvGetImageROI(test_img);
            }
            else
            {
                cvCopy(patch,test_img);
            }
            IplImage* patch_32f = cvCreateImage(cvSize(_roi.width, _roi.height), IPL_DEPTH_32F, 1);
            double sum = cvSum(test_img).val[0];
            cvConvertScale(test_img, patch_32f, 1.0f/sum);
969

970 971 972 973 974 975 976 977 978 979 980
            //ProjectPCASample(patch_32f, avg, eigenvectors, pca_coeffs);
            //Projecting PCA
            CvMat* patch_mat = ConvertImageToMatrix(patch_32f);
            CvMat* temp = cvCreateMat(1, eigenvectors->cols, CV_32FC1);
            cvProjectPCA(patch_mat, avg, eigenvectors, temp);
            CvMat temp1;
            cvGetSubRect(temp, &temp1, cvRect(0, 0, pca_coeffs->cols, 1));
            cvCopy(&temp1, pca_coeffs);
            cvReleaseMat(&temp);
            cvReleaseMat(&patch_mat);
            //End of projecting
981

982 983 984 985
            cvReleaseImage(&patch_32f);
            cvReleaseImage(&test_img);
        }
        //--------
986 987 988



989 990 991 992
        for(int i = 0; i < desc_count; i++)
        {
            int _pose_idx = -1;
            float _distance = 0;
993

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
#if 0
            descriptors[i].EstimatePose(patch, _pose_idx, _distance);
#else
            if (!avg)
            {
                descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
            }
            else
            {
                descriptors[i].EstimatePosePCA(pca_coeffs, _pose_idx, _distance, avg, eigenvectors);
            }
#endif
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
            for (int j=0;j<n;j++)
            {
                if(_distance < distances[j])
                {
                    for (int k=(n-1);k > j;k--)
                    {
                        desc_idxs[k] = desc_idxs[k-1];
                        pose_idxs[k] = pose_idxs[k-1];
                        distances[k] = distances[k-1];
                    }
                    desc_idxs[j] = i;
                    pose_idxs[j] = _pose_idx;
                    distances[j] = _distance;
                    break;
                }
            }
        }
        cvReleaseMat(&pca_coeffs);
    }
1026

1027 1028 1029 1030 1031 1032 1033 1034
    void FindOneWayDescriptorEx(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch,
                                float scale_min, float scale_max, float scale_step,
                                int& desc_idx, int& pose_idx, float& distance, float& scale,
                                CvMat* avg, CvMat* eigenvectors)
    {
        CvSize patch_size = descriptors[0].GetPatchSize();
        IplImage* input_patch;
        CvRect roi;
1035

1036 1037
        input_patch= cvCreateImage(patch_size, IPL_DEPTH_8U, 1);
        roi = cvGetImageROI((IplImage*)patch);
1038

1039 1040 1041 1042 1043 1044
        int _desc_idx, _pose_idx;
        float _distance;
        distance = 1e10;
        for(float cur_scale = scale_min; cur_scale < scale_max; cur_scale *= scale_step)
        {
            //        printf("Scale = %f\n", cur_scale);
1045

1046 1047 1048
            CvRect roi_scaled = resize_rect(roi, cur_scale);
            cvSetImageROI(patch, roi_scaled);
            cvResize(patch, input_patch);
1049 1050


1051 1052 1053 1054 1055 1056 1057 1058
#if 0
            if(roi.x > 244 && roi.y < 200)
            {
                cvNamedWindow("1", 1);
                cvShowImage("1", input_patch);
                cvWaitKey(0);
            }
#endif
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068
            FindOneWayDescriptor(desc_count, descriptors, input_patch, _desc_idx, _pose_idx, _distance, avg, eigenvectors);
            if(_distance < distance)
            {
                distance = _distance;
                desc_idx = _desc_idx;
                pose_idx = _pose_idx;
                scale = cur_scale;
            }
        }
1069 1070


1071 1072
        cvSetImageROI((IplImage*)patch, roi);
        cvReleaseImage(&input_patch);
1073

1074
    }
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084
    void FindOneWayDescriptorEx(int desc_count, const OneWayDescriptor* descriptors, IplImage* patch,
                                float scale_min, float scale_max, float scale_step,
                                int n, std::vector<int>& desc_idxs, std::vector<int>& pose_idxs,
                                std::vector<float>& distances, std::vector<float>& scales,
                                CvMat* avg, CvMat* eigenvectors)
    {
        CvSize patch_size = descriptors[0].GetPatchSize();
        IplImage* input_patch;
        CvRect roi;
1085

1086 1087
        input_patch= cvCreateImage(patch_size, IPL_DEPTH_8U, 1);
        roi = cvGetImageROI((IplImage*)patch);
1088

1089 1090 1091 1092 1093 1094 1095
        //  float min_distance = 1e10;
        std::vector<int> _desc_idxs;
        _desc_idxs.resize(n);
        std::vector<int> _pose_idxs;
        _pose_idxs.resize(n);
        std::vector<float> _distances;
        _distances.resize(n);
1096 1097


1098 1099 1100 1101
        for (int i=0;i<n;i++)
        {
            distances[i] = 1e10;
        }
1102

1103 1104
        for(float cur_scale = scale_min; cur_scale < scale_max; cur_scale *= scale_step)
        {
1105

1106 1107 1108
            CvRect roi_scaled = resize_rect(roi, cur_scale);
            cvSetImageROI(patch, roi_scaled);
            cvResize(patch, input_patch);
1109 1110 1111



1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
            FindOneWayDescriptor(desc_count, descriptors, input_patch, n,_desc_idxs, _pose_idxs, _distances, avg, eigenvectors);
            for (int i=0;i<n;i++)
            {
                if(_distances[i] < distances[i])
                {
                    distances[i] = _distances[i];
                    desc_idxs[i] = _desc_idxs[i];
                    pose_idxs[i] = _pose_idxs[i];
                    scales[i] = cur_scale;
                }
            }
        }
1124 1125 1126



1127 1128 1129
        cvSetImageROI((IplImage*)patch, roi);
        cvReleaseImage(&input_patch);
    }
1130

1131
#if defined(_KDTREE)
1132
    void FindOneWayDescriptorEx(cv::flann::Index* m_pca_descriptors_tree, CvSize patch_size, int m_pca_dim_low,
1133 1134 1135 1136 1137 1138 1139
                                int m_pose_count, IplImage* patch,
                                float scale_min, float scale_max, float scale_step,
                                int& desc_idx, int& pose_idx, float& distance, float& scale,
                                CvMat* avg, CvMat* eigenvectors)
    {
        IplImage* input_patch;
        CvRect roi;
1140

1141 1142
        input_patch= cvCreateImage(patch_size, IPL_DEPTH_8U, 1);
        roi = cvGetImageROI((IplImage*)patch);
1143

1144 1145 1146 1147 1148 1149
        int _desc_idx, _pose_idx;
        float _distance;
        distance = 1e10;
        for(float cur_scale = scale_min; cur_scale < scale_max; cur_scale *= scale_step)
        {
            //        printf("Scale = %f\n", cur_scale);
1150

1151 1152 1153
            CvRect roi_scaled = resize_rect(roi, cur_scale);
            cvSetImageROI(patch, roi_scaled);
            cvResize(patch, input_patch);
1154

1155 1156 1157 1158 1159 1160 1161 1162 1163
            FindOneWayDescriptor(m_pca_descriptors_tree, patch_size, m_pca_dim_low, m_pose_count, input_patch, _desc_idx, _pose_idx, _distance, avg, eigenvectors);
            if(_distance < distance)
            {
                distance = _distance;
                desc_idx = _desc_idx;
                pose_idx = _pose_idx;
                scale = cur_scale;
            }
        }
1164 1165


1166 1167
        cvSetImageROI((IplImage*)patch, roi);
        cvReleaseImage(&input_patch);
1168

1169 1170
    }
#endif
1171

1172 1173 1174 1175
    const char* OneWayDescriptor::GetFeatureName() const
    {
        return m_feature_name.c_str();
    }
1176

1177 1178 1179 1180
    CvPoint OneWayDescriptor::GetCenter() const
    {
        return m_center;
    }
1181

1182 1183 1184 1185
    int OneWayDescriptor::GetPCADimLow() const
    {
        return m_pca_dim_low;
    }
1186

1187 1188 1189 1190 1191 1192 1193 1194 1195
    int OneWayDescriptor::GetPCADimHigh() const
    {
        return m_pca_dim_high;
    }

    CvMat* ConvertImageToMatrix(IplImage* patch)
    {
        CvRect roi = cvGetImageROI(patch);
        CvMat* mat = cvCreateMat(1, roi.width*roi.height, CV_32FC1);
1196

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        if(patch->depth == 32)
        {
            for(int y = 0; y < roi.height; y++)
            {
                for(int x = 0; x < roi.width; x++)
                {
                    mat->data.fl[y*roi.width + x] = *((float*)(patch->imageData + (y + roi.y)*patch->widthStep) + x + roi.x);
                }
            }
        }
        else if(patch->depth == 8)
        {
            for(int y = 0; y < roi.height; y++)
            {
                for(int x = 0; x < roi.width; x++)
                {
                    mat->data.fl[y*roi.width + x] = (float)(unsigned char)patch->imageData[(y + roi.y)*patch->widthStep + x + roi.x];
                }
            }
        }
        else
        {
            printf("Image depth %d is not supported\n", patch->depth);
            return 0;
        }
1222

1223 1224
        return mat;
    }
1225

1226 1227 1228
    OneWayDescriptorBase::OneWayDescriptorBase(CvSize patch_size, int pose_count, const char* train_path,
                                               const char* pca_config, const char* pca_hr_config,
                                               const char* pca_desc_config, int pyr_levels,
1229 1230
                                               int pca_dim_high, int pca_dim_low)
    : m_pca_dim_high(pca_dim_high), m_pca_dim_low(pca_dim_low), scale_min (0.7f), scale_max(1.5f), scale_step (1.2f)
1231
    {
1232 1233 1234 1235
#if defined(_KDTREE)
        m_pca_descriptors_matrix = 0;
        m_pca_descriptors_tree = 0;
#endif
1236
        //  m_pca_descriptors_matrix = 0;
1237 1238 1239 1240 1241
        m_patch_size = patch_size;
        m_pose_count = pose_count;
        m_pyr_levels = pyr_levels;
        m_poses = 0;
        m_transforms = 0;
1242

1243 1244 1245 1246 1247
        m_pca_avg = 0;
        m_pca_eigenvectors = 0;
        m_pca_hr_avg = 0;
        m_pca_hr_eigenvectors = 0;
        m_pca_descriptors = 0;
1248

1249
        m_descriptors = 0;
1250

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
        if(train_path == 0 || strlen(train_path) == 0)
        {
            // skip pca loading
            return;
        }
        char pca_config_filename[1024];
        sprintf(pca_config_filename, "%s/%s", train_path, pca_config);
        readPCAFeatures(pca_config_filename, &m_pca_avg, &m_pca_eigenvectors);
        if(pca_hr_config && strlen(pca_hr_config) > 0)
        {
            char pca_hr_config_filename[1024];
            sprintf(pca_hr_config_filename, "%s/%s", train_path, pca_hr_config);
            readPCAFeatures(pca_hr_config_filename, &m_pca_hr_avg, &m_pca_hr_eigenvectors);
        }
1265

1266
        m_pca_descriptors = new OneWayDescriptor[m_pca_dim_high + 1];
1267

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
#if !defined(_GH_REGIONS)
        if(pca_desc_config && strlen(pca_desc_config) > 0)
            //    if(0)
        {
            //printf("Loading the descriptors...");
            char pca_desc_config_filename[1024];
            sprintf(pca_desc_config_filename, "%s/%s", train_path, pca_desc_config);
            LoadPCADescriptors(pca_desc_config_filename);
            //printf("done.\n");
        }
        else
        {
            printf("Initializing the descriptors...\n");
            InitializePoseTransforms();
            CreatePCADescriptors();
            SavePCADescriptors("pca_descriptors.yml");
        }
#endif //_GH_REGIONS
        //    SavePCADescriptors("./pca_descriptors.yml");
1287

1288
    }
1289 1290

    OneWayDescriptorBase::OneWayDescriptorBase(CvSize patch_size, int pose_count, const string &pca_filename,
1291 1292 1293 1294
                                               const string &train_path, const string &images_list, float _scale_min, float _scale_max,
                                               float _scale_step, int pyr_levels,
                                               int pca_dim_high, int pca_dim_low)
    : m_pca_dim_high(pca_dim_high), m_pca_dim_low(pca_dim_low), scale_min(_scale_min), scale_max(_scale_max), scale_step(_scale_step)
1295
    {
1296 1297 1298 1299
#if defined(_KDTREE)
        m_pca_descriptors_matrix = 0;
        m_pca_descriptors_tree = 0;
#endif
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
        m_patch_size = patch_size;
        m_pose_count = pose_count;
        m_pyr_levels = pyr_levels;
        m_poses = 0;
        m_transforms = 0;

        m_pca_avg = 0;
        m_pca_eigenvectors = 0;
        m_pca_hr_avg = 0;
        m_pca_hr_eigenvectors = 0;
        m_pca_descriptors = 0;

        m_descriptors = 0;

1314 1315 1316 1317 1318 1319

        if (pca_filename.length() == 0)
        {
            return;
        }

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
        CvFileStorage* fs = cvOpenFileStorage(pca_filename.c_str(), NULL, CV_STORAGE_READ);
        if (fs != 0)
        {
            cvReleaseFileStorage(&fs);

            readPCAFeatures(pca_filename.c_str(), &m_pca_avg, &m_pca_eigenvectors, "_lr");
            readPCAFeatures(pca_filename.c_str(), &m_pca_hr_avg, &m_pca_hr_eigenvectors, "_hr");
            m_pca_descriptors = new OneWayDescriptor[m_pca_dim_high + 1];
#if !defined(_GH_REGIONS)
            LoadPCADescriptors(pca_filename.c_str());
#endif //_GH_REGIONS
        }
        else
        {
            GeneratePCA(train_path.c_str(), images_list.c_str());
            m_pca_descriptors = new OneWayDescriptor[m_pca_dim_high + 1];
            char pca_default_filename[1024];
            sprintf(pca_default_filename, "%s/%s", train_path.c_str(), GetPCAFilename().c_str());
            LoadPCADescriptors(pca_default_filename);
        }
    }
1341

1342
    void OneWayDescriptorBase::Read (const FileNode &fn)
1343
    {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        clear ();

        m_pose_count = fn["poseCount"];
        int patch_width = fn["patchWidth"];
        int patch_height = fn["patchHeight"];
        m_patch_size = cvSize (patch_width, patch_height);
        m_pyr_levels = fn["pyrLevels"];
        m_pca_dim_high = fn["pcaDimHigh"];
        m_pca_dim_low = fn["pcaDimLow"];
        scale_min = fn["minScale"];
        scale_max = fn["maxScale"];
        scale_step = fn["stepScale"];
1356 1357

    LoadPCAall (fn);
1358
    }
1359

1360 1361
    void OneWayDescriptorBase::LoadPCAall (const FileNode &fn)
    {
1362 1363 1364 1365 1366 1367 1368
        readPCAFeatures(fn, &m_pca_avg, &m_pca_eigenvectors, "_lr");
        readPCAFeatures(fn, &m_pca_hr_avg, &m_pca_hr_eigenvectors, "_hr");
        m_pca_descriptors = new OneWayDescriptor[m_pca_dim_high + 1];
#if !defined(_GH_REGIONS)
        LoadPCADescriptors(fn);
#endif //_GH_REGIONS
    }
1369

1370 1371 1372 1373
    OneWayDescriptorBase::~OneWayDescriptorBase()
    {
        cvReleaseMat(&m_pca_avg);
        cvReleaseMat(&m_pca_eigenvectors);
1374

1375 1376 1377 1378 1379 1380
        if(m_pca_hr_eigenvectors)
        {
            delete[] m_pca_descriptors;
            cvReleaseMat(&m_pca_hr_avg);
            cvReleaseMat(&m_pca_hr_eigenvectors);
        }
1381 1382


1383 1384 1385 1386 1387
        if(m_descriptors)
            delete []m_descriptors;

        if(m_poses)
            delete []m_poses;
1388

1389
        if (m_transforms)
1390
        {
1391 1392 1393 1394 1395
            for(int i = 0; i < m_pose_count; i++)
            {
                cvReleaseMat(&m_transforms[i]);
            }
            delete []m_transforms;
1396 1397
        }
#if defined(_KDTREE)
1398 1399 1400 1401 1402 1403 1404 1405
        if (m_pca_descriptors_matrix)
        {
            cvReleaseMat(&m_pca_descriptors_matrix);
        }
        if (m_pca_descriptors_tree)
        {
            delete m_pca_descriptors_tree;
        }
1406 1407
#endif
    }
1408

1409
    void OneWayDescriptorBase::clear(){
1410 1411 1412 1413 1414
        if (m_descriptors)
        {
            delete []m_descriptors;
            m_descriptors = 0;
        }
1415 1416

#if defined(_KDTREE)
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        if (m_pca_descriptors_matrix)
        {
            cvReleaseMat(&m_pca_descriptors_matrix);
            m_pca_descriptors_matrix = 0;
        }
        if (m_pca_descriptors_tree)
        {
            delete m_pca_descriptors_tree;
            m_pca_descriptors_tree = 0;
        }
1427 1428 1429
#endif
    }

1430 1431 1432 1433 1434 1435 1436 1437
    void OneWayDescriptorBase::InitializePoses()
    {
        m_poses = new CvAffinePose[m_pose_count];
        for(int i = 0; i < m_pose_count; i++)
        {
            m_poses[i] = GenRandomAffinePose();
        }
    }
1438

1439 1440 1441 1442 1443 1444 1445 1446 1447
    void OneWayDescriptorBase::InitializeTransformsFromPoses()
    {
        m_transforms = new CvMat*[m_pose_count];
        for(int i = 0; i < m_pose_count; i++)
        {
            m_transforms[i] = cvCreateMat(2, 3, CV_32FC1);
            GenerateAffineTransformFromPose(cvSize(m_patch_size.width*2, m_patch_size.height*2), m_poses[i], m_transforms[i]);
        }
    }
1448

1449 1450 1451 1452 1453
    void OneWayDescriptorBase::InitializePoseTransforms()
    {
        InitializePoses();
        InitializeTransformsFromPoses();
    }
1454

1455 1456
    void OneWayDescriptorBase::InitializeDescriptor(int desc_idx, IplImage* train_image, const KeyPoint& keypoint, const char* feature_label)
    {
1457

1458 1459
        // TBD add support for octave != 0
        CvPoint center = keypoint.pt;
1460

1461 1462 1463 1464 1465 1466 1467 1468
        CvRect roi = cvRect(center.x - m_patch_size.width/2, center.y - m_patch_size.height/2, m_patch_size.width, m_patch_size.height);
        cvResetImageROI(train_image);
        roi = fit_rect_fixedsize(roi, train_image);
        cvSetImageROI(train_image, roi);
        if(roi.width != m_patch_size.width || roi.height != m_patch_size.height)
        {
            return;
        }
1469

1470 1471 1472
        InitializeDescriptor(desc_idx, train_image, feature_label);
        cvResetImageROI(train_image);
    }
1473

1474 1475 1476 1477 1478
    void OneWayDescriptorBase::InitializeDescriptor(int desc_idx, IplImage* train_image, const char* feature_label)
    {
        m_descriptors[desc_idx].SetPCADimHigh(m_pca_dim_high);
        m_descriptors[desc_idx].SetPCADimLow(m_pca_dim_low);
        m_descriptors[desc_idx].SetTransforms(m_poses, m_transforms);
1479

1480 1481 1482 1483 1484 1485 1486 1487 1488
        if(!m_pca_hr_eigenvectors)
        {
            m_descriptors[desc_idx].Initialize(m_pose_count, train_image, feature_label);
        }
        else
        {
            m_descriptors[desc_idx].InitializeFast(m_pose_count, train_image, feature_label,
                                                   m_pca_hr_avg, m_pca_hr_eigenvectors, m_pca_descriptors);
        }
1489

1490 1491 1492 1493 1494
        if(m_pca_avg)
        {
            m_descriptors[desc_idx].InitializePCACoeffs(m_pca_avg, m_pca_eigenvectors);
        }
    }
1495

1496 1497 1498 1499 1500 1501
    void OneWayDescriptorBase::FindDescriptor(IplImage* src, cv::Point2f pt, int& desc_idx, int& pose_idx, float& distance) const
    {
        CvRect roi = cvRect(cvRound(pt.x - m_patch_size.width/4),
                            cvRound(pt.y - m_patch_size.height/4),
                            m_patch_size.width/2, m_patch_size.height/2);
        cvSetImageROI(src, roi);
1502

1503
        FindDescriptor(src, desc_idx, pose_idx, distance);
1504
        cvResetImageROI(src);
1505
    }
1506

1507 1508 1509 1510 1511
    void OneWayDescriptorBase::FindDescriptor(IplImage* patch, int& desc_idx, int& pose_idx, float& distance, float* _scale, float* scale_ranges) const
    {
#if 0
        ::FindOneWayDescriptor(m_train_feature_count, m_descriptors, patch, desc_idx, pose_idx, distance, m_pca_avg, m_pca_eigenvectors);
#else
1512 1513 1514
        float min = scale_min;
        float max = scale_max;
        float step = scale_step;
1515

1516 1517
        if (scale_ranges)
        {
1518 1519
            min = scale_ranges[0];
            max = scale_ranges[1];
1520
        }
1521

1522
        float scale = 1.0f;
1523

1524 1525
#if !defined(_KDTREE)
        cv::FindOneWayDescriptorEx(m_train_feature_count, m_descriptors, patch,
1526
                                   min, max, step, desc_idx, pose_idx, distance, scale,
1527 1528 1529
                                   m_pca_avg, m_pca_eigenvectors);
#else
        cv::FindOneWayDescriptorEx(m_pca_descriptors_tree, m_descriptors[0].GetPatchSize(), m_descriptors[0].GetPCADimLow(), m_pose_count, patch,
1530
                                   min, max, step, desc_idx, pose_idx, distance, scale,
1531 1532
                                   m_pca_avg, m_pca_eigenvectors);
#endif
1533

1534 1535
        if (_scale)
            *_scale = scale;
1536

1537 1538
#endif
    }
1539

1540 1541 1542
    void OneWayDescriptorBase::FindDescriptor(IplImage* patch, int n, std::vector<int>& desc_idxs, std::vector<int>& pose_idxs,
                                              std::vector<float>& distances, std::vector<float>& _scales, float* scale_ranges) const
    {
1543 1544 1545
        float min = scale_min;
        float max = scale_max;
        float step = scale_step;
1546

1547 1548
        if (scale_ranges)
        {
1549 1550
            min = scale_ranges[0];
            max = scale_ranges[1];
1551
        }
1552

1553 1554 1555 1556 1557
        distances.resize(n);
        _scales.resize(n);
        desc_idxs.resize(n);
        pose_idxs.resize(n);
        /*float scales = 1.0f;*/
1558

1559
        cv::FindOneWayDescriptorEx(m_train_feature_count, m_descriptors, patch,
1560
                                   min, max, step ,n, desc_idxs, pose_idxs, distances, _scales,
1561
                                   m_pca_avg, m_pca_eigenvectors);
1562

1563
    }
1564

1565 1566 1567 1568 1569
    void OneWayDescriptorBase::SetPCAHigh(CvMat* avg, CvMat* eigenvectors)
    {
        m_pca_hr_avg = cvCloneMat(avg);
        m_pca_hr_eigenvectors = cvCloneMat(eigenvectors);
    }
1570

1571 1572 1573 1574 1575
    void OneWayDescriptorBase::SetPCALow(CvMat* avg, CvMat* eigenvectors)
    {
        m_pca_avg = cvCloneMat(avg);
        m_pca_eigenvectors = cvCloneMat(eigenvectors);
    }
1576

1577 1578 1579 1580 1581 1582 1583 1584 1585
    void OneWayDescriptorBase::AllocatePCADescriptors()
    {
        m_pca_descriptors = new OneWayDescriptor[m_pca_dim_high + 1];
        for(int i = 0; i < m_pca_dim_high + 1; i++)
        {
            m_pca_descriptors[i].SetPCADimHigh(m_pca_dim_high);
            m_pca_descriptors[i].SetPCADimLow(m_pca_dim_low);
        }
    }
1586

1587 1588 1589 1590 1591 1592 1593
    void OneWayDescriptorBase::CreatePCADescriptors()
    {
        if(m_pca_descriptors == 0)
        {
            AllocatePCADescriptors();
        }
        IplImage* frontal = cvCreateImage(m_patch_size, IPL_DEPTH_32F, 1);
1594

1595 1596 1597
        eigenvector2image(m_pca_hr_avg, frontal);
        m_pca_descriptors[0].SetTransforms(m_poses, m_transforms);
        m_pca_descriptors[0].Initialize(m_pose_count, frontal, "", 0);
1598

1599 1600 1601 1602 1603
        for(int j = 0; j < m_pca_dim_high; j++)
        {
            CvMat eigenvector;
            cvGetSubRect(m_pca_hr_eigenvectors, &eigenvector, cvRect(0, j, m_pca_hr_eigenvectors->cols, 1));
            eigenvector2image(&eigenvector, frontal);
1604

1605 1606
            m_pca_descriptors[j + 1].SetTransforms(m_poses, m_transforms);
            m_pca_descriptors[j + 1].Initialize(m_pose_count, frontal, "", 0);
1607

1608 1609
            printf("Created descriptor for PCA component %d\n", j);
        }
1610

1611 1612
        cvReleaseImage(&frontal);
    }
1613 1614


1615 1616
    int OneWayDescriptorBase::LoadPCADescriptors(const char* filename)
    {
1617 1618
        FileStorage fs = FileStorage (filename, FileStorage::READ);
        if(!fs.isOpened ())
1619 1620 1621 1622
        {
            printf("File %s not found...\n", filename);
            return 0;
        }
1623 1624 1625 1626 1627

        LoadPCADescriptors (fs.root ());

        printf("Successfully read %d pca components\n", m_pca_dim_high);
        fs.release ();
1628

1629 1630 1631 1632 1633
        return 1;
    }

    int OneWayDescriptorBase::LoadPCADescriptors(const FileNode &fn)
    {
1634
        // read affine poses
1635 1636 1637 1638 1639 1640 1641
//            FileNode* node = cvGetFileNodeByName(fs, 0, "affine poses");
        CvMat* poses = reinterpret_cast<CvMat*> (fn["affine_poses"].readObj ());
        if (poses == 0)
        {
            poses = reinterpret_cast<CvMat*> (fn["affine poses"].readObj ());
            if (poses == 0)
                return 0;
1642
        }
1643 1644 1645


        if(m_poses)
1646
        {
1647
            delete m_poses;
1648
        }
1649 1650
        m_poses = new CvAffinePose[m_pose_count];
        for(int i = 0; i < m_pose_count; i++)
1651
        {
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
            m_poses[i].phi = (float)cvmGet(poses, i, 0);
            m_poses[i].theta = (float)cvmGet(poses, i, 1);
            m_poses[i].lambda1 = (float)cvmGet(poses, i, 2);
            m_poses[i].lambda2 = (float)cvmGet(poses, i, 3);
        }
        cvReleaseMat(&poses);

        // now initialize pose transforms
        InitializeTransformsFromPoses();

        m_pca_dim_high = (int) fn["pca_components_number"];
        if (m_pca_dim_high == 0)
        {
            m_pca_dim_high = (int) fn["pca components number"];
        }
        if(m_pca_descriptors)
        {
            delete []m_pca_descriptors;
        }
        AllocatePCADescriptors();
        for(int i = 0; i < m_pca_dim_high + 1; i++)
        {
            m_pca_descriptors[i].Allocate(m_pose_count, m_patch_size, 1);
            m_pca_descriptors[i].SetTransforms(m_poses, m_transforms);
            char buf[1024];
            sprintf(buf, "descriptor_for_pca_component_%d", i);

            if (! m_pca_descriptors[i].ReadByName(fn, buf))
1680 1681
            {
                sprintf(buf, "descriptor for pca component %d", i);
1682
                m_pca_descriptors[i].ReadByName(fn, buf);
1683 1684 1685 1686
            }
        }
        return 1;
    }
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712


    void savePCAFeatures(FileStorage &fs, const char* postfix, CvMat* avg, CvMat* eigenvectors)
    {
        char buf[1024];
        sprintf(buf, "avg_%s", postfix);
        fs.writeObj(buf, avg);
        sprintf(buf, "eigenvectors_%s", postfix);
        fs.writeObj(buf, eigenvectors);
    }

    void calcPCAFeatures(vector<IplImage*>& patches, FileStorage &fs, const char* postfix, CvMat** avg,
                         CvMat** eigenvectors)
    {
        int width = patches[0]->width;
        int height = patches[0]->height;
        int length = width * height;
        int patch_count = (int)patches.size();

        CvMat* data = cvCreateMat(patch_count, length, CV_32FC1);
        *avg = cvCreateMat(1, length, CV_32FC1);
        CvMat* eigenvalues = cvCreateMat(1, length, CV_32FC1);
        *eigenvectors = cvCreateMat(length, length, CV_32FC1);

        for (int i = 0; i < patch_count; i++)
        {
1713
            float nf = (float)(1./cvSum(patches[i]).val[0]);
1714 1715 1716 1717 1718
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    *((float*)(data->data.ptr + data->step * i) + y * width + x)
1719
                            = (unsigned char)patches[i]->imageData[y * patches[i]->widthStep + x] * nf;
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
                }
            }
        }

        //printf("Calculating PCA...");
        cvCalcPCA(data, *avg, eigenvalues, *eigenvectors, CV_PCA_DATA_AS_ROW);
        //printf("done\n");

        // save pca data
        savePCAFeatures(fs, postfix, *avg, *eigenvectors);

        cvReleaseMat(&data);
        cvReleaseMat(&eigenvalues);
    }

1735
    static void extractPatches (IplImage *img, vector<IplImage*>& patches, CvSize patch_size)
1736 1737
    {
        vector<KeyPoint> features;
1738 1739 1740 1741
        Ptr<FeatureDetector> surf_extractor = FeatureDetector::create("SURF");
        if( surf_extractor.empty() )
            CV_Error(CV_StsNotImplemented, "OpenCV was built without SURF support");
        surf_extractor->set("hessianThreshold", 1.0);
1742
        //printf("Extracting SURF features...");
1743
        surf_extractor->detect(Mat(img), features);
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
        //printf("done\n");

        for (int j = 0; j < (int)features.size(); j++)
        {
            int patch_width = patch_size.width;
            int patch_height = patch_size.height;

            CvPoint center = features[j].pt;

            CvRect roi = cvRect(center.x - patch_width / 2, center.y - patch_height / 2, patch_width, patch_height);
            cvSetImageROI(img, roi);
            roi = cvGetImageROI(img);
            if (roi.width != patch_width || roi.height != patch_height)
            {
                continue;
            }

            IplImage* patch = cvCreateImage(cvSize(patch_width, patch_height), IPL_DEPTH_8U, 1);
            cvCopy(img, patch);
            patches.push_back(patch);
            cvResetImageROI(img);
        }
        //printf("Completed file, extracted %d features\n", (int)features.size());
    }

/*
    void loadPCAFeatures(const FileNode &fn, vector<IplImage*>& patches, CvSize patch_size)
    {
        FileNodeIterator begin = fn.begin();
        for (FileNodeIterator i = fn.begin(); i != fn.end(); i++)
        {
            IplImage *img = reinterpret_cast<IplImage*> ((*i).readObj());
            extractPatches (img, patches, patch_size);
            cvReleaseImage(&img);
        }
    }
*/

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
    void loadPCAFeatures(const char* path, const char* images_list, vector<IplImage*>& patches, CvSize patch_size)
    {
        char images_filename[1024];
        sprintf(images_filename, "%s/%s", path, images_list);
        FILE *pFile = fopen(images_filename, "r");
        if (pFile == 0)
        {
            printf("Cannot open images list file %s\n", images_filename);
            return;
        }
        while (!feof(pFile))
        {
            char imagename[1024];
            if (fscanf(pFile, "%s", imagename) <= 0)
            {
                break;
            }

            char filename[1024];
            sprintf(filename, "%s/%s", path, imagename);

            //printf("Reading image %s...", filename);
1804 1805 1806 1807 1808 1809
            IplImage* img = 0;
#ifdef HAVE_OPENCV_HIGHGUI
            img = cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE);
#else
            CV_Error(CV_StsNotImplemented, "OpenCV has been compiled without image I/O support");
#endif
1810 1811
            //printf("done\n");

1812
            extractPatches (img, patches, patch_size);
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

            cvReleaseImage(&img);
        }
        fclose(pFile);
    }

    void generatePCAFeatures(const char* path, const char* img_filename, FileStorage& fs, const char* postfix,
                             CvSize patch_size, CvMat** avg, CvMat** eigenvectors)
    {
        vector<IplImage*> patches;
        loadPCAFeatures(path, img_filename, patches, patch_size);
        calcPCAFeatures(patches, fs, postfix, avg, eigenvectors);
    }

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
/*
    void generatePCAFeatures(const FileNode &fn, const char* postfix,
                             CvSize patch_size, CvMat** avg, CvMat** eigenvectors)
    {
        vector<IplImage*> patches;
        loadPCAFeatures(fn, patches, patch_size);
        calcPCAFeatures(patches, fs, postfix, avg, eigenvectors);
    }


    void OneWayDescriptorBase::GeneratePCA(const FileNode &fn, int pose_count)
    {
        generatePCAFeatures(fn, "hr", m_patch_size, &m_pca_hr_avg, &m_pca_hr_eigenvectors);
        generatePCAFeatures(fn, "lr", cvSize(m_patch_size.width / 2, m_patch_size.height / 2),
                            &m_pca_avg, &m_pca_eigenvectors);


        OneWayDescriptorBase descriptors(m_patch_size, pose_count);
        descriptors.SetPCAHigh(m_pca_hr_avg, m_pca_hr_eigenvectors);
        descriptors.SetPCALow(m_pca_avg, m_pca_eigenvectors);

        printf("Calculating %d PCA descriptors (you can grab a coffee, this will take a while)...\n",
               descriptors.GetPCADimHigh());
        descriptors.InitializePoseTransforms();
        descriptors.CreatePCADescriptors();
        descriptors.SavePCADescriptors(*fs);
    }
*/

1856
    void OneWayDescriptorBase::GeneratePCA(const char* img_path, const char* images_list, int pose_count)
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
    {
        char pca_filename[1024];
        sprintf(pca_filename, "%s/%s", img_path, GetPCAFilename().c_str());
        FileStorage fs = FileStorage(pca_filename, FileStorage::WRITE);

        generatePCAFeatures(img_path, images_list, fs, "hr", m_patch_size, &m_pca_hr_avg, &m_pca_hr_eigenvectors);
        generatePCAFeatures(img_path, images_list, fs, "lr", cvSize(m_patch_size.width / 2, m_patch_size.height / 2),
                            &m_pca_avg, &m_pca_eigenvectors);

        OneWayDescriptorBase descriptors(m_patch_size, pose_count);
        descriptors.SetPCAHigh(m_pca_hr_avg, m_pca_hr_eigenvectors);
        descriptors.SetPCALow(m_pca_avg, m_pca_eigenvectors);

        printf("Calculating %d PCA descriptors (you can grab a coffee, this will take a while)...\n",
               descriptors.GetPCADimHigh());
        descriptors.InitializePoseTransforms();
        descriptors.CreatePCADescriptors();
        descriptors.SavePCADescriptors(*fs);

        fs.release();
    }

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
    void OneWayDescriptorBase::Write (FileStorage &fs) const
    {
        fs << "poseCount" << m_pose_count;
        fs << "patchWidth" << m_patch_size.width;
        fs << "patchHeight" << m_patch_size.height;
        fs << "minScale" << scale_min;
        fs << "maxScale" << scale_max;
        fs << "stepScale" << scale_step;
        fs << "pyrLevels" << m_pyr_levels;
        fs << "pcaDimHigh" << m_pca_dim_high;
        fs << "pcaDimLow" << m_pca_dim_low;

        SavePCAall (fs);
    }

1894 1895 1896 1897 1898 1899 1900
    void OneWayDescriptorBase::SavePCAall (FileStorage &fs) const
    {
        savePCAFeatures(fs, "hr", m_pca_hr_avg, m_pca_hr_eigenvectors);
        savePCAFeatures(fs, "lr", m_pca_avg, m_pca_eigenvectors);
        SavePCADescriptors(*fs);
    }

1901 1902 1903 1904
    void OneWayDescriptorBase::SavePCADescriptors(const char* filename)
    {
        CvMemStorage* storage = cvCreateMemStorage();
        CvFileStorage* fs = cvOpenFileStorage(filename, storage, CV_STORAGE_WRITE);
1905

1906
        SavePCADescriptors (fs);
1907

1908 1909 1910
        cvReleaseMemStorage(&storage);
        cvReleaseFileStorage(&fs);
    }
1911

1912
    void OneWayDescriptorBase::SavePCADescriptors(CvFileStorage *fs) const
1913
    {
1914
        cvWriteInt(fs, "pca_components_number", m_pca_dim_high);
1915 1916 1917 1918
        cvWriteComment(
                       fs,
                       "The first component is the average Vector, so the total number of components is <pca components number> + 1",
                       0);
1919 1920
        cvWriteInt(fs, "patch_width", m_patch_size.width);
        cvWriteInt(fs, "patch_height", m_patch_size.height);
1921

1922 1923
        // pack the affine transforms into a single CvMat and write them
        CvMat* poses = cvCreateMat(m_pose_count, 4, CV_32FC1);
1924
        for (int i = 0; i < m_pose_count; i++)
1925 1926 1927 1928 1929 1930
        {
            cvmSet(poses, i, 0, m_poses[i].phi);
            cvmSet(poses, i, 1, m_poses[i].theta);
            cvmSet(poses, i, 2, m_poses[i].lambda1);
            cvmSet(poses, i, 3, m_poses[i].lambda2);
        }
1931
        cvWrite(fs, "affine_poses", poses);
1932
        cvReleaseMat(&poses);
1933 1934

        for (int i = 0; i < m_pca_dim_high + 1; i++)
1935 1936
        {
            char buf[1024];
1937
            sprintf(buf, "descriptor_for_pca_component_%d", i);
1938 1939 1940
            m_pca_descriptors[i].Write(fs, buf);
        }
    }
1941 1942


1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
    void OneWayDescriptorBase::Allocate(int train_feature_count)
    {
        m_train_feature_count = train_feature_count;
        m_descriptors = new OneWayDescriptor[m_train_feature_count];
        for(int i = 0; i < m_train_feature_count; i++)
        {
            m_descriptors[i].SetPCADimHigh(m_pca_dim_high);
            m_descriptors[i].SetPCADimLow(m_pca_dim_low);
        }
    }
1953

1954 1955 1956 1957 1958 1959
    void OneWayDescriptorBase::InitializeDescriptors(IplImage* train_image, const vector<KeyPoint>& features,
                                                     const char* feature_label, int desc_start_idx)
    {
        for(int i = 0; i < (int)features.size(); i++)
        {
            InitializeDescriptor(desc_start_idx + i, train_image, features[i], feature_label);
1960

1961 1962
        }
        cvResetImageROI(train_image);
1963

1964 1965 1966 1967
#if defined(_KDTREE)
        ConvertDescriptorsArrayToTree();
#endif
    }
1968

1969 1970 1971
    void OneWayDescriptorBase::CreateDescriptorsFromImage(IplImage* src, const std::vector<KeyPoint>& features)
    {
        m_train_feature_count = (int)features.size();
1972

1973
        m_descriptors = new OneWayDescriptor[m_train_feature_count];
1974

1975
        InitializeDescriptors(src, features);
1976

1977
    }
1978

1979 1980 1981 1982 1983 1984 1985
#if defined(_KDTREE)
    void OneWayDescriptorBase::ConvertDescriptorsArrayToTree()
    {
        int n = this->GetDescriptorCount();
        if (n<1)
            return;
        int pca_dim_low = this->GetDescriptor(0)->GetPCADimLow();
1986

1987
        //if (!m_pca_descriptors_matrix)
1988
        //  m_pca_descriptors_matrix = new ::cvflann::Matrix<float>(n*m_pose_count,pca_dim_low);
1989 1990
        //else
        //{
1991 1992 1993 1994 1995
        //  if ((m_pca_descriptors_matrix->cols != pca_dim_low)&&(m_pca_descriptors_matrix->rows != n*m_pose_count))
        //  {
        //      delete m_pca_descriptors_matrix;
        //      m_pca_descriptors_matrix = new ::cvflann::Matrix<float>(n*m_pose_count,pca_dim_low);
        //  }
1996
        //}
1997

1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
        m_pca_descriptors_matrix = cvCreateMat(n*m_pose_count,pca_dim_low,CV_32FC1);
        for (int i=0;i<n;i++)
        {
            CvMat** pca_coeffs = m_descriptors[i].GetPCACoeffs();
            for (int j = 0;j<m_pose_count;j++)
            {
                for (int k=0;k<pca_dim_low;k++)
                {
                    m_pca_descriptors_matrix->data.fl[(i*m_pose_count+j)*m_pca_dim_low + k] = pca_coeffs[j]->data.fl[k];
                }
            }
        }
        cv::Mat pca_descriptors_mat(m_pca_descriptors_matrix,false);
2011

2012
        //::cvflann::KDTreeIndexParams params;
2013 2014
        //params.trees = 1;
        //m_pca_descriptors_tree = new KDTree(pca_descriptors_mat);
2015
        m_pca_descriptors_tree = new cv::flann::Index(pca_descriptors_mat,cv::flann::KDTreeIndexParams(1));
2016 2017 2018 2019
        //cvReleaseMat(&m_pca_descriptors_matrix);
        //m_pca_descriptors_tree->buildIndex();
    }
#endif
2020

2021 2022 2023 2024
    void OneWayDescriptorObject::Allocate(int train_feature_count, int object_feature_count)
    {
        OneWayDescriptorBase::Allocate(train_feature_count);
        m_object_feature_count = object_feature_count;
2025

2026 2027
        m_part_id = new int[m_object_feature_count];
    }
2028 2029


2030 2031 2032 2033
    void OneWayDescriptorObject::InitializeObjectDescriptors(IplImage* train_image, const vector<KeyPoint>& features,
                                                             const char* feature_label, int desc_start_idx, float scale, int is_background)
    {
        InitializeDescriptors(train_image, features, feature_label, desc_start_idx);
2034

2035 2036 2037
        for(int i = 0; i < (int)features.size(); i++)
        {
            CvPoint center = features[i].pt;
2038

2039 2040 2041 2042 2043 2044 2045 2046 2047
            if(!is_background)
            {
                // remember descriptor part id
                CvPoint center_scaled = cvPoint(round(center.x*scale), round(center.y*scale));
                m_part_id[i + desc_start_idx] = MatchPointToPart(center_scaled);
            }
        }
        cvResetImageROI(train_image);
    }
2048

2049 2050 2051 2052
    int OneWayDescriptorObject::IsDescriptorObject(int desc_idx) const
    {
        return desc_idx < m_object_feature_count ? 1 : 0;
    }
2053

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    int OneWayDescriptorObject::MatchPointToPart(CvPoint pt) const
    {
        int idx = -1;
        const int max_dist = 10;
        for(int i = 0; i < (int)m_train_features.size(); i++)
        {
            if(norm(Point2f(pt) - m_train_features[i].pt) < max_dist)
            {
                idx = i;
                break;
            }
        }
2066

2067 2068
        return idx;
    }
2069

2070 2071 2072 2073 2074
    int OneWayDescriptorObject::GetDescriptorPart(int desc_idx) const
    {
        //    return MatchPointToPart(GetDescriptor(desc_idx)->GetCenter());
        return desc_idx < m_object_feature_count ? m_part_id[desc_idx] : -1;
    }
2075

2076 2077 2078 2079 2080 2081
    OneWayDescriptorObject::OneWayDescriptorObject(CvSize patch_size, int pose_count, const char* train_path,
                                                   const char* pca_config, const char* pca_hr_config, const char* pca_desc_config, int pyr_levels) :
    OneWayDescriptorBase(patch_size, pose_count, train_path, pca_config, pca_hr_config, pca_desc_config, pyr_levels)
    {
        m_part_id = 0;
    }
2082

2083
    OneWayDescriptorObject::OneWayDescriptorObject(CvSize patch_size, int pose_count, const string &pca_filename,
2084 2085
                                                   const string &train_path, const string &images_list, float _scale_min, float _scale_max, float _scale_step, int pyr_levels) :
    OneWayDescriptorBase(patch_size, pose_count, pca_filename, train_path, images_list, _scale_min, _scale_max, _scale_step, pyr_levels)
2086 2087 2088 2089
    {
        m_part_id = 0;
    }

2090 2091
    OneWayDescriptorObject::~OneWayDescriptorObject()
    {
2092 2093
        if (m_part_id)
            delete []m_part_id;
2094
    }
2095

2096 2097 2098 2099 2100 2101 2102
    vector<KeyPoint> OneWayDescriptorObject::_GetLabeledFeatures() const
    {
        vector<KeyPoint> features;
        for(size_t i = 0; i < m_train_features.size(); i++)
        {
            features.push_back(m_train_features[i]);
        }
2103

2104 2105
        return features;
    }
2106

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
    void eigenvector2image(CvMat* eigenvector, IplImage* img)
    {
        CvRect roi = cvGetImageROI(img);
        if(img->depth == 32)
        {
            for(int y = 0; y < roi.height; y++)
            {
                for(int x = 0; x < roi.width; x++)
                {
                    float val = (float)cvmGet(eigenvector, 0, roi.width*y + x);
                    *((float*)(img->imageData + (roi.y + y)*img->widthStep) + roi.x + x) = val;
                }
            }
        }
        else
        {
            for(int y = 0; y < roi.height; y++)
            {
                for(int x = 0; x < roi.width; x++)
                {
                    float val = (float)cvmGet(eigenvector, 0, roi.width*y + x);
                    img->imageData[(roi.y + y)*img->widthStep + roi.x + x] = (unsigned char)val;
                }
            }
        }
    }
2133

2134
    void readPCAFeatures(const char* filename, CvMat** avg, CvMat** eigenvectors, const char* postfix)
2135
    {
2136 2137
        FileStorage fs = FileStorage(filename, FileStorage::READ);
        if (!fs.isOpened ())
2138 2139 2140
        {
            printf("Cannot open file %s! Exiting!", filename);
        }
2141

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
        readPCAFeatures (fs.root (), avg, eigenvectors, postfix);
        fs.release ();
    }

    void readPCAFeatures(const FileNode &fn, CvMat** avg, CvMat** eigenvectors, const char* postfix)
    {
        std::string str = std::string ("avg") + postfix;
        CvMat* _avg = reinterpret_cast<CvMat*> (fn[str].readObj());
        if (_avg != 0)
        {
            *avg = cvCloneMat(_avg);
            cvReleaseMat(&_avg);
        }

        str = std::string ("eigenvectors") + postfix;
        CvMat* _eigenvectors = reinterpret_cast<CvMat*> (fn[str].readObj());
        if (_eigenvectors != 0)
        {
            *eigenvectors = cvCloneMat(_eigenvectors);
            cvReleaseMat(&_eigenvectors);
        }
2163
    }
2164

2165 2166 2167
    /****************************************************************************************\
     *                                OneWayDescriptorMatcher                                  *
     \****************************************************************************************/
2168

2169 2170 2171 2172 2173 2174 2175
    OneWayDescriptorMatcher::Params::Params( int _poseCount, Size _patchSize, string _pcaFilename,
                                            string _trainPath, string _trainImagesList,
                                            float _minScale, float _maxScale, float _stepScale ) :
    poseCount(_poseCount), patchSize(_patchSize), pcaFilename(_pcaFilename),
    trainPath(_trainPath), trainImagesList(_trainImagesList),
    minScale(_minScale), maxScale(_maxScale), stepScale(_stepScale)
    {}
2176 2177


2178 2179 2180 2181
    OneWayDescriptorMatcher::OneWayDescriptorMatcher( const Params& _params)
    {
        initialize(_params);
    }
2182

2183 2184
    OneWayDescriptorMatcher::~OneWayDescriptorMatcher()
    {}
2185

2186 2187 2188
    void OneWayDescriptorMatcher::initialize( const Params& _params, const Ptr<OneWayDescriptorBase>& _base )
    {
        clear();
2189

2190 2191
        if( _base.empty() )
            base = _base;
2192

2193 2194
        params = _params;
    }
2195

2196 2197 2198
    void OneWayDescriptorMatcher::clear()
    {
        GenericDescriptorMatcher::clear();
2199

2200 2201 2202 2203
        prevTrainCount = 0;
        if( !base.empty() )
            base->clear();
    }
2204

2205 2206 2207 2208 2209 2210
    void OneWayDescriptorMatcher::train()
    {
        if( base.empty() || prevTrainCount < (int)trainPointCollection.keypointCount() )
        {
            base = new OneWayDescriptorObject( params.patchSize, params.poseCount, params.pcaFilename,
                                              params.trainPath, params.trainImagesList, params.minScale, params.maxScale, params.stepScale );
2211

2212 2213
            base->Allocate( (int)trainPointCollection.keypointCount() );
            prevTrainCount = (int)trainPointCollection.keypointCount();
2214

2215 2216 2217 2218 2219 2220 2221 2222
            const vector<vector<KeyPoint> >& points = trainPointCollection.getKeypoints();
            int count = 0;
            for( size_t i = 0; i < points.size(); i++ )
            {
                IplImage _image = trainPointCollection.getImage((int)i);
                for( size_t j = 0; j < points[i].size(); j++ )
                    base->InitializeDescriptor( count++, &_image, points[i][j], "" );
            }
2223

2224 2225 2226 2227 2228
#if defined(_KDTREE)
            base->ConvertDescriptorsArrayToTree();
#endif
        }
    }
2229

2230 2231 2232 2233
    bool OneWayDescriptorMatcher::isMaskSupported()
    {
        return false;
    }
2234

2235 2236 2237 2238 2239
    void OneWayDescriptorMatcher::knnMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                               vector<vector<DMatch> >& matches, int knn,
                                               const vector<Mat>& /*masks*/, bool /*compactResult*/ )
    {
        train();
2240

2241
        CV_Assert( knn == 1 ); // knn > 1 unsupported because of bug in OneWayDescriptorBase for this case
2242

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
        matches.resize( queryKeypoints.size() );
        IplImage _qimage = queryImage;
        for( size_t i = 0; i < queryKeypoints.size(); i++ )
        {
            int descIdx = -1, poseIdx = -1;
            float distance;
            base->FindDescriptor( &_qimage, queryKeypoints[i].pt, descIdx, poseIdx, distance );
            matches[i].push_back( DMatch((int)i, descIdx, distance) );
        }
    }
2253

2254 2255 2256 2257 2258
    void OneWayDescriptorMatcher::radiusMatchImpl( const Mat& queryImage, vector<KeyPoint>& queryKeypoints,
                                                  vector<vector<DMatch> >& matches, float maxDistance,
                                                  const vector<Mat>& /*masks*/, bool /*compactResult*/ )
    {
        train();
2259

2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
        matches.resize( queryKeypoints.size() );
        IplImage _qimage = queryImage;
        for( size_t i = 0; i < queryKeypoints.size(); i++ )
        {
            int descIdx = -1, poseIdx = -1;
            float distance;
            base->FindDescriptor( &_qimage, queryKeypoints[i].pt, descIdx, poseIdx, distance );
            if( distance < maxDistance )
                matches[i].push_back( DMatch((int)i, descIdx, distance) );
        }
    }
2271

2272 2273 2274 2275 2276 2277
    void OneWayDescriptorMatcher::read( const FileNode &fn )
    {
        base = new OneWayDescriptorObject( params.patchSize, params.poseCount, string (), string (), string (),
                                          params.minScale, params.maxScale, params.stepScale );
        base->Read (fn);
    }
2278

2279 2280 2281 2282
    void OneWayDescriptorMatcher::write( FileStorage& fs ) const
    {
        base->Write (fs);
    }
2283

2284 2285 2286 2287
    bool OneWayDescriptorMatcher::empty() const
    {
        return base.empty() || base->empty();
    }
2288

2289 2290 2291
    Ptr<GenericDescriptorMatcher> OneWayDescriptorMatcher::clone( bool emptyTrainData ) const
    {
        OneWayDescriptorMatcher* matcher = new OneWayDescriptorMatcher( params );
2292

2293 2294 2295 2296
        if( !emptyTrainData )
        {
            CV_Error( CV_StsNotImplemented, "deep clone functionality is not implemented, because "
                     "OneWayDescriptorBase has not copy constructor or clone method ");
2297

2298 2299 2300 2301 2302 2303 2304
            //matcher->base;
            matcher->params = params;
            matcher->prevTrainCount = prevTrainCount;
            matcher->trainPointCollection = trainPointCollection;
        }
        return matcher;
    }
2305
}