-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfusion2sphere.c
executable file
·1569 lines (1368 loc) · 45.4 KB
/
fusion2sphere.c
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 "fusion2sphere.h"
/*
Convert a dual fisheye to spherical map.
Initially based upon fish2sphere.
Documentation here: http://paulbourke.net/dome/dualfish2sphere/
Feb 2017: Added jpg support
Apr 2017: Updated general image file support
General cleanup of "old" testing code
May 2017: Added optimisation algorithm, looks at pixels across seam
while random searching parameter space.
Jun 2017: Experimental brightness correction across seam
Jun 2017: Added support for assymetric fisheye lenses
Oct 2017: Added overwriting of input file for sequences, -f
Mar 2018: Added mirror flipping of the image, arise from the Insta360 camera.
Cleaned up parameter handling
May 2020: Added transformations that are applied to final equirectangular
Feb 2022: Added batch support
Feb 2022: Add remap filters for ffmpeg, just the fish2sphere part. See documentation for blending
*/
FISHEYE fisheye[2]; // Input fisheye
PARAMS params; // General parameters
BITMAP4 *spherical = NULL; // Output image
// These are known frame templates
// The appropriate one to use will be auto detected, error is none match
#define NTEMPLATE 3
FRAMESPECS template[NTEMPLATE] = {{3104,3000,0,0,0,0},{2704,2624,0,0,0,0},{1568,1504,0,0,0,0}};
int whichtemplate = -1;
// Lookup table
typedef struct {
UV uv;
} LLTABLE;
LLTABLE *lltable = NULL;
int readJPGFast(FISHEYE *fJPG)
{
FILE *fimg;
if ((fimg = fopen(fJPG->fname,"rb")) == NULL) {
fprintf(stderr," Failed to open image file \"%s\"\n",fJPG->fname);
return(FALSE);
}
//JPEG_Info(fimg, &fJPG->width, &fJPG->height,&d);
if (JPEG_Read(fimg, fJPG->image,&fJPG->width,&fJPG->height) != 0) {
fprintf(stderr," Failed to correctly read image \"%s\"\n",fJPG->fname);
return(FALSE);
}
return(TRUE);
}
int readJPG(FISHEYE *fJPG)
{
FILE *fimg;
int w,h,d;
if ((fimg = fopen(fJPG->fname,"rb")) == NULL) {
fprintf(stderr," Failed to open image file \"%s\"\n",fJPG->fname);
return(FALSE);
}
JPEG_Info(fimg, &fJPG->width, &fJPG->height,&d);
fJPG->image = Create_Bitmap(fJPG->width, fJPG->height);
if (JPEG_Read(fimg, fJPG->image,&w,&h) != 0) {
fprintf(stderr," Failed to correctly read image \"%s\"\n",fJPG->fname);
return(FALSE);
}
return(TRUE);
}
int WriteOutputImageBatch(BITMAP4 *spherical, char *basename,char *s)
{
int i;
FILE *fptr;
char fname[256];
if (IsJPEG(s)) { // remove extension
for (i=strlen(s)-1;i>0;i--) {
if (s[i] == '.') {
s[i] = '\0';
break;
}
}
}
strcpy(fname,s);
// Add extension
strcat(fname,".jpg");
// Open file
if ((fptr = fopen(fname,"wb")) == NULL) {
fprintf(stderr,"Failed to open output file \"%s\"\n",fname);
return(FALSE);
}
JPEG_Write(fptr,spherical,params.outwidth,params.outheight,100);
fclose(fptr);
return(TRUE);
}
/*
Given a longitude and latitude calculate the rgb value from the fisheye
Return FALSE if the pixel is outside the fisheye image
*/
int FindFishPixelBatch(int n,double latitude,double longitude,UV *uv, int width, int height)
{
char ind[256];
int k,index;
XYZ p,q = {0,0,0};
double theta,phi,r;
int u,v;
UV fuv;
// Ignore pixels that will never be touched because out of blend range
if (n == 0) {
if (longitude > params.blendmid + params.blendwidth || longitude < -params.blendmid - params.blendwidth)
return(FALSE);
}
if (n == 1) {
if (longitude > -params.blendmid + params.blendwidth && longitude < params.blendmid - params.blendwidth)
return(FALSE);
}
// Turn by 180 degrees for the second fisheye
if (n == 1) {
longitude += M_PI;
//printf("\nturn 180 deg %lf\n", longitude);
}
// p is the ray from the camera position into the scene
p.x = cos(latitude) * sin(longitude);
p.y = cos(latitude) * cos(longitude);
p.z = sin(latitude);
// Apply fisheye correction transformation
for (k=0;k<fisheye[n].ntransform;k++) {
printf("Apply fisheye correction transformation");
switch(fisheye[n].transform[k].axis) {
case XTILT:
q.x = p.x;
q.y = p.y * fisheye[n].transform[k].cvalue + p.z * fisheye[n].transform[k].svalue;
q.z = -p.y * fisheye[n].transform[k].svalue + p.z * fisheye[n].transform[k].cvalue;
break;
case YROLL:
q.x = p.x * fisheye[n].transform[k].cvalue + p.z * fisheye[n].transform[k].svalue;
q.y = p.y;
q.z = -p.x * fisheye[n].transform[k].svalue + p.z * fisheye[n].transform[k].cvalue;
break;
case ZPAN:
q.x = p.x * fisheye[n].transform[k].cvalue + p.y * fisheye[n].transform[k].svalue;
q.y = -p.x * fisheye[n].transform[k].svalue + p.y * fisheye[n].transform[k].cvalue;
q.z = p.z;
break;
}
p = q;
}
// Calculate fisheye coordinates
theta = atan2(p.z,p.x);
phi = atan2(sqrt(p.x*p.x+p.z*p.z),p.y);
r = phi / fisheye[n].fov; // 0 ... 1
// Determine the u,v coordinate
u = fisheye[n].centerx + fisheye[n].radius * r * cos(theta);
//printf("u: %d, fisheye[n].width: %d", u, fisheye[n].width);
if (u < 0 || u >= width)
return(FALSE);
v = fisheye[n].centery + fisheye[n].radius * r * sin(theta);
if (v < 0 || v >= height)
return(FALSE);
index = v * width + u;
sprintf(ind,"%d%d",index, n);
fuv.index = atoi(ind);
*uv = fuv;
return(TRUE);
}
int startDirectoryExtraction(int argc, char **argv, char *front, char *back, char *out, int nstart, int nstop){
char fname1[256], fname2[256];
int width=0, height=0;
int i,j,aj,ai,n=0;
int index,nantialias[2];
int inblendzone = FALSE;
char basename[256];
BITMAP4 black = {0,0,0,255};
double latitude0,longitude0,latitude,longitude;
double blend = 1;
COLOUR rgbsum[2],rgbzero = {0,0,0};
int noptiterations = 1; // > 1 for optimisation
char fnameout[256],tablename[256];
FILE *fptr;
int ntable = 0;
int itable = 0;
int nframe, nt=0, nn = 0;
double dx,dy;
if(inblendzone != FALSE){
inblendzone = FALSE;
}
if ((strlen(front) > 2) && (strlen(back) > 2) && (strlen(out) > 2)) {
if (!CheckTemplate(front,1))
front[0] = '\0';
if (!CheckTemplate(back,1))
back[0] = '\0';
if (!CheckTemplate(out,1))
out[0] = '\0';
if( !((CheckTemplate(front,1) == TRUE) && (CheckTemplate(back,1) == TRUE) && (CheckTemplate(out,1) == TRUE))){
exit(-1);
}
}
else{
exit(-1);
}
// Check the first frame to determine template and frame sizes
sprintf(fname1,front,nstart);
sprintf(fname2,back,nstart);
if ((whichtemplate = CheckFrames(fname1,fname2,&width,&height)) < 0)
exit(-1);
if (params.debug) {
fprintf(stderr,"%s() - frame dimensions: %d x %d\n",argv[0],width,height);
fprintf(stderr,"%s() - Expect frame template %d\n",argv[0],whichtemplate+1);
}
fisheye[0].width = width;
fisheye[0].height = height;
fisheye[1].width = width;
fisheye[1].height = height;
// Memory for images
fisheye[0].image = Create_Bitmap(width,height);
fisheye[1].image = Create_Bitmap(width,height);
// Create output spherical (equirectangular) image
spherical = Create_Bitmap(params.outwidth,params.outheight);
// Read parameter file name
if (!ReadParameters(argv[argc-1])) {
fprintf(stderr,"Failed to read parameter file \"%s\"\n",argv[argc-1]);
exit(-1);
}
// Apply defaults and precompute values
FisheyeDefaults(&fisheye[0]);
FisheyeDefaults(&fisheye[1]);
FlipFisheye(fisheye[0]);
FlipFisheye(fisheye[1]);
// Create output spherical (equirectangular) image
spherical = Create_Bitmap(params.outwidth,params.outheight);
// Must have blending on for optimisation
if (noptiterations > 1 && params.blendwidth <= 0) {
fprintf(stderr,"Warning: Must enable blending for optimisation, setting to 6 degrees\n");
params.blendwidth = 3*DTOR;
}
if (params.debug)
DumpParameters();
ntable = params.outheight * params.outwidth * params.antialias * params.antialias * 2;
lltable = malloc(ntable*sizeof(LLTABLE));
sprintf(tablename,"f_%d_%d_%d_%d.data",whichtemplate,params.outwidth,params.outheight,params.antialias);
if ((fptr = fopen(tablename,"r")) != NULL) {
if (params.debug)
fprintf(stderr,"%s() - Reading lookup table\n",argv[0]);
if ((nt = fread(lltable,sizeof(LLTABLE),ntable,fptr)) != ntable) {
fprintf(stderr,"%s() - Failed to read lookup table \"%s\" (%d != %d)\n",argv[0],tablename,nt,ntable);
}
fclose(fptr);
}
dx = params.antialias * params.outwidth;
dy = params.antialias * params.outheight;
if (nt != ntable) {
itable = 0;
for (j=0;j<params.outheight;j++) {
latitude0 = PI * j / (double)params.outheight - PID2; // -pi/2 ... pi/2
for (i=0;i<params.outwidth;i++) {
longitude0 = TWOPI * i / (double)params.outwidth - PI; // -pi ... pi
for (ai=0;ai<params.antialias;ai++) {
longitude = longitude0 + ai * TWOPI / dx;
for (aj=0;aj<params.antialias;aj++) {
latitude = latitude0 + aj * M_PI / dy;
for (n=0;n<2;n++) {
if(FindFishPixelBatch(n,latitude,longitude,&(lltable[itable].uv), width, height)) {
itable++;
}
}
} // aj
} // ai
lltable[itable].uv.index = -1;
itable++;
} // i
} // j
fptr = fopen(tablename,"w");
fwrite(lltable,ntable,sizeof(LLTABLE),fptr);
fclose(fptr);
}
for (nframe=nstart;nframe<=nstop;nframe++) {
sprintf(fisheye[0].fname,front,nframe);
sprintf(fisheye[1].fname,back,nframe);
sprintf(fnameout,out,nframe);
if (IsJPEG(fisheye[0].fname)){
if(1 != readJPGFast(&fisheye[0])){
continue;
}
}
if (IsJPEG(fisheye[1].fname)){
if(1 != readJPGFast(&fisheye[1])){
continue;
}
}
itable = 0;
Erase_Bitmap(spherical,params.outwidth,params.outheight,black);
for (j=0;j<params.outheight;j++) {
latitude0 = PI * j / (double)params.outheight - PID2; // -pi/2 ... pi/2
for (i=0;i<params.outwidth;i++) {
longitude0 = TWOPI * i / (double)params.outwidth - PI; // -pi ... pi
// Blending masks, only depend on longitude
if (params.blendwidth > 0) {
blend = (params.blendmid + params.blendwidth - fabs(longitude0)) / (2*params.blendwidth); // 0 ... 1
if (blend < 0) blend = 0;
if (blend > 1) blend = 1;
if (params.blendpower > 1) {
blend = 2 * blend - 1; // -1 to 1
blend = 0.5 + 0.5 * SIGN(blend) * pow(fabs(blend),1.0/params.blendpower);
}
} else { // No blend
blend = 0;
if (ABS(longitude0) <= params.blendmid) // Hard edge
blend = 1;
}
// Are we in the blending zones
inblendzone = FALSE;
if (longitude0 <= params.blendmid + params.blendwidth && longitude0 >= params.blendmid - params.blendwidth)
inblendzone = TRUE;
if (longitude0 >= -params.blendmid - params.blendwidth && longitude0 <= -params.blendmid + params.blendwidth)
inblendzone = TRUE;
//printf("\n %lf, %lf, %lf\n", params.blendwidth, params.blendmid, params.blendpower);// 0.000000, 1.570796, 1.000000
// Initialise antialiasing accumulation variables
for (n=0;n<2;n++) {
rgbsum[n] = rgbzero;
nantialias[n] = 0;
}
for (n=0;n<100;n++) {
nn = 0;
index = lltable[itable].uv.index;
if(index == -1){
itable++;
break;
}
nn = index%10;
index = index/10;
//if(nn == 0){printf("\nnn: %d, index: %d, itable: %d\n", nn, index, itable);}
rgbsum[nn].r += fisheye[nn].image[index].r;
rgbsum[nn].g += fisheye[nn].image[index].g;
rgbsum[nn].b += fisheye[nn].image[index].b;
nantialias[nn]++;
itable++;
}
// Normalise by antialiasing samples
for (n=0;n<2;n++) {
if (nantialias[n] > 0) {
rgbsum[n].r /= nantialias[n];
rgbsum[n].g /= nantialias[n];
rgbsum[n].b /= nantialias[n];
}
}
index = j * params.outwidth + i;
spherical[index].r = blend * rgbsum[0].r + (1 - blend) * rgbsum[1].r;
spherical[index].g = blend * rgbsum[0].g + (1 - blend) * rgbsum[1].g;
spherical[index].b = blend * rgbsum[0].b + (1 - blend) * rgbsum[1].b;
//printf("%d ", index);
//printf("\nindex: %d, r: %d, g: %d, b: %d\n", index, spherical[index].r, spherical[index].g, spherical[index].b);
//if(itable > 100){
//break;
//}
} // i
//break;
} // j
// Write out the spherical map
if (!WriteOutputImageBatch(spherical, basename,fnameout)) {
fprintf(stderr,"Failed to write output image file\n");
exit(-1);
}
}
// Optionally create ffmpeg remap filter PGM files
if (params.makeremap)
MakeRemap();
Destroy_Bitmap(spherical);
Destroy_Bitmap(fisheye[0].image);
Destroy_Bitmap(fisheye[1].image);
return 0;
}
int main(int argc,char **argv)
{
int i,j,aj,ai,n=0, sdir=0, nstart=0, nstop=0,ix,iy;
int index,nantialias[2],inblendzone;
char basename[256],outfilename[256] = "\0";
BITMAP4 black = {0,0,0,255},red = {255,0,0,255};
double latitude0,longitude0,latitude,longitude;
double weight = 1,blend = 1;
COLOUR rgb,rgbsum[2],rgbzero = {0,0,0};
double starttime=0,stoptime=0;
int nopt,noptiterations = 1; // > 1 for optimisation
double fov[2];
int centerx[2],centery[2];
double r,theta,minerror=1e32,opterror=0,errorsum = 0;
int nsave = 0;
char fname[256], front[256], back[256];
int nfish = 0;
FILE *fptr;
// Initial values for fisheye structure and general parameters
InitParams();
InitFisheye(&fisheye[0]);
InitFisheye(&fisheye[1]);
// Usage, require at least a parameter file
if (argc < 2)
GiveUsage(argv[0]);
// Create basename
strcpy(basename,argv[argc-1]);
for (i=0;i<strlen(basename);i++)
if (basename[i] == '.')
basename[i] = '\0';
// Parse the command line arguments
for (i=1;i<argc;i++) {
if (strcmp(argv[i],"-w") == 0) {
i++;
params.outwidth = atoi(argv[i]);
params.outwidth /= 4;
params.outwidth *= 4; // Ensure multiple of 4
params.outheight = params.outwidth / 2; // Default for equirectangular images, will be even
} else if (strcmp(argv[i],"-a") == 0) {
i++;
if ((params.antialias = atoi(argv[i])) < 1)
params.antialias = 1;
} else if (strcmp(argv[i],"-b") == 0) {
i++;
if ((params.blendwidth = DTOR*atof(argv[i])) < 0)
params.blendwidth = 0;
params.blendwidth /= 2; // Now half blendwith
} else if (strcmp(argv[i],"-d") == 0) {
params.debug = TRUE;
} else if (strcmp(argv[i],"-q") == 0) {
i++;
params.blendpower = atof(argv[i]);
} else if (strcmp(argv[i],"-o") == 0) {
i++;
strcpy(outfilename,argv[i]);
} else if (strcmp(argv[i],"-f") == 0) {
i++;
strcpy(fisheye[0].fname,argv[i]);
if (IsJPEG(fisheye[0].fname)){
if(1 != readJPG(&fisheye[0])){
exit(-1);
}
nfish +=1;
}
i++;
strcpy(fisheye[1].fname,argv[i]);
if (IsJPEG(fisheye[1].fname)){
if(1 != readJPG(&fisheye[1])){
exit(-1);
}
nfish +=1;
}
if(nfish == 2){
params.fileformat = JPG;
}
else{
fprintf(stderr,"Expected two fisheye images, instead found %d\n",nfish);
exit(-1);
}
} else if (strcmp(argv[i],"-r") == 0) {
params.makeremap = TRUE;
} else if (strcmp(argv[i],"-e") == 0) {
i++;
noptiterations = atoi(argv[i]);
} else if (strcmp(argv[i],"-p") == 0) {
i++;
params.deltafov = DTOR*atof(argv[i]);
i++;
params.deltacenter = atoi(argv[i]);
i++;
params.deltatheta = DTOR*atof(argv[i]);
} else if (strcmp(argv[i],"-i") == 0) {
params.icorrection = TRUE;
} else if (strcmp(argv[i],"-m") == 0) {
i++;
params.blendmid = atof(argv[i]);
params.blendmid *= (DTOR*0.5);
}
else if (strcmp(argv[i],"-x") == 0) {
sdir = 1;
i++;
strcpy(front,argv[i]);
i++;
strcpy(back,argv[i]);
} else if (strcmp(argv[i],"-g") == 0) {
i++;
nstart = atoi(argv[i]);
} else if (strcmp(argv[i],"-h") == 0) {
i++;
nstop = atoi(argv[i]);
}
}
if(sdir == 1){
startDirectoryExtraction(argc, argv, front, back, outfilename, nstart, nstop);
exit(0);
}
// Read parameter file name
if (!ReadParameters(argv[argc-1])) {
fprintf(stderr,"Failed to read parameter file \"%s\"\n",argv[argc-1]);
exit(-1);
}
// Apply defaults and precompute values
FisheyeDefaults(&fisheye[0]);
FisheyeDefaults(&fisheye[1]);
FlipFisheye(fisheye[0]);
FlipFisheye(fisheye[1]);
// Create output spherical (equirectangular) image
spherical = Create_Bitmap(params.outwidth,params.outheight);
// Must have blending on for optimisation
if (noptiterations > 1 && params.blendwidth <= 0) {
fprintf(stderr,"Warning: Must enable blending for optimisation, setting to 6 degrees\n");
params.blendwidth = 3*DTOR;
}
// Remember the baseline values
for (j=0;j<2;j++) {
fov[j] = fisheye[j].fov;
centerx[j] = fisheye[j].centerx;
centery[j] = fisheye[j].centery;
}
if (params.debug)
DumpParameters();
// Optimisation loop, otherwise just do once if noptiterations=1
for (nopt=0;nopt<noptiterations;nopt++) {
// Only apply random perturbation after first iteration
if (noptiterations > 1) {
for (j=0;j<2;j++) {
fisheye[j].fov = fov[j] + (drand48() - 0.5) * params.deltafov; // Half
r = drand48() * params.deltacenter;
theta = drand48() * TWOPI;
fisheye[j].centerx = centerx[j] + r * cos(theta);
fisheye[j].centery = centery[j] + r * sin(theta);
}
MakeRandomRotations();
}
if (noptiterations > 1 && nopt % (noptiterations/100==0?1:noptiterations/100) == 0)
fprintf(stderr,"Optimisation step %8d of %8d\n",nopt,noptiterations);
opterror = 0;
errorsum = 0;
// Form the spherical map
starttime = GetTime();
Erase_Bitmap(spherical,params.outwidth,params.outheight,black);
for (j=0;j<params.outheight;j++) {
latitude0 = PI * j / (double)params.outheight - PID2; // -pi/2 ... pi/2
for (i=0;i<params.outwidth;i++) {
longitude0 = TWOPI * i / (double)params.outwidth - PI; // -pi ... pi
// Blending masks, only depend on longitude
if (params.blendwidth > 0) {
blend = (params.blendmid + params.blendwidth - fabs(longitude0)) / (2*params.blendwidth); // 0 ... 1
if (blend < 0) blend = 0;
if (blend > 1) blend = 1;
if (params.blendpower > 1) {
blend = 2 * blend - 1; // -1 to 1
blend = 0.5 + 0.5 * SIGN(blend) * pow(fabs(blend),1.0/params.blendpower);
}
} else { // No blend
blend = 0;
if (ABS(longitude0) <= params.blendmid) // Hard edge
blend = 1;
}
// Are we in the blending zones
inblendzone = FALSE;
if (longitude0 <= params.blendmid + params.blendwidth && longitude0 >= params.blendmid - params.blendwidth)
inblendzone = TRUE;
if (longitude0 >= -params.blendmid - params.blendwidth && longitude0 <= -params.blendmid + params.blendwidth)
inblendzone = TRUE;
// If optimising then only need to calculate image within the blend zone
if (noptiterations > 1 && !inblendzone)
continue;
// Initialise antialiasing accumulation variables
for (n=0;n<2;n++) {
rgbsum[n] = rgbzero;
nantialias[n] = 0;
}
// Antialiasing, inner loops
// Find the corresponding pixel in the fisheye image
// Sum over the supersampling set
for (ai=0;ai<params.antialias;ai++) {
longitude = longitude0 + ai * TWOPI / (params.antialias*params.outwidth);
for (aj=0;aj<params.antialias;aj++) {
latitude = latitude0 + aj * M_PI / (params.antialias*params.outheight);
for (n=0;n<2;n++) {
if (FindFishPixel(n,latitude,longitude,&ix,&iy,&rgb)) {
rgbsum[n].r += rgb.r;
rgbsum[n].g += rgb.g;
rgbsum[n].b += rgb.b;
nantialias[n]++;
}
}
} // aj
} // ai
// Normalise by antialiasing samples
for (n=0;n<2;n++) {
if (nantialias[n] > 0) {
rgbsum[n].r /= nantialias[n];
rgbsum[n].g /= nantialias[n];
rgbsum[n].b /= nantialias[n];
}
}
// Update antialiased value to final image with blending
index = j * params.outwidth + i;
spherical[index].r = blend * rgbsum[0].r + (1 - blend) * rgbsum[1].r;
spherical[index].g = blend * rgbsum[0].g + (1 - blend) * rgbsum[1].g;
spherical[index].b = blend * rgbsum[0].b + (1 - blend) * rgbsum[1].b;
// Determine error metric if in optimisation mode
// Experimental, weight higher if closer to the center of blend
if (noptiterations > 1 && inblendzone) {
//weight = 1;
weight = 1 - 2 * fabs(0.5 - blend); // 0 to 1 in middle of blend to 0
if (j > 0.2*params.outheight && j < 0.8*params.outheight) {
opterror += CalcError(rgbsum[0],rgbsum[1],weight);
errorsum += weight;
}
}
} // i
} // j
stoptime = GetTime();
// Write a parameter file, suitable for normal fusion2sphere usage
opterror /= errorsum; // Normalise to "per pixel"
if (noptiterations > 1 && opterror < minerror) {
sprintf(fname,"%s_%02d.txt",basename,nsave);
fptr = fopen(fname,"w");
fprintf(fptr,"# Optimisation step %d of %d\n",nopt,noptiterations);
fprintf(fptr,"# Error: %g\n",opterror);
fprintf(fptr,"# delta fov: %g degrees\n",RTOD*params.deltafov);
fprintf(fptr,"# delta center: %d pixels\n",params.deltacenter);
fprintf(fptr,"# delta theta: %g degrees\n",RTOD*params.deltatheta);
fprintf(fptr,"# blend width: %g degrees\n",RTOD*2*params.blendwidth);
fprintf(fptr,"\n");
for (j=0;j<2;j++) {
fprintf(fptr,"# image %d\n",j);
fprintf(fptr,"IMAGE: %s\n",fisheye[j].fname);
fprintf(fptr,"RADIUS: %d\n",fisheye[j].radius);
fprintf(fptr,"CENTER: %d %d\n",fisheye[j].centerx,fisheye[j].height-1-fisheye[j].centery);
fprintf(fptr,"# Was: %d %d\n",centerx[j],fisheye[j].height-1-centery[j]);
fprintf(fptr,"FOV: %.1lf\n",fisheye[j].fov*2*RTOD);
fprintf(fptr,"# Was: %.1lf\n",fov[j]*2*RTOD);
if (fisheye[j].hflip < 0)
fprintf(fptr,"HFLIP: -1\n");
if (fisheye[j].vflip < 0)
fprintf(fptr,"VFLIP: -1\n");
for (i=0;i<fisheye[j].ntransform;i++) {
switch (fisheye[j].transform[i].axis) {
case XTILT:
fprintf(fptr,"ROTATEX: %.1lf\n",fisheye[j].transform[i].value*RTOD);
break;
case YROLL:
fprintf(fptr,"ROTATEY: %.1lf\n",fisheye[j].transform[i].value*RTOD);
break;
case ZPAN:
fprintf(fptr,"ROTATEZ: %.1lf\n",fisheye[j].transform[i].value*RTOD);
break;
}
}
}
fclose(fptr);
// Write image so far, will just be the blend strip
sprintf(fname,"%s_%02d",basename,nsave);
WriteOutputImage(basename,fname);
fprintf(stderr,"Optimisation step %8d of %8d Error: %5.1lf ",nopt,noptiterations,opterror);
fprintf(stderr,"Saved to %s_%02d\n",basename,nsave);
nsave++;
minerror = opterror; // Remember best so far
}
} // nopt
// Timing and optionally show the blend range
if (params.debug) {
fprintf(stderr,"Time for sampling: %g\n",stoptime-starttime);
for (j=0;j<params.outheight;j++) {
i = params.outwidth / 4.0;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
i = 3 * params.outwidth / 4.0;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
if (params.blendwidth > 0) {
i = params.outwidth / 4.0 + params.outwidth * params.blendwidth / TWOPI;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
i = params.outwidth / 4.0 - params.outwidth * params.blendwidth / TWOPI;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
i = 3 * params.outwidth / 4.0 + params.outwidth * params.blendwidth / TWOPI;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
i = 3 * params.outwidth / 4.0 - params.outwidth * params.blendwidth / TWOPI;
Draw_Pixel(spherical,params.outwidth,params.outheight,i,j,red);
}
}
}
// Optionally create ffmpeg remap filter PGM files
if (params.makeremap)
MakeRemap();
// Write out the spherical map
if (!WriteOutputImage(basename,outfilename)) {
fprintf(stderr,"Failed to write output image file\n");
exit(-1);
}
exit(0);
}
void GiveUsage(char *s)
{
fprintf(stderr,"Usage: %s [options] parameterfile\n",s);
fprintf(stderr,"Options\n");
fprintf(stderr," -w n sets the output image size, default: %d\n",params.outwidth);
fprintf(stderr," -a n sets antialiasing level, default: %d\n",params.antialias);
fprintf(stderr," -b n longitude width for blending, default: %g\n",2*params.blendwidth);
fprintf(stderr," -q n blend power, default: %g\n",params.blendpower);
fprintf(stderr," -e n optimise over n random steps, default: off\n");
fprintf(stderr," -p n n n range search fov, center and rotations, default: %g %d %g\n",
params.deltafov*RTOD,params.deltacenter,params.deltatheta*RTOD);
fprintf(stderr," -i enable intensity edge roll-off correction, default: off\n");
fprintf(stderr," -f s1 s2 input filename, overwrite file specified in parameter file\n");
fprintf(stderr," -o s output file name, default: derived from input name\n");
fprintf(stderr," -m n specify blend mid angle, default: %g\n",RTOD*2*params.blendmid);
fprintf(stderr," -d debug mode, default: off\n");
fprintf(stderr," -r create remap filters for ffmpeg, default: off\n");
exit(-1);
}
/*
Set default values for fisheye structure
*/
void InitFisheye(FISHEYE *f)
{
f->fname[0] = '\0';
f->image = NULL;
f->width = 0;
f->height = 0;
f->centerx = -1;
f->centery = -1;
f->radius = -1;
f->fov = 180;
f->hflip = 1;
f->vflip = 1;
f->transform = NULL;
f->ntransform = 0;
}
/*
Fill in remaining fisheye values
*/
void FisheyeDefaults(FISHEYE *f)
{
int j;
// fov will only be used as half value, and radians
f->fov /= 2;
f->fov *= DTOR;
// Set center to image center, if not set in parameter file
if (f->centerx < 0 || f->centery < 0) {
f->centerx = f->width / 2;
f->centery = f->height / 2;
}
// Origin bottom left
f->centery = f->height - 1 - f->centery;
// Set fisheye radius to half height, if not set in parameter file
if (f->radius < 0)
f->radius = f->height / 2;
// Precompute sine and cosine of transformation angles
for (j=0;j<f->ntransform;j++) {
f->transform[j].cvalue = cos(f->transform[j].value);
f->transform[j].svalue = sin(f->transform[j].value);
}
}
/*
Given a longitude and latitude calculate the rgb value from the fisheye
Return FALSE if the pixel is outside the fisheye image
*/
int FindFishPixel(int n,double latitude,double longitude,int *u,int *v,COLOUR *rgb)
{
int k,index;
COLOUR c = {0,0,0};
XYZ p,q = {0,0,0};
double theta,phi,r;
*u = -1;
*v = -1;
*rgb = c;
// Ignore pixels that will never be touched because out of blend range
if (n == 0) {
if (longitude > params.blendmid + params.blendwidth || longitude < -params.blendmid - params.blendwidth)
return(FALSE);
}
if (n == 1) {
if (longitude > -params.blendmid + params.blendwidth && longitude < params.blendmid - params.blendwidth)
return(FALSE);
}
// Turn by 180 degrees for the second fisheye
if (n == 1) {
longitude += M_PI;
}
// p is the ray from the camera position into the scene
p.x = cos(latitude) * sin(longitude);
p.y = cos(latitude) * cos(longitude);
p.z = sin(latitude);
// Apply fisheye correction transformation
for (k=0;k<fisheye[n].ntransform;k++) {
switch(fisheye[n].transform[k].axis) {
case XTILT:
q.x = p.x;
q.y = p.y * fisheye[n].transform[k].cvalue + p.z * fisheye[n].transform[k].svalue;
q.z = -p.y * fisheye[n].transform[k].svalue + p.z * fisheye[n].transform[k].cvalue;
break;
case YROLL:
q.x = p.x * fisheye[n].transform[k].cvalue + p.z * fisheye[n].transform[k].svalue;
q.y = p.y;
q.z = -p.x * fisheye[n].transform[k].svalue + p.z * fisheye[n].transform[k].cvalue;
break;
case ZPAN:
q.x = p.x * fisheye[n].transform[k].cvalue + p.y * fisheye[n].transform[k].svalue;
q.y = -p.x * fisheye[n].transform[k].svalue + p.y * fisheye[n].transform[k].cvalue;
q.z = p.z;
break;
}
p = q;
}
// Calculate fisheye coordinates
theta = atan2(p.z,p.x);
phi = atan2(sqrt(p.x*p.x+p.z*p.z),p.y);
r = phi / fisheye[n].fov; // 0 ... 1
// Determine the u,v coordinate
*u = fisheye[n].centerx + fisheye[n].radius * r * cos(theta);
if (*u < 0 || *u >= fisheye[n].width)
return(FALSE);
*v = fisheye[n].centery + fisheye[n].radius * r * sin(theta);
if (*v < 0 || *v >= fisheye[n].height)
return(FALSE);
// Extract rgb colour
index = (*v) * fisheye[n].width + (*u);
rgb->r = fisheye[n].image[index].r;
rgb->g = fisheye[n].image[index].g;
rgb->b = fisheye[n].image[index].b;
return(TRUE);
}
/*
This s highly system/OS dependent
Will need replacing for Windows.
*/
double GetTime(void)
{
double sec = 0;
struct timeval tp;
gettimeofday(&tp,NULL);
sec = tp.tv_sec + tp.tv_usec / 1000000.0;
return(sec);
}
/*
Purely for debugging
*/
void DumpParameters(void)
{
int i,j;
for (i=0;i<2;i++) {
fprintf(stderr,"FISHEYE: %d\n",i);
fprintf(stderr," IMAGE: %s (%dx%d)\n",fisheye[i].fname,fisheye[i].width,fisheye[i].height);
fprintf(stderr," CENTER: %d,%d\n",fisheye[i].centerx,fisheye[i].height-1-fisheye[i].centery);
fprintf(stderr," RADIUS: %d\n",fisheye[i].radius);
fprintf(stderr," FOV: %g\n",fisheye[i].fov*2*RTOD);
fprintf(stderr," HFLIP: %d\n",fisheye[i].hflip);
fprintf(stderr," VFLIP: %d\n",fisheye[i].vflip);
for (j=0;j<fisheye[i].ntransform;j++) {
if (fisheye[i].transform[j].axis == XTILT)
fprintf(stderr," ROTATEX: ");
else if (fisheye[i].transform[j].axis == YROLL)
fprintf(stderr," ROTATEY: ");
else if (fisheye[i].transform[j].axis == ZPAN)
fprintf(stderr," ROTATEZ: ");
fprintf(stderr,"%.1lf\n",fisheye[i].transform[j].value*RTOD);
}
}
}
/*
Read the parameter file, loading up the FISHEYE structure
Consists of keyword and value pairs, one per line
This makes lots of assumptions, that is, is not very general and does not deal with edge cases
Comment lines have # as the first character of the line
*/
int ReadParameters(char *s)
{
int nfish = 0;
int i,j,flip;
char ignore[256],aline[256];
double angle;
FILE *fptr;
if ((fptr = fopen(s,"r")) == NULL) {
fprintf(stderr," Failed to open parameter file \"%s\"\n",s);
return(FALSE);
}
while (fgets(aline,255,fptr) != NULL) {
if (aline[0] == '#') // Comment line
continue;
if (strstr(aline,"IMAGE:") != NULL) {