forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoneway.cpp
More file actions
2305 lines (1946 loc) · 79.2 KB
/
oneway.cpp
File metadata and controls
2305 lines (1946 loc) · 79.2 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
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
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* cvoneway.cpp
* one_way_sample
*
* Created by Victor Eruhimov on 3/23/10.
* Copyright 2010 Argus Corp. All rights reserved.
*
*/
#include "precomp.hpp"
#include "opencv2/opencv_modules.hpp"
#ifdef HAVE_OPENCV_HIGHGUI
# include "opencv2/highgui/highgui.hpp"
#endif
#include <stdio.h>
namespace cv{
inline int round(float value)
{
if(value > 0)
{
return int(value + 0.5f);
}
else
{
return int(value - 0.5f);
}
}
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));
}
CvMat* ConvertImageToMatrix(IplImage* patch);
class CvCameraPose
{
public:
CvCameraPose()
{
m_rotation = cvCreateMat(1, 3, CV_32FC1);
m_translation = cvCreateMat(1, 3, CV_32FC1);
};
~CvCameraPose()
{
cvReleaseMat(&m_rotation);
cvReleaseMat(&m_translation);
};
void SetPose(CvMat* rotation, CvMat* translation)
{
cvCopy(rotation, m_rotation);
cvCopy(translation, m_translation);
};
CvMat* GetRotation() {return m_rotation;};
CvMat* GetTranslation() {return m_translation;};
protected:
CvMat* m_rotation;
CvMat* m_translation;
};
// 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);
// 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);
// Generates a random affine pose
CvAffinePose GenRandomAffinePose();
const static int num_mean_components = 500;
const static float noise_intensity = 0.15f;
static inline CvPoint rect_center(CvRect rect)
{
return cvPoint(rect.x + rect.width/2, rect.y + rect.height/2);
}
// static void homography_transform(IplImage* frontal, IplImage* result, CvMat* homography)
// {
// cvWarpPerspective(frontal, result, homography);
// }
static CvAffinePose perturbate_pose(CvAffinePose pose, float noise)
{
// perturbate the matrix
float noise_mult_factor = 1 + (0.5f - float(rand())/RAND_MAX)*noise;
float noise_add_factor = noise_mult_factor - 1;
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;
return pose_pert;
}
static void generate_mean_patch(IplImage* frontal, IplImage* result, CvAffinePose pose, int pose_count, float noise)
{
IplImage* sum = cvCreateImage(cvSize(result->width, result->height), IPL_DEPTH_32F, 1);
IplImage* workspace = cvCloneImage(result);
IplImage* workspace_float = cvCloneImage(sum);
cvSetZero(sum);
for(int i = 0; i < pose_count; i++)
{
CvAffinePose pose_pert = perturbate_pose(pose, noise);
AffineTransformPatch(frontal, workspace, pose_pert);
cvConvertScale(workspace, workspace_float);
cvAdd(sum, workspace_float, sum);
}
cvConvertScale(sum, result, 1.0f/pose_count);
cvReleaseImage(&workspace);
cvReleaseImage(&sum);
cvReleaseImage(&workspace_float);
}
// 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++)
// {
// }*/
// }
void readPCAFeatures(const char *filename, CvMat** avg, CvMat** eigenvectors, const char *postfix = "");
void readPCAFeatures(const FileNode &fn, CvMat** avg, CvMat** eigenvectors, const char* postfix = "");
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);
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);
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);
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,
CvMat* avg = 0, CvMat* eigenvalues = 0);
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);
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);
void FindOneWayDescriptorEx(cv::flann::Index* m_pca_descriptors_tree, CvSize patch_size, int m_pca_dim_low, 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);
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);
}
inline CvRect fit_rect_fixedsize(CvRect rect, IplImage* img)
{
CvRect roi = cvGetImageROI(img);
return fit_rect_roi_fixedsize(rect, roi);
}
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;
}
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;
if(!m_transforms)
{
delete []m_affine_poses;
}
}
}
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);
if(!m_transforms)
{
m_affine_poses = new CvAffinePose[m_pose_count];
}
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);
}
m_input_patch = cvCreateImage(GetPatchSize(), IPL_DEPTH_8U, 1);
m_train_patch = cvCreateImage(GetInputPatchSize(), IPL_DEPTH_8U, 1);
}
// 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);
// }
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);
return pose;
}
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);
CvMat rotation;
cvGetSubRect(temp, &rotation, cvRect(0, 0, 3, 2));
cv2DRotationMatrix(cvPoint2D32f(size.width/2, size.height/2), pose.phi, 1.0, &rotation);
cvCopy(temp, final);
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);
cv2DRotationMatrix(cvPoint2D32f(size.width/2, size.height/2), pose.theta - pose.phi, 1.0, &rotation);
cvMatMul(temp, final, final);
cvGetSubRect(final, &rotation, cvRect(0, 0, 3, 2));
cvCopy(&rotation, transform);
cvReleaseMat(&temp);
cvReleaseMat(&final);
}
void AffineTransformPatch(IplImage* src, IplImage* dst, CvAffinePose pose)
{
CvRect src_large_roi = cvGetImageROI(src);
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);
CvSize new_size = cvSize(cvRound(temp->width*pose.lambda1), cvRound(temp->height*pose.lambda2));
IplImage* temp3 = cvCreateImage(new_size, IPL_DEPTH_32F, src->nChannels);
cvConvertScale(src, temp);
cvResetImageROI(temp);
cv2DRotationMatrix(cvPoint2D32f(temp->width/2, temp->height/2), pose.phi, 1.0, rotation_phi);
cvWarpAffine(temp, temp2, rotation_phi);
cvSetZero(temp);
cvResize(temp2, temp3);
cv2DRotationMatrix(cvPoint2D32f(temp3->width/2, temp3->height/2), pose.theta - pose.phi, 1.0, rotation_phi);
cvWarpAffine(temp3, temp, rotation_phi);
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);
cvReleaseImage(&temp3);
cvReleaseImage(&temp2);
cvReleaseImage(&temp);
}
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);
double scale = 1.0f;
if(norm)
{
double sum = cvSum(patch_8u).val[0];
scale = 1/sum;
}
cvConvertScale(patch_8u, m_samples[i], scale);
#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);
}
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;
}
CvMat* pca_coeffs = cvCreateMat(1, pca_hr_eigenvectors->cols, CV_32FC1);
double maxval;
cvMinMaxLoc(frontal, 0, &maxval);
CvMat* frontal_data = ConvertImageToMatrix(frontal);
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]);
#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
}
cvAdd(pca_descriptors[0].GetPatch(i), m_samples[i], m_samples[i]);
double sm = cvSum(m_samples[i]).val[0];
cvConvertScale(m_samples[i], m_samples[i], 1.0/sm);
#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);
cvNamedWindow("1", 1);
cvShowImage("1", frontal);
cvNamedWindow("2", 1);
cvShowImage("2", test);
cvWaitKey(0);
#endif
}
cvReleaseMat(&pca_coeffs);
cvReleaseMat(&frontal_data);
}
void OneWayDescriptor::SetTransforms(CvAffinePose* poses, CvMat** transforms)
{
if(m_affine_poses)
{
delete []m_affine_poses;
}
m_affine_poses = poses;
m_transforms = transforms;
}
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);
Allocate(pose_count, cvSize(roi.width, roi.height), frontal->nChannels);
GenerateSamples(pose_count, frontal, norm);
}
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);
Allocate(pose_count, cvSize(roi.width, roi.height), frontal->nChannels);
GenerateSamplesFast(frontal, pca_hr_avg, pca_hr_eigenvectors, pca_descriptors);
}
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]);
}
}
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);
cvReleaseMat(&temp);
cvReleaseMat(&patch_mat);
}
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
{
}
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);
}
}
CvMat* pca_coeffs = cvCreateMat(1, m_pca_dim_low, CV_32FC1);
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);
}
distance = 1e10;
pose_idx = -1;
for(int i = 0; i < m_pose_count; i++)
{
double dist = cvNorm(m_pca_coeffs[i], pca_coeffs);
// 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);
// }
////#if 1
// 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]);
// }
//#else
// 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]);
// }
//#endif
if(dist < distance)
{
distance = (float)dist;
pose_idx = i;
}
}
cvReleaseMat(&pca_coeffs);
}
void OneWayDescriptor::EstimatePose(IplImage* patch, int& pose_idx, float& distance) const
{
distance = 1e10;
pose_idx = -1;
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);
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;
//for (int y = 0; y<patch_32f->height; y++)
// 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);
// }
if(dist < distance)
{
distance = (float)dist;
pose_idx = i;
}
#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);
cvNamedWindow("1", 1);
cvShowImage("1", img1);
cvNamedWindow("2", 1);
cvShowImage("2", img2);
printf("Distance = %f\n", dist);
cvWaitKey(0);
#endif
}
cvReleaseImage(&patch_32f);
}
void OneWayDescriptor::Save(const char* path)
{
for(int i = 0; i < m_pose_count; i++)
{
char buf[1024];
sprintf(buf, "%s/patch_%04d.png", path, i);
IplImage* patch = cvCreateImage(cvSize(m_samples[i]->width, m_samples[i]->height), IPL_DEPTH_8U, m_samples[i]->nChannels);
double maxval;
cvMinMaxLoc(m_samples[i], 0, &maxval);
cvConvertScale(m_samples[i], patch, 255/maxval);
#ifdef HAVE_OPENCV_HIGHGUI
cvSaveImage(buf, patch);
#else
CV_Error(CV_StsNotImplemented, "OpenCV has been compiled without image I/O support");
#endif
cvReleaseImage(&patch);
}
}
void OneWayDescriptor::Write(CvFileStorage* fs, const char* name)
{
CvMat* mat = cvCreateMat(m_pose_count, m_samples[0]->width*m_samples[0]->height, CV_32FC1);
// 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);
}
}
}
cvWrite(fs, name, mat);
cvReleaseMat(&mat);
}
int OneWayDescriptor::ReadByName(const FileNode &parent, const char* name)
{
CvMat* mat = reinterpret_cast<CvMat*> (parent[name].readObj ());
if(!mat)
{
return 0;
}
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;
}
}
}
cvReleaseMat(&mat);
return 1;
}
int OneWayDescriptor::ReadByName(CvFileStorage* fs, CvFileNode* parent, const char* name)
{
return ReadByName (FileNode (fs, parent), name);
}
IplImage* OneWayDescriptor::GetPatch(int index)
{
return m_samples[index];
}
CvAffinePose OneWayDescriptor::GetPose(int index) const
{
return m_affine_poses[index];
}
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)
{
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);
//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);
}
//--------
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
if (!avg)
{
descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
}
else
{
descriptors[i].EstimatePosePCA(pca_coeffs, _pose_idx, _distance, avg, eigenvectors);
}
#endif
if(_distance < distance)
{
desc_idx = i;
pose_idx = _pose_idx;
distance = _distance;
}
}
cvReleaseMat(&pca_coeffs);
}
#if defined(_KDTREE)
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,
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)
//{
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);
// }
//--------
//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;
// 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
// if (!avg)
// {
// descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
// }
// else
// {
// descriptors[i].EstimatePosePCA(pca_coeffs, _pose_idx, _distance, avg, eigenvectors);
// }
//#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)
{
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);
//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);
}
//--------
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
if (!avg)
{
descriptors[i].EstimatePosePCA(patch, _pose_idx, _distance, avg, eigenvectors);
}