-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtitool.cpp
More file actions
6473 lines (5052 loc) · 203 KB
/
rtitool.cpp
File metadata and controls
6473 lines (5052 loc) · 203 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
#include "rtitool.h"
#include "ui_rtitool.h"
#include <iostream>
#include <fstream>
#include <QFileDialog>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <QInputDialog>
#include <QDebug>
#include <QPixmap>
#include <QPainter>
#include <QFile>
#include <QTime>
#include <QProgressDialog>
#include <QMessageBox>
#include <QtCore/qtextstream.h>
#include "s_hull_pro.h"
using namespace std;
using namespace cv;
bool pointSortPredicate(const Shx& a, const Shx& b)
{
if (a.r < b.r)
return true;
else if (a.r > b.r)
return false;
else if (a.c < b.c)
return true;
else
return false;
};
bool pointComparisonPredicate(const Shx& a, const Shx& b)
{
return a.r == b.r && a.c == b.c;
}
template<class T>struct compare_index
{
const T base_arr;
compare_index (const T arr) : base_arr (arr) {}
bool operator () (int a, int b) const
{
return (base_arr[a] < base_arr[b]);
}
};
void savePTM_LRGB(QString filename, int W, int H, QString chroma_img){
//save the result in the LRGB format
double max[6], min[6];
int bias[6];
char* files[6] = {"file.c1","file.c2","file.c3","file.c4","file.c5","file.c6"};
float scale[6];
float* pBuff;
for (int i = 0; i <= 5; i++){
ifstream coef (files[i], ios::in | ios::binary);
pBuff = new float[W*H];
coef.read((char*)pBuff,W*H*sizeof(float));
min[i] = 99999999999;
max[i] = -99999999999;
for (int x= 0; x < W*H; x++)
{
if(pBuff[x] > max[i]) max[i]=pBuff[x];
if(pBuff[x] < min[i]) min[i]=pBuff[x];
}
scale[i]=(float) 1.0+floor((max[i]-min[i]-1)/256);
bias[i]=(int)(-min[i]/scale[i]);// you can change this value
delete(pBuff);
qDebug() <<"minmax "<<min[i]<< ' ' << max[i] <<'\n';
qDebug() <<"scale "<<int(scale[i])<<'\n';
qDebug() <<"bias "<<int(bias[i])<<'\n';
coef.close();
}
unsigned char* scaledc = new unsigned char[W*H*6];
for (int i = 0; i <= 5; i++){
ifstream coef (files[i], ios::in | ios::binary);
pBuff = new float[W*H];
coef.read((char*)pBuff,W*H*sizeof(float));
coef.close();
for (int x = 0;x<W; x++)
for (int y = 0; y <H; y++)
{
scaledc[x+y*W+W*H*i] = (unsigned char)((pBuff[y*W+x]/scale[i])+(float)bias[i]);
}
delete(pBuff);
}
ofstream outfile;
outfile.open("test.ptm",ios::binary);
outfile << "PTM_1.2\n";
outfile << "PTM_FORMAT_LRGB\n";
outfile << W <<"\n";
outfile << H <<"\n";
QString num;
for (int i = 0; i < 6; i++){
num=QString::number((float)scale[i]);
outfile << num.toStdString()<<" ";
} outfile <<'\n';
for (int i = 0; i < 6; i++){
num=QString::number((int)bias[i]);
outfile << num.toStdString()<<' ';
}outfile <<'\n';
int offset;
unsigned char c;
cv::Mat image;
image = cv::imread(chroma_img.toStdString(), CV_LOAD_IMAGE_COLOR);
// image = cv::imread("/home/giach/Data/Repos/scan4reco/playground/rtitool2/CROPPEDRoughCorrSing/cropped0.tif", CV_LOAD_IMAGE_COLOR);
for (int y = H-1; y >=0; y--)
for (int x = 0;x<W; x++)
for (int i = 0; i < 6; i++)
{
c=scaledc[x+y*W+W*H*i] ;//scaledc[i].at<unsigned char>(x,y);
outfile.write(( char *)&c,1);
}
for (int y = H-1; y >=0; y--)
for (int x = 0;x<W; x++){
Vec3b val=image.at<Vec3b>(y,x);
for (int i = 0; i < 3; i++)
outfile.write(( char *)&val[i],1);
}
delete(scaledc);
outfile.close();
}
string type2str(int type) {
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;
}
cv::Mat processImageGrabCut(cv::Mat image ){
cv::Mat bimage;
//cv::Mat mask = imread("mask.png");
// cv::threshold(mask, mask, 100, 150, cv::THRESH_BINARY_INV);
//mask.convertTo(mask,CV_8UC1);
image.convertTo(bimage, CV_8UC3);
// define bounding rectangle
//cv::Rect rectangle(40,90,bimage.cols-80,bimage.rows-170);
cv::Rect rectangle(10,10,bimage.cols-10,bimage.rows-10);
cv::Mat result; // segmentation result (4 possible values)
cv::Mat bgModel,fgModel; // the models (internally used)
//contours = mask.clone();
//GrabCut segmentation
cv::grabCut(bimage, // input image
result, // segmentation result
rectangle,// rectangle containing foreground
bgModel,fgModel, // models
1, // number of iterations
cv::GC_INIT_WITH_RECT); // use rectangle
//cv::Mat cimage = Mat::zeros(image.size(), CV_8UC3);
//cv::grabCut(contours,mask, rectangle, bgModel, fgModel,1,cv::GC_INIT_WITH_RECT);
cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ);
// Generate output image
cv::Mat foreground(bimage.size(),CV_8UC3,cv::Scalar(255,255,255));
cv::Mat background(bimage.size(),CV_8UC3,cv::Scalar(255,255,255));
bimage.copyTo(foreground,result);
return foreground;
}
cv::RotatedRect segmentAndFitEllipse(cv::Mat& image){
cv::Mat cloneim=image.clone();
cv::Mat gray, segmentedOtsu;
cv::cvtColor(cloneim,gray, cv::COLOR_BGR2GRAY);
cv::threshold(gray, segmentedOtsu, 100, 150,cv::THRESH_OTSU);
cv::threshold(segmentedOtsu, segmentedOtsu, 0, 255,cv::THRESH_BINARY_INV);
imshow("segmentedOtsu",segmentedOtsu);
waitKey();
cv::Mat sel = cv::getStructuringElement(cv::MorphShapes (MORPH_ELLIPSE),cv::Size(30,30));
cv::morphologyEx(segmentedOtsu, segmentedOtsu, cv::MorphShapes (MORPH_CLOSE),sel);
cv::imwrite("mask.png",segmentedOtsu);
vector<vector<Point> > contours;
findContours(segmentedOtsu, contours, RETR_LIST, CHAIN_APPROX_NONE);
cv::RotatedRect box;
cv::Mat cimage = Mat::zeros(segmentedOtsu.size(), CV_8UC3);
for(std::size_t i = 0; i < contours.size(); i++){
size_t count = contours[i].size();
cout<<"\nCount "<<count<<endl;
cv::Mat pointsf;
Mat(contours[i]).convertTo(pointsf, CV_32F);
box = cv::fitEllipse(pointsf);
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
continue;
cv::drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);
cv::ellipse(cimage, box, Scalar(0,0,255), 1, LINE_AA);
cv::ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, LINE_AA);
cout<<"\nEllipse features-Center: "<<box.center<<" Angle "<<box.angle<<" Width "<<box.size.width<<" Height "<<box.size.height<<endl;
Point2f vtx[4];
box.points(vtx);
for( int j = 0; j < 4; j++ )
line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, LINE_AA);
}
imshow("Fit Ellipse", cimage);
waitKey();
return box;
}
cv::RotatedRect segmentAndFitEllipseMax(cv::Mat& image){
cv::Mat cloneim=image.clone();
cv::Mat gray, segmentedOtsu, segmentedGC;
cv::cvtColor(cloneim,gray, cv::COLOR_BGR2GRAY);
cv::Mat fgd, bgd;
cv::threshold(gray, segmentedOtsu, 0, 255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
// segmentedGC = segmentedOtsu*cv::GC_PR_BGD;
// imshow("segmentedOtsu",gray);
// waitKey();
/* cv::Rect rectangle(50,50,image.cols-100,image.rows-100);
cv::grabCut(cloneim, // input image
segmentedGC, // segmentation result
rectangle,// rectangle containing foreground
bgd,fgd, // models
1, // number of iterations
cv::GC_INIT_WITH_RECT); // use mask
// cv::threshold(segmentedOtsu, segmentedOtsu, 0, 255,cv::THRESH_BINARY_INV);
cv::compare(segmentedGC,cv::GC_PR_FGD,segmentedGC,cv::CMP_EQ);
cv::Mat foreground(cloneim.size(),CV_8UC3,cv::Scalar(255,255,255));
cloneim.copyTo(foreground,segmentedGC); // bg pixels not copied
*/
//imshow("segmentedGC",foreground);
//waitKey();
/* cv::Mat sel = cv::getStructuringElement(cv::MorphShapes (MORPH_ELLIPSE),cv::Size(20,20));
cv::morphologyEx(segmentedOtsu, segmentedOtsu, cv::MorphShapes (MORPH_OPEN),sel);
sel = cv::getStructuringElement(cv::MorphShapes (MORPH_ELLIPSE),cv::Size(40,40));
cv::morphologyEx(segmentedOtsu, segmentedOtsu, cv::MorphShapes (MORPH_CLOSE),sel);*/
// cv::imwrite("mask.png",segmentedOtsu);
// imshow("segmentedOtsu",segmentedOtsu);
// waitKey();
vector<vector<Point> > contours;
findContours(segmentedOtsu, contours, RETR_LIST, CHAIN_APPROX_NONE);
//cout<<"\nContours Size"<<contours.size()<<endl;
std::vector<unsigned int> contoursDim(contours.size());
for(size_t i = 0; i < contours.size(); i++){
unsigned int count = contours[i].size();
contoursDim[i] = count;
// cout<<"\nContours Dim"<<contoursDim[i]<<endl;
}
Mat cimage = Mat::zeros(segmentedOtsu.size(), CV_8UC3);
RotatedRect box;
std::vector<unsigned int>::iterator result = std::max_element(contoursDim.begin(), contoursDim.end());
unsigned int maxIndex = std::distance(contoursDim.begin(),result);
//cout<<"\nIndex of maximum contour: "<<maxIndex<<endl;
Mat pointsf;
Mat(contours[maxIndex]).convertTo(pointsf, CV_32F);
box = cv::fitEllipse(pointsf);
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 ){
qDebug() <<"\nFitting went wrong!";
}
else
{
cv::drawContours(cimage, contours, (int)maxIndex, Scalar::all(255), 1, 8);
cv::ellipse(cimage, box, Scalar(0,0,255), 1, LINE_AA);
cv::ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, LINE_AA);
qDebug() <<"\nEllipse features-Center: "<<box.center.x <<" Angle "<<box.angle<<" Width "<<box.size.width<<" Height "<<box.size.height<<endl;
Point2f vtx[4];
box.points(vtx);
for( int j = 0; j < 4; j++ )
line(cimage, vtx[j], vtx[(j+1)%4], Scalar(0,255,0), 1, LINE_AA);
}
// imshow("Fit Max Ellipse", cimage);
// waitKey();
return box;
}
cv::Point2f getHighlightPosition(cv::Mat& image, cv::RotatedRect& boxEllipse){
Point2f highlightCoordinates = Point2f(0,0);
Mat gray;
cv::cvtColor(image,gray, cv::COLOR_BGR2GRAY);
Mat mask = Mat::zeros(image.size(), CV_8UC1);
cv::ellipse(mask, boxEllipse, 255, -1, LINE_AA);
Mat area;
gray.copyTo(area,mask);
Point centroide;
Mat dst, copia;
Scalar color(255,39,0);
Scalar color2(0,0,255);
vector< vector<Point> > contorni;
double la= 0.0;
int li= -1;
/* Method: starting from 255 (gray level and 8 bit image) and decreasing we threshold at this value the image and get the regions extracted
* stopping when a bright region is found inside the circle. If more regions are found at the threshold, the largest is preferred to locate the highlight
* the highlight is finally placed estimating the elliptic approximation of the region and taking the center.
*
* The light direction is computed then assuming ortographic view like done in the literature
*
* However, to change it we must do differently. This is not obvious as we don't have the information in the cropped region. We need to know the real pixels
* coordinates. The best solution may be to return the highlight position in the ellipse then process outside
*
* */
// loop over gray level
// for (int valore = 255; (la>0 == 0) && valore>5; valore=valore-1){
for (int valore = 255; (contorni.size() == 0) && valore>5; valore=valore-3){
threshold( area , dst, valore, 255,0);
findContours(dst, contorni, RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, Point(0,0));
la = 0; li= -1;
for( int i = 0; i< contorni.size(); i++ ) { // if there is a region
// Find the area of contour
double a=contourArea(contorni[i],false);
qDebug() << "--" << contorni.size() << " " << valore << " " << i << " " << a;
if (a>la){
copia = Mat::zeros( dst.size(), CV_8U );
cv::drawContours(copia, contorni, i, 255, -1,8, noArray(), 0,Point(0,0));
Moments momento = moments(copia, true);
Point centroid_i;
centroid_i.x = momento.m10/momento.m00;
centroid_i.y = momento.m01/momento.m00;
la=a;
li=i;
centroide = centroid_i;
}
if(li==-1){
li=0;
la=0;
centroide.x = contorni[0][0].x;
centroide.y = contorni[0][0].y;
}
}
qDebug() << "val "<< valore << " " << centroide.x << " " << centroide.y;
}
if (li<0) {
std::cerr << "############ NO HIGHLIGHT!!!############" << std::endl;
abort();
} else {
drawContours(image, contorni, li, color, -1,8, noArray(), 0,Point(0,0));
circle(image ,centroide, 1, color2, -1, 8,0);
/* imshow("region",image);
waitKey();
*/
}
return(centroide);
}
double* getLightDirection(cv::RotatedRect ellipse, cv::Point2d hlPos, cv::Mat CameraMatrix, double radiusSphere, QTextStream& stream){
////Method that estimates light direction based on the parameters of the ellipse, the coordinates of the light position,
////and the intrinsics of the camera. The rationale behind is https://www.overleaf.com/5539544ykcdsw#/17814043/.
//write sphre position
double ox, oy, alphax, alphay,sx, sy,f;
alphax = CameraMatrix.at<double>(0,0); //11513.914929;
alphay = CameraMatrix.at<double>(1,1);//11521.026366;
f = alphax;//focal length in centimeters
ox = CameraMatrix.at<double>(0,2);//3768.398316;
oy = CameraMatrix.at<double>(1,2);//2257.433392;
sx = 1;
sy = alphay/alphax;
double vecx = sx*(ellipse.center.x-ox);
double vecy = sy*(ellipse.center.y-oy);
double nor = sqrt(vecx*vecx+vecy*vecy);
double dx=vecx/nor;
double dy=vecy/nor;
double majorAxis = ellipse.size.height;
double minorAxis = ellipse.size.width;
double px,py,qx,qy;
////the extreme of the major axis computed with the ellipse equation.
px = ellipse.center.x - majorAxis*0.5f*dx;
py = ellipse.center.y - majorAxis*0.5f*dy;
qx = ellipse.center.x + majorAxis*0.5f*dx;
qy = ellipse.center.y + majorAxis*0.5f*dy;
cv::Point3d p((px-ox)*sx, (py-oy)*sy,f);
cv::Point3d q((qx-ox)*sx, (qy-oy)*sy,f);
cv::Point3d centerProjection(ox,oy,0);
cv::Point3d o(ox,oy,f);
cv::Point3d a,b,w,v;
a = (p)/norm(p);
b = (q)/norm(p);
w = (a+b)/norm(a+b);
//radius of the sphere in cm
//radius of the sphere in pixels;
//float radiusSphere = 151.181102;
////compute angles of triangle OCP;
float angleOCP, anglePOC, OP, cameraDistance;
anglePOC = acos((a.x*w.x +a.y*w.y +a.z*w.z));
angleOCP = asin((a.x*w.x +a.y*w.y +a.z*w.z));
OP = tan(angleOCP)*radiusSphere;
cameraDistance = sqrt(pow(OP,2)+pow(radiusSphere,2));
qDebug() <<M_PI<<"Test: "<<OP<<" camera distance "<<cameraDistance<<"\t AnglePOC\t"<<anglePOC*180/M_PI<<"\tAngleOCP\t"<<angleOCP*180/M_PI;
//compute the coordinates of the sphere's center in camera coordinates.
cv::Point3d centerSphere = w*cameraDistance;
stream<<centerSphere.x<<" "<< centerSphere.y<<" " <<centerSphere.z<<"\n";
//highlight coordinates in camera coordinates.
cv::Point3d imageHighlight((hlPos.x -ox)*sx, (hlPos.y-oy)*sy,f);
//view direction vector
cv::Point3d viewDirection = (imageHighlight)/norm(imageHighlight);
//solve quadratic sphere equation
double sol1,sol2, discriminant, coefa, coefb, coefc;
cv::Point3d sphereHighlight,sphereHighlight1, sphereHighlight2;
coefa = viewDirection.x*viewDirection.x+viewDirection.y*viewDirection.y+viewDirection.z*viewDirection.z;
coefb = -2*(viewDirection.x*centerSphere.x + viewDirection.y*centerSphere.y+viewDirection.z*centerSphere.z);
coefc = centerSphere.x*centerSphere.x +centerSphere.y*centerSphere.y +centerSphere.z*centerSphere.z-radiusSphere*radiusSphere;
discriminant = coefb*coefb -4*coefa*coefc;
sol1 = (-coefb + sqrt(discriminant))/(2*coefa);
sol2 = (-coefb - sqrt(discriminant))/(2*coefa);
//choose the solution closest to the origin.
sphereHighlight1 = sol1*viewDirection;
sphereHighlight2 = sol2*viewDirection;
if(abs(sphereHighlight1.z) < abs(sphereHighlight2.z))
sphereHighlight = sphereHighlight1;
else
sphereHighlight = sphereHighlight2;
//normal vector
cv::Point3d normal = (sphereHighlight-centerSphere)/norm(sphereHighlight-centerSphere);
//estimate light direction
sphereHighlight = sphereHighlight/norm(sphereHighlight);
double dotProductNormalHiglight = sphereHighlight.x*normal.x + sphereHighlight.y*normal.y + sphereHighlight.z*normal.z;
qDebug() <<"Solution"<<dotProductNormalHiglight<<"\n";
cv::Point3d lightDirection = sphereHighlight - 2*dotProductNormalHiglight*normal;
lightDirection = lightDirection/norm(lightDirection);
qDebug() <<"\nLight direction vector:\t"<<lightDirection.x<<"\t"<<lightDirection.y<<"\t"<<lightDirection.z;
double dotProductNormalIncident = lightDirection.x*normal.x + lightDirection.y*normal.y + lightDirection.z*normal.z;
double ang = acos(dotProductNormalIncident);
qDebug() <<"\nHighlight angle\t"<<ang<<"\t"<<ang*180/M_PI;
double* ld=new double[3];
ld[0]=lightDirection.x;
ld[1]=-lightDirection.y;
ld[2]=-lightDirection.z;
return ld;
}
/**
* La funzione viene usata per permettere all'utente di modificare posizione del centro e raggio del cerchio trovato
* con la funzione detectSphere.
*/
void resizeArea(int event, int x, int y, int flags, void* userdata){
Mat* image = static_cast< Mat* > (userdata);
Mat img = (*image).clone();
Mat imgmod = img.clone();
img.copyTo(imgmod);
Scalar color(155,239,98);
bool selezioneL, selezioneR;
int posizione;
Point centro;
double raggio;
if ( event == CV_EVENT_LBUTTONDOWN){
selezioneL = true;
}
if ( event == CV_EVENT_RBUTTONDOWN){
posizione = x;
selezioneR = true;
}
if ( event == CV_EVENT_LBUTTONUP){
selezioneL = false;
}
if ( event == CV_EVENT_RBUTTONUP){
selezioneR = false;
}
if ( event == CV_EVENT_MOUSEMOVE && selezioneL){
centro.x = x;
centro.y = y;
circle(imgmod, centro, raggio, color, 1, 8, 0);
circle(imgmod, centro, 1, color, CV_FILLED, 8,0);
imshow("ROI", imgmod);
}
if ( event == CV_EVENT_MOUSEMOVE && selezioneR){
if(x >= posizione)
raggio++;
else
raggio--;
posizione = x;
if(raggio >= 3)
circle(imgmod, centro, raggio, color, 1, 8, 0);
circle(imgmod, centro, 1, color, CV_FILLED, 8,0);
imshow("ROI", imgmod);
}
}
// This function takes the cropped ROI of the full-size image (OpenCV) and fit a circle over edges
// using the standard opencv hough function. It is not optimal and actually I wanted to do differently
// in any case now we will change
void fitCircle(Mat image, float* cx, float* cy, float* r){
float dx[16], dy[16];
for(int k=0;k<16;k++)
{
dx[k]=sin(k*M_PI/8);
dy[k]=cos(k*M_PI/8);
}
int diffmax = 0;
float raggio = *r;
Point centro(*cx,*cy);
float val = image.at<uchar>(centro);
// int center_intensity = Center_intensity.val[0]; // Il primo valore è quello che a noi interessa
float save_x=centro.x;
float save_y=centro.y;
float save_r= raggio;
int nv[16];
float funct, maxf=0;
vector<Vec3f> circles;
qDebug() << "inte " << val;
Mat contours;
//Canny(image,contours,50,200);
// cv::namedWindow("Canny");
// cv::imshow("Canny",contours);
//cv::waitKey(0);
//GaussianBlur( image, image, Size(3, 3), 2, 2 );
HoughCircles( image, circles, CV_HOUGH_GRADIENT, 1, 10, 60, 20, *r/2, *r+2);
for( size_t i = 0; i < circles.size(); i++ )
{
qDebug() << circles[i][2];
}
if(circles.size()>0){
qDebug() << "Fit OK";
*cx= (circles[0][0]);
*cy= (circles[0][1]);
*r= (circles[0][2]);
}
// display for debug
//namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
// imshow( "Hough Circle Transform Demo", image );
//waitKey(0);
// old trials to do a different circle detection
/* for(float x=centro.x-10; x<centro.x+10; x++)
for(float y=centro.y-10; y<centro.y+10; y++)
for(float ro=raggio-10; ro< raggio+1; ro++){
int nu=0;
float val=0;
for(int k=0;k<16;k++){
if(x+dx[k]*(ro+1) >= 0 && x+dx[k]*(ro+1) < image.size().width)
if(y+dy[k]*(ro+1) >= 0 && y+dy[k]*(ro+1) < image.size().height){
val = val+ (ro-20)*max(10,image.at<uchar>(x+dx[k]*(float)(ro+1),y+dy[k]*(float)(ro+1))-image.at<uchar>(x+dx[k]*(float)(ro-1),y+dy[k]*(float)(ro-1)));
nu++;
}
}
if(val > maxf) {
maxf =val;
save_x=x;
save_y=y;
save_r=ro;
qDebug() << "inte " << maxf << " " << save_x << " " << save_y << " " << save_r;
}
}
//float raggio = sqrt( double(pow(double((centro.x- radius.x)),2.0) + pow(double((centro.y - radius.y)),2.0))); // Calcolo il raggio tramite il Teorema di Pitagora
*cx=save_x;
*cy=save_y;
*r=save_r;
*/
// circle(image,Point(*cx,*cy),*r,Scalar(255,255,255),1,8,0);
// namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
// imshow( "Hough Circle Transform Demo", image );
}
/**
* This function is used both to estimate the highlight position and to estimate the light direction from the highlight and the sphere
*
*/
double* Highlight(Mat region, int cx, int cy, int raggio){
//qDebug() << "Hightlight...";
Point centroide;
Mat area, dst;
Scalar color(255,39,0);
Scalar color2(0,0,255);
vector< vector<Point> > contorni;
double Sx, Sy, phiL, tetaL, vectorX, vectorY, vectorZ;
cvtColor( region, area, CV_RGB2GRAY );
Mat copia;
double la= 0.0;
int li= -1;
/* Method: starting from 255 (gray level and 8 bit image) and decreasing we threshold at this value the image and get the regions extracted
* stopping when a bright region is found inside the circle. If more regions are found at the threshold, the largest is preferred to locate the highlight
* the highlight is finally placed estimating the elliptic approximation of the region and taking the center.
*
* The light direction is computed then assuming ortographic view like done in the literature
*
* However, to change it we must do differently. This is not obvious as we don't have the information in the cropped region. We need to know the real pixels
* coordinates. The best solution may be to return the highlight position in the ellipse then process outside
*
* */
// loop over gray level
qDebug() << "h search";
for (int valore = 255; (contorni.size() == 0) && valore>5; valore=valore-5){
threshold( area , dst, valore, 255,0);
findContours(dst, contorni, RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, Point(0,0));
la = 0.0; li= -1;
for( int i = 0; i< contorni.size(); i++ ) { // if there is a region
// Find the area of contour
double a=contourArea(contorni[i],false);
qDebug() << "reg found" << a;
if (a>la){
copia = Mat::zeros( dst.size(), CV_8U );
cv::drawContours(copia, contorni, i, 255, -1,8, noArray(), 0,Point(0,0));
Moments momento = moments(copia, true);
Point centroid_i;
centroid_i.x = momento.m10/momento.m00;
centroid_i.y = momento.m01/momento.m00;
centroid_i.x = cx -raggio + centroid_i.x;
centroid_i.y = cy -raggio + centroid_i.y;
double Sx_i = double((centroid_i.x - cx)) / raggio;
double Sy_i = -1.0 * double((centroid_i.y - cy)) / raggio;
if (1.0 - pow(Sx_i,2.0) - pow(Sy_i,2.0) > 0.0) {
// Good candidate
la=a;
li=i;
centroide = centroid_i;
Sx = Sx_i;
Sy = Sy_i;
}
}
if(li==-1){
li=0;
la=0;
centroide.x = cx -raggio + contorni[0][0].x;
centroide.y = cy -raggio + contorni[0][0].y;
Sx = double((centroide.x - cx)) / raggio;
Sy = -1.0 * double((centroide.y - cy)) / raggio;
}
} // Look for centroid at current level
if (li>=0) {
// Found!
} else {
// Continue at next gray level
contorni.clear();
}
}
if (li<0) {
std::cerr << "############ NO HIGHLIGHT!!!############" << std::endl;
vectorX=0.0; vectorY=0.0; vectorZ=1.0;
abort();
} else {
drawContours(region, contorni, li, color, -1,8, noArray(), 0,Point(0,0));
Point lc;
lc.x = centroide.x+raggio-cx;
lc.y = centroide.y+raggio-cy;
circle(region ,lc, 1, color2, -1, 8,0);
//imshow("region",region);
//waitKey();
// Compute light vector
phiL=0;
if(1.0 - pow(Sx,2.0) - pow(Sy,2.0)>0)
phiL = 2.0 *acos (double(sqrt(1.0 - pow(Sx,2.0) - pow(Sy,2.0))));
//tetaL = atan (double(cy - centroide.y)/ double((cx - centroide.x)));
tetaL = atan2 (double(cy - centroide.y),double((cx - centroide.x)));
vectorX = (centroide.x > cx ? abs(sin(phiL) * cos(tetaL)) : -1*abs(sin(phiL) * cos(tetaL)));
vectorY = (centroide.y < cy ? abs(sin(phiL) * sin(tetaL)) : -1*abs(sin(phiL) * sin(tetaL)));
vectorZ = abs(cos(phiL));
}
double* lightVector = new double(3);
double norm = sqrt(vectorX*vectorX+vectorY*vectorY+vectorZ*vectorZ);
lightVector[0] = vectorX/norm;
lightVector[1] = vectorY/norm;
lightVector[2] = vectorZ/norm;
//qDebug() << lightVector[0] << " " << lightVector[1] << " " << lightVector[2] << endl;
return(lightVector);
}
RTITool::RTITool(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::RTITool)
{
ui->setupUi(this);
iw=new ImageView(this);
ui->weightDir->setChecked(true);
ui->autoFit->setChecked(true);
ui->onMax->setChecked(true);
ui->projBox->setChecked(true);
ui->cx1spin->setVisible(false);
ui->cx2spin->setVisible(false);
ui->cx3spin->setVisible(false);
ui->cx4spin->setVisible(false);
ui->cy1spin->setVisible(false);
ui->cy2spin->setVisible(false);
ui->cy3spin->setVisible(false);
ui->cy4spin->setVisible(false);
ui->r1spin->setVisible(false);
ui->r2spin->setVisible(false);
ui->r3spin->setVisible(false);
ui->r4spin->setVisible(false);
ui->r2_1Spin->setVisible(false);
ui->r2_2Spin->setVisible(false);
ui->r2_3Spin->setVisible(false);
ui->r2_4Spin->setVisible(false);
ui->angle1spin->setVisible(false);
ui->angle2spin->setVisible(false);
ui->angle3spin->setVisible(false);
ui->angle4spin->setVisible(false);
ui->tabDir->setTabEnabled(2, false);
ui->tabDir->setTabEnabled(3, false);
ui->tabDir->setTabEnabled(4, false);
ui->tabDir->setTabEnabled(1, false);
ui->folderName->setReadOnly(true);
ui->zoomButton->setShortcut(tr("Ctrl+Z"));
ui->zoomButton2->setShortcut(QKeySequence::ZoomOut);
}
RTITool::~RTITool()
{
delete ui;
}
void RTITool::clearParams(){
for(int i=0;i<4;i++){
iw->ls[i]->setGeometry(0,0,0,0);
iw->ls[i]->setVisible(true);
iw->cx[i]=0;
iw->cy[i]=0;
iw->rx[i]=0;
iw->ry[i]=0;
iw->angle[i]=0;
iw->radius[i]=0;
iw->origins[i]=QPoint(0,0);
}
iw->sphere1->setGeometry(QRect(0,0,0,0));
ui->sph1->setText(QString("-"));
ui->cx1spin->setVisible(false);
ui->cy1spin->setVisible(false);
ui->r1spin->setVisible(false);
ui->r1spin->setVisible(false);
ui->r2_1Spin->setVisible(false);
ui->angle1spin->setVisible(false);
iw->sphere2->setGeometry(QRect(0,0,0,0));
ui->sph2->setText(QString("-"));
ui->cx2spin->setVisible(false);
ui->cy2spin->setVisible(false);
ui->r2spin->setVisible(false);
ui->r2spin->setVisible(false);
ui->r2_2Spin->setVisible(false);
ui->angle2spin->setVisible(false);
iw->sphere3->setGeometry(QRect(0,0,0,0));
ui->sph3->setText(QString("-"));
ui->cx3spin->setVisible(false);
ui->cy3spin->setVisible(false);
ui->r3spin->setVisible(false);
ui->r3spin->setVisible(false);
ui->r2_3Spin->setVisible(false);
ui->angle3spin->setVisible(false);
iw->sphere4->setGeometry(QRect(0,0,0,0));
ui->sph4->setText(QString("-"));
ui->cx4spin->setVisible(false);
ui->cy4spin->setVisible(false);
ui->r4spin->setVisible(false);
ui->r4spin->setVisible(false);
ui->r2_4Spin->setVisible(false);
ui->angle4spin->setVisible(false);
}
void RTITool::on_actionImage_list_triggered()
{
QString fileName;
fileName = QFileDialog::getOpenFileName(this,
tr("Open image list"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
qDebug(fileName.toLatin1());
QStringList nList;
QTextStream textStream(&file);
while (true)
{
QString line = textStream.readLine();
qDebug(line.toLatin1());
if (line.isNull())
break;
else
nList.append(line);
}
file.close();
ui->listWidget->clear();
ui->listWidget->addItems( nList );
QString filen = ui->folderName->text() + QDir::separator() + "images" + QDir::separator() + ui->listWidget->item(0)->text();
iw->load(filen);
//iw->load(ui->listWidget->item(0)->text());
iw->show();
for(int i=0;i<4;i++){
iw->ls[i]->setGeometry(0,0,0,0);
iw->ls[i]->setVisible(true);
iw->cx[i]=0;
iw->cy[i]=0;
iw->rx[i]=0;
iw->ry[i]=0;
iw->angle[i]=0;
iw->radius[i]=0;
iw->origins[i]=QPoint(0,0);
}
iw->sphere1->setGeometry(QRect(0,0,0,0));
ui->sph1->setText(QString("-"));
ui->cx1spin->setVisible(false);
ui->cy1spin->setVisible(false);
ui->r1spin->setVisible(false);
ui->r1spin->setVisible(false);
ui->r2_1Spin->setVisible(false);
ui->angle1spin->setVisible(false);
iw->sphere2->setGeometry(QRect(0,0,0,0));
ui->sph2->setText(QString("-"));
ui->cx2spin->setVisible(false);
ui->cy2spin->setVisible(false);
ui->r2spin->setVisible(false);
ui->r2spin->setVisible(false);
ui->r2_2Spin->setVisible(false);
ui->angle2spin->setVisible(false);
iw->sphere3->setGeometry(QRect(0,0,0,0));
ui->sph3->setText(QString("-"));
ui->cx3spin->setVisible(false);
ui->cy3spin->setVisible(false);
ui->r3spin->setVisible(false);
ui->r3spin->setVisible(false);
ui->r2_3Spin->setVisible(false);
ui->angle3spin->setVisible(false);
iw->sphere4->setGeometry(QRect(0,0,0,0));
ui->sph4->setText(QString("-"));
ui->cx4spin->setVisible(false);
ui->cy4spin->setVisible(false);
ui->r4spin->setVisible(false);
ui->r4spin->setVisible(false);
ui->r2_4Spin->setVisible(false);
ui->angle4spin->setVisible(false);
// qDebug(nList);