-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path_passive.cpp
executable file
·819 lines (644 loc) · 33.2 KB
/
_passive.cpp
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
/* C++ extension for stereo matching algorithms */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <numpy/arrayobject.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <thread>
#include "headers/safequeue.hpp"
#include "headers/colorconversion.hpp"
// ******************************** ASW ********************************
void workerASW(SafeQueue<int> &jobs, npy_ubyte *data1, npy_ubyte *data2, double *dataLab1, double *dataLab2,
npy_int16 *disparityMap, double *proximityWeights, double gammaC,
int width, int height, int winSize, int padding,
int minDisparity, int maxDisparity)
{
int dBest;
double cost, costBest, tot;
int ii,jj,kk;
int i,j,y,x,d;
double *w1 = new double[winSize*winSize]; // Weights
double *w2 = new double[winSize*winSize];
while(!jobs.empty())
{
jobs.pop(y); // Get element, put it in y and remove from queue
for(x=0; x < width; ++x) { // For each column on left image
// Pre-compute weights for left window
for(i = 0; i < winSize; ++i) {
ii = y - padding + i;
if( ii < 0) continue; // Image top border
if( ii >= height) break; // Image bottom border
for(j = 0; j < winSize; ++j) {
jj = x - padding + j;
if(jj<0) continue;
if(jj>=width) break;
w1[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab1[3*(ii*width + jj) ] - dataLab1[3*(y*width + x) ],2) +
pow(dataLab1[3*(ii*width + jj)+1] - dataLab1[3*(y*width + x)+1],2) +
pow(dataLab1[3*(ii*width + jj)+2] - dataLab1[3*(y*width + x)+2],2) )/gammaC);
}
}
dBest = 0;
costBest = INFINITY; // Initialize cost to an high value
for(d = x-minDisparity; d >= std::max(0,x-maxDisparity); --d) { // For each allowed disparity (reverse order)
cost = 0; // Cost of current match
tot = 0; // Sum of weights
for(i = 0; i < winSize; ++i) {
ii = y - padding + i;
if( ii < 0) continue; // Image top border
if( ii >= height) break; // Image bottom border
for(j = 0; j < winSize; ++j) {
jj = d - padding + j;
kk = x - padding + j;
if(jj<0 || kk<0) continue;
if(jj>=width || kk>=width) break;
// Build weight
w2[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab2[3*(ii*width + jj) ] - dataLab2[3*(y*width + d) ],2) +
pow(dataLab2[3*(ii*width + jj)+1] - dataLab2[3*(y*width + d)+1],2) +
pow(dataLab2[3*(ii*width + jj)+2] - dataLab2[3*(y*width + d)+2],2) )/gammaC);
// Update cost
cost += w1[i*winSize+j]*w2[i*winSize+j]*std::min( 40, abs(data1[3*(ii*width + kk) ] - data2[3*(ii*width + jj) ]) +
abs(data1[3*(ii*width + kk)+1] - data2[3*(ii*width + jj)+1]) +
abs(data1[3*(ii*width + kk)+2] - data2[3*(ii*width + jj)+2]) );
// And denominator
tot += w1[i*winSize+j]*w2[i*winSize+j];
}
}
// Weighted average
cost = cost / tot;
if(cost < costBest) {
costBest = cost;
dBest = d;
}
}
// Update disparity
disparityMap[y*width + x] = x-dBest;
}
} // End of while
}
void workerASWconsistent(SafeQueue<int> &jobs, npy_ubyte *data1, npy_ubyte *data2, double *dataLab1, double *dataLab2,
npy_int16 *disparityMap, double *proximityWeights, double gammaC,
int width, int height, int winSize, int padding,
int minDisparity, int maxDisparity)
{
int dBest;
double cost, costBest, tot;
int ii,jj,kk;
int i,j,y,x,d;
double *w1 = new double[winSize*winSize]; // Weights
double *w2 = new double[winSize*winSize];
int left,right,k;
while(!jobs.empty())
{
jobs.pop(y); // Get element, put it in y and remove from queue
for(x=0; x < width; ++x) { // For each column on left image
// Pre-compute weights for left window
for(i = 0; i < winSize; ++i) {
ii = y-padding+i;
if(ii<0) continue;
if(ii>=height) break;
for(j = 0; j < winSize; ++j) {
jj = x-padding+j;
if(jj<0) continue;
if(jj>=width) break;
w1[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab1[3*(ii*width + jj) ] - dataLab1[3*(y*width+x) ],2) +
pow(dataLab1[3*(ii*width + jj)+1] - dataLab1[3*(y*width+x)+1],2) +
pow(dataLab1[3*(ii*width + jj)+2] - dataLab1[3*(y*width+x)+2],2) )/gammaC);
}
}
dBest = 0;
costBest = INFINITY; // Initialize cost to an high value
for(d = x-minDisparity; d >= std::max(0,x-maxDisparity); --d) { // For each allowed disparity ON RIGHT (reverse order)
cost = 0; // Cost of current match
tot = 0; // Sum of weights
for(i = 0; i < winSize; ++i) {
ii = y-padding+i;
if(ii<0) continue;
if(ii>=height) break;
for(j = 0; j < winSize; ++j) {
jj = d-padding+j;
kk = x-padding+j;
if(jj<0 || kk<0) continue;
if(jj>=width || kk>=width) break;
// Build weight
w2[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab2[3*(ii*width + jj) ] - dataLab2[3*(y*width+d) ],2) +
pow(dataLab2[3*(ii*width + jj)+1] - dataLab2[3*(y*width+d)+1],2) +
pow(dataLab2[3*(ii*width + jj)+2] - dataLab2[3*(y*width+d)+2],2) )/gammaC);
// Update cost
cost += w1[i*winSize+j]*w2[i*winSize+j]*std::min( 40, abs(data1[3*(ii*width + kk)] - data2[3*(ii*width + jj)]) +
abs(data1[3*(ii*width + kk)+1] - data2[3*(ii*width + jj)+1]) +
abs(data1[3*(ii*width + kk)+2] - data2[3*(ii*width + jj)+2]) );
// And denominator
tot += w1[i*winSize+j]*w2[i*winSize+j];
}
}
// Weighted average
cost = cost / tot;
if(cost < costBest) {
costBest = cost;
dBest = d;
}
}
// Update disparity
disparityMap[y*width + x] = x-dBest;
}
// Consistency check *****************
for(x=0; x < width; ++x) { // For each column on RIGHT image
// Pre-compute weights for RIGHT window
for(i = 0; i < winSize; ++i) {
ii = y-padding+i;
if(ii<0) continue;
if(ii>=height) break;
for(j = 0; j < winSize; ++j) {
jj = x-padding+j;
if(jj<0) continue;
if(jj>=width) break;
w2[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab2[3*(ii*width + jj) ] - dataLab2[3*(y*width+x) ],2) +
pow(dataLab2[3*(ii*width + jj)+1] - dataLab2[3*(y*width+x)+1],2) +
pow(dataLab2[3*(ii*width + jj)+2] - dataLab2[3*(y*width+x)+2],2) )/gammaC);
}
}
dBest = 0;
costBest = INFINITY; // Initialize cost to an high value
for(d = x+minDisparity; d <= std::min(width-1,x+maxDisparity); ++d) { // For each allowed disparity ON LEFT
cost = 0; // Cost of current match
tot = 0; // Sum of weights
for(i = 0; i < winSize; ++i) {
ii = y-padding+i;
if(ii<0) continue;
if(ii>=height) break;
for(j = 0; j < winSize; ++j) {
jj = d-padding+j;
kk = x-padding+j;
if(jj<0 || kk<0) continue;
if(jj>=width || kk>=width) break;
// Build weight
w1[i*winSize+j] = proximityWeights[i*winSize + j] *
exp(-sqrt( pow(dataLab1[3*(ii*width + jj) ] - dataLab1[3*(y*width+d) ],2) +
pow(dataLab1[3*(ii*width + jj)+1] - dataLab1[3*(y*width+d)+1],2) +
pow(dataLab1[3*(ii*width + jj)+2] - dataLab1[3*(y*width+d)+2],2) )/gammaC);
// Update cost
cost += w1[i*winSize+j]*w2[i*winSize+j]*std::min( 40, abs(data2[3*(ii*width + kk) ] - data1[3*(ii*width + jj) ]) +
abs(data2[3*(ii*width + kk)+1] - data1[3*(ii*width + jj)+1]) +
abs(data2[3*(ii*width + kk)+2] - data1[3*(ii*width + jj)+2]) );
// And denominator
tot += w1[i*winSize+j]*w2[i*winSize+j];
}
}
// Weighted average
cost = cost / tot;
if(cost < costBest) {
costBest = cost;
dBest = d;
}
}
// Update disparity map (dBest-x is the disparity, dBest is the best x coordinate on img1)
if(disparityMap[y*width + dBest] != dBest-x) // Check if equal to first calculation
disparityMap[y*width + dBest] = -1; // Invalidated pixel!
}
// Left-Right consistency check
// Disparity value == -1 means invalidated (occluded) pixel
for(j=0; j < width; ++j) {
if(disparityMap[y*width + j] == -1){
// Find limits
left = j-1;
right = j+1;
while(left>=0 && disparityMap[y*width + left] == -1){
--left;
}
while(right<width && disparityMap[y*width + right] == -1){
++right;
}
// Left and right contain the first non occluded pixel in that direction
// Ensure that we are within image limits
// and assing valid value to occluded pixels
if(left < 0){
for(k=0;k<right;++k)
disparityMap[y*width + k] = disparityMap[y*width + right];
}
else if(right > width-1){
for(k=left+1;k<width;++k)
disparityMap[y*width + k] = disparityMap[y*width + left];
}
else{
for(k=left+1;k<right;++k)
disparityMap[y*width + k] = std::min(disparityMap[y*width + left],disparityMap[y*width + right]); // Set background disparity
}
}
}
} // End of while
}
PyObject *computeASW(PyObject *self, PyObject *args)
{
PyArrayObject *img1, *img2;
int winSize, maxDisparity, minDisparity;
double gammaC, gammaP;
int consistent = 0; // Optional value
// Parse input. See https://docs.python.org/3/c-api/arg.html
if (!PyArg_ParseTuple(args, "O!O!iiidd|p", &PyArray_Type, &img1, &PyArray_Type, &img2,
&winSize, &maxDisparity, &minDisparity, &gammaC, &gammaP,
&consistent)){
PyErr_SetString(PyExc_ValueError, "Invalid input format!");
return NULL;
}
// Check input format
if (!(PyArray_TYPE(img1) == NPY_UBYTE && PyArray_TYPE(img1) == NPY_UBYTE)){
// Raising an exception in C is done by setting the exception object or string and then returning NULL from the function.
// See https://docs.python.org/3/c-api/exceptions.html
PyErr_SetString(PyExc_TypeError, "Wrong type input!");
return NULL;
}
if (PyArray_NDIM(img1)!=3 || PyArray_NDIM(img1)!=PyArray_NDIM(img2) ||
PyArray_DIM(img1,2)!=3 || PyArray_DIM(img2,2)!=3 ||
PyArray_DIM(img1,0)!=PyArray_DIM(img2,0) ||
PyArray_DIM(img1,1)!=PyArray_DIM(img2,1)){
PyErr_SetString(PyExc_ValueError, "Wrong image dimensions!");
return NULL;
}
if (!(winSize>0 && winSize%2==1)) {
PyErr_SetString(PyExc_ValueError, "winSize must be a positive odd number!");
return NULL;
}
//Retrieve input
int height = PyArray_DIM(img1,0);
int width = PyArray_DIM(img1,1);
// See https://numpy.org/devdocs/reference/c-api/dtype.html
npy_ubyte *data1 = (npy_ubyte *)PyArray_DATA(img1); // Pointer to first element (casted to right type!)
npy_ubyte *data2 = (npy_ubyte *)PyArray_DATA(img2); // These are 1D arrays, (f**k)!
// Convert to CIELab
ColorConversion cc;
double *dataLab1 = new double[height*width*3];
double *dataLab2 = new double[height*width*3];
cc.ImageFromBGR2Lab(data1, dataLab1, width, height);
cc.ImageFromBGR2Lab(data2, dataLab2, width, height);
// Initialize disparity map
npy_intp disparityMapDims[2] = {height, width};
PyArrayObject *disparityMapObj = (PyArrayObject*)PyArray_EMPTY(2, disparityMapDims, NPY_INT16,0);
npy_int16 *disparityMap = (npy_int16 *)PyArray_DATA(disparityMapObj); // Pointer to first element
// Working variables
int padding = winSize / 2;
int i,j;
SafeQueue<int> jobs; // Jobs queue
int num_threads = std::thread::hardware_concurrency();
std::thread* workersArr = new std::thread[num_threads];
// Build proximity weights matrix
double *proximityWeights = new double[winSize*winSize];
for(i = 0; i < winSize; ++i) {
for(j = 0; j < winSize; ++j) {
proximityWeights[i*winSize+j] = exp(-sqrt( pow(i-padding,2) + pow(j-padding,2))/gammaP);
}
}
// TEMP
//printf("BGR %d %d %d\n", data1[3*(90*width + 67)], data1[3*(90*width + 67)+1], data1[3*(90*width + 67)+2]);
//printf("LAB %f %f %f\n", dataLab1[3*(90*width + 67)], dataLab1[3*(90*width + 67)+1], dataLab1[3*(90*width + 67)+2]);
// Put each image row in queue
for(i=0; i < height; ++i) {
jobs.push(i);
}
if(!consistent) {
// Start workers
for(i = 0; i < num_threads; ++i) {
workersArr[i] = std::thread( workerASW, std::ref(jobs), data1, data2, dataLab1, dataLab2,
disparityMap, proximityWeights, gammaC,
width, height, winSize, padding, minDisparity, maxDisparity);
}
} else { // If consistent mode is chosen
// Start consistent workers
for(i = 0; i < num_threads; ++i) {
workersArr[i] = std::thread( workerASWconsistent, std::ref(jobs), data1, data2, dataLab1, dataLab2,
disparityMap, proximityWeights, gammaC,
width, height, winSize, padding, minDisparity, maxDisparity);
}
}
// Join threads
for(i = 0; i < num_threads; ++i) {
workersArr[i].join();
}
return PyArray_Return(disparityMapObj);
}
// ******************************** GSW ********************************
void workerGSW(SafeQueue<int> &jobs, npy_ubyte *data1, npy_ubyte *data2,
npy_int16 *disparityMap, int width, int height, int winSize, int padding,
int minDisparity, int maxDisparity, int gamma, float fMax, int iterations, int bins)
{
int dBest;
float cost, costBest, temp, wBest;
int ii,jj,kk;
int i,j,k,y,x,d;
int tot = winSize*winSize;
float* w = new float[tot]; // Weights
int center = (tot-1) / 2;
int xx, yy;
int left,right;
while(!jobs.empty())
{
jobs.pop(y); // Get element, put it in y and remove from queue
// USING LEFT IMAGE AS REFERENCE
for(x=0; x < width; ++x) { // For each column on left image
/* Build geodesic map approximation*/
/* Refer to "Distance Transformations in Digital Images", GUNILLA BORGEFORS*/
// Weights initialization
for(i=0;i<tot;i++){
w[i]=INFINITY; // Set all weights to high value
}
w[center] = 0; // Except for the center one
// Iterations
for (d=0;d<iterations;++d){
// Forward pass (row major order)
for(i=0;i<tot;++i){ // For every window pixel
yy = y-padding + i/winSize; // Whole image coordinates
xx = x-padding + i%winSize;
if(xx<0 || yy<0) continue; //Image left border
if(xx>=width || yy>=height) break; // Image right border
wBest = INFINITY;
for(k=0;k<=center;++k) // Find minimum in upper kernel
{
jj = y-padding + k/winSize; // Whole image coordinates (kernel)
kk = x-padding + k%winSize;
if(jj<0 || kk<0) continue;
if(jj>=height || kk>=width) break;
// OVER THE UPPER KERNEL
temp = w[k] + sqrt( pow(data1[3*(yy*width + xx) ] - data1[3*(jj*width + kk) ],2)
+ pow(data1[3*(yy*width + xx)+1] - data1[3*(jj*width + kk)+1],2)
+ pow(data1[3*(yy*width + xx)+2] - data1[3*(jj*width + kk)+2],2) );
if(temp<wBest) wBest=temp;
}
w[i] = wBest;
}
// Backward pass (reverse row major order)
for(i=tot-1;i>=0;--i){ // For every window pixel
yy = y-padding + i/winSize; // Whole image coordinates
xx = x-padding + i%winSize;
if(yy<0 || xx<0) continue;
if(yy>=height || xx>=width) break;
wBest = INFINITY;
for(k=center;k<tot;++k) // Find minimum in upper kernel
{
jj = y-padding + k/winSize; // Whole image coordinates (kernel)
kk = x-padding + k%winSize;
if(jj<0 || kk<0) continue;
if(jj>=height || kk>=width) break;
// OVER THE LOWER KERNEL
temp = w[k] + sqrt( pow(data1[3*(yy*width + xx) ] - data1[3*(jj*width + kk) ],2)
+ pow(data1[3*(yy*width + xx)+1] - data1[3*(jj*width + kk)+1],2)
+ pow(data1[3*(yy*width + xx)+2] - data1[3*(jj*width + kk)+2],2) );
if(temp<wBest) wBest=temp;
}
w[i] = wBest;
}
}
// Convert to weights
for(i=0;i<tot;i++){
w[i]=exp(-w[i]/gamma);
}
// Calculate best disp
dBest = 0;
costBest = INFINITY; // Initialize cost to an high value
for(d = x-minDisparity; d >= std::max(0,x-maxDisparity); --d) { // For each allowed x-coord on image 2 (reverse order)
cost=0; // Cost of current match
// MUTUAL INFORMATION
/* Needs to be implemented, but it's difficult to.
* OpenCV Stereo_SGBM replaced the matching cost as well. */
// SQUARED COLOR DIFFERENCES
cost = 0; // Cost of current match
for(i = 0; i < winSize; ++i) {
ii = y - padding + i;
if( ii < 0) continue; // Image top border
if( ii >= height) break; // Image bottom border
for(j = 0; j < winSize; ++j) {
kk = x - padding + j;
jj = d - padding + j;
if( jj < 0 || kk < 0) continue; // Image left border
if( jj >= width || kk >= width) break; // Image right border
// Update cost
// Color difference is capped to fMax
cost += w[i*winSize + j] * std::min(fMax,
(float) sqrt(pow(data1[3*(ii*width + kk)] - data2[3*(ii*width + jj) ], 2)
+ pow(data1[3*(ii*width + kk)+1] - data2[3*(ii*width + jj)+1], 2)
+ pow(data1[3*(ii*width + kk)+2] - data2[3*(ii*width + jj)+2], 2)) );
}
}
if(cost < costBest) {
costBest = cost;
dBest = d;
}
}
// Update disparity
disparityMap[y*width + x] = x-dBest;
}
// USING RIGHT IMAGE AS REFERENCE
for(x=0; x < width; ++x) { // For each column on left image
/* Build geodesic map approximation, managing border areas too */
// Weights initialization
for(i=0;i<tot;i++){
w[i]=INFINITY; // Set all weights to high value
}
w[center] = 0; // Except for the center one
// Iterations
for (d=0;d<iterations;++d){
// Forward pass (row major order)
for(i=0;i<tot;++i){ // For every window pixel
yy = y-padding + i/winSize; // Whole image coordinates
if(yy<0 || yy>=height) continue; //Image y border
xx = x-padding + i%winSize;
if(xx<0 || xx>=width) continue; // Image x border
wBest = INFINITY;
for(k=0;k<=center;++k) // Find minimum in upper kernel
{
jj = y-padding + k/winSize; // Whole image coordinates (kernel)
if(jj<0 || jj>=height) continue;
kk = x-padding + k%winSize;
if(kk<0 || kk>=width) continue;
// OVER THE UPPER KERNEL
temp = w[k] + sqrt( pow(data2[3*(yy*width + xx) ] - data2[3*(jj*width + kk) ],2)
+ pow(data2[3*(yy*width + xx)+1] - data2[3*(jj*width + kk)+1],2)
+ pow(data2[3*(yy*width + xx)+2] - data2[3*(jj*width + kk)+2],2) );
if(temp<wBest) wBest=temp;
}
w[i] = wBest;
}
// Backward pass (reverse row major order)
for(i=tot-1;i>=0;--i){ // For every window pixel
yy = y-padding + i/winSize; // Whole image coordinates
if(yy<0 || yy>=height) continue; //Image y border
xx = x-padding + i%winSize;
if(xx<0 || xx>=width) continue; // Image x border
wBest = INFINITY;
for(k=center;k<tot;++k) // Find minimum in upper kernel
{
jj = y-padding + k/winSize; // Whole image coordinates (kernel)
if(jj<0 || jj>=height) continue;
kk = x-padding + k%winSize;
if(kk<0 || kk>=width) continue;
// OVER THE LOWER KERNEL
temp = w[k] + sqrt( pow(data2[3*(yy*width + xx) ] - data2[3*(jj*width + kk) ],2)
+ pow(data2[3*(yy*width + xx)+1] - data2[3*(jj*width + kk)+1],2)
+ pow(data2[3*(yy*width + xx)+2] - data2[3*(jj*width + kk)+2],2) );
if(temp<wBest) wBest=temp;
}
w[i] = wBest;
}
}
// Convert to weights
for(i=0;i<tot;i++){
w[i]=exp(-w[i]/gamma);
}
// Calculate best disp
dBest = 0;
costBest = INFINITY; // Initialize cost to an high value
for(d = x+minDisparity; d <= std::min(width-1,x+maxDisparity); ++d) { // For each allowed disparity ON LEFT
cost=0; // Cost of current match
// SQUARED COLOR DIFFERENCES
cost = 0; // Cost of current match
for(i = 0; i < winSize; ++i) {
ii = y - padding + i;
if( ii < 0) continue; // Image top border
if( ii >= height) break; // Image bottom border
for(j = 0; j < winSize; ++j) {
kk = x - padding + j;
jj = d - padding + j;
if( jj < 0 || kk < 0) continue; // Image left border
if( jj >= width || kk >= width) break; // Image right border
// Update cost
// Color difference is capped to fMax
cost += w[i*winSize + j] * std::min(fMax,
(float) sqrt(pow(data2[3*(ii*width + kk)] - data1[3*(ii*width + jj) ], 2)
+ pow(data2[3*(ii*width + kk)+1] - data1[3*(ii*width + jj)+1], 2)
+ pow(data2[3*(ii*width + kk)+2] - data1[3*(ii*width + jj)+2], 2)) );
}
}
if(cost < costBest) {
costBest = cost;
dBest = d;
}
}
// Update disparity map (dBest-x is the disparity, dBest is the best x coordinate on img1)
if(disparityMap[y*width + dBest] != dBest-x) // Check if equal to first calculation
disparityMap[y*width + dBest] = -1; // Invalidated pixel!
}
// Left-Right consistency check
// Disparity value == -1 means invalidated (occluded) pixel
for(j=0; j < width; ++j) {
if(disparityMap[y*width + j] == -1){
// Find limits
left = j-1;
right = j+1;
while(left>=0 && disparityMap[y*width + left] == -1){
--left;
}
while(right<width && disparityMap[y*width + right] == -1){
++right;
}
// Left and right contain the first non occluded pixel in that direction
// Ensure that we are within image limits
// and assing valid value to occluded pixels
if(left < 0){
for(k=0;k<right;++k)
disparityMap[y*width + k] = disparityMap[y*width + right];
}
else if(right > width-1){
for(k=left+1;k<width;++k)
disparityMap[y*width + k] = disparityMap[y*width + left];
}
else{
for(k=left+1;k<right;++k)
disparityMap[y*width + k] = std::min(disparityMap[y*width + left],disparityMap[y*width + right]);
}
}
}
} // End of while
}
PyObject *computeGSW(PyObject *self, PyObject *args)
{
PyArrayObject *img1, *img2;
int winSize, maxDisparity, minDisparity, gamma, iterations, bins;
float fMax;
// Parse input. See https://docs.python.org/3/c-api/arg.html
if (!PyArg_ParseTuple(args, "O!O!iiiifii", &PyArray_Type, &img1, &PyArray_Type, &img2,
&winSize, &maxDisparity, &minDisparity, &gamma,
&fMax, &iterations, &bins)){
PyErr_SetString(PyExc_ValueError, "Invalid input format!");
return NULL;
}
// Check input format
if (!(PyArray_TYPE(img1) == NPY_UBYTE && PyArray_TYPE(img1) == NPY_UBYTE)){
// Raising an exception in C is done by setting the exception object or string and then returning NULL from the function.
// See https://docs.python.org/3/c-api/exceptions.html
PyErr_SetString(PyExc_TypeError, "Wrong type input!");
return NULL;
}
if (PyArray_NDIM(img1)!=3 || PyArray_NDIM(img1)!=PyArray_NDIM(img2) ||
PyArray_DIM(img1,2)!=3 || PyArray_DIM(img2,2)!=3 ||
PyArray_DIM(img1,0)!=PyArray_DIM(img2,0) ||
PyArray_DIM(img1,1)!=PyArray_DIM(img2,1)){
PyErr_SetString(PyExc_ValueError, "Wrong image dimensions!");
return NULL;
}
if (!(winSize>0 && winSize%2==1)) {
PyErr_SetString(PyExc_ValueError, "winSize must be a positive odd number!");
return NULL;
}
//Retrieve input
int height = PyArray_DIM(img1,0);
int width = PyArray_DIM(img1,1);
// See https://numpy.org/devdocs/reference/c-api/dtype.html
npy_ubyte *data1 = (npy_ubyte *)PyArray_DATA(img1); // Pointer to first element (casted to right type!)
npy_ubyte *data2 = (npy_ubyte *)PyArray_DATA(img2); // These are 1D arrays, (f**k)!
// Initialize disparity map
npy_intp disparityMapDims[2] = {height, width};
PyArrayObject *disparityMapObj = (PyArrayObject*)PyArray_EMPTY(2, disparityMapDims, NPY_INT16, 0);
npy_int16 *disparityMap = (npy_int16 *)PyArray_DATA(disparityMapObj); // Pointer to first element
// Working variables
int padding = winSize / 2;
int i;
SafeQueue<int> jobs; // Jobs queue
int num_threads = std::thread::hardware_concurrency();
std::thread* workersArr = new std::thread[num_threads];
// Put each image row in queue
for(i=0; i < height; ++i) {
jobs.push(i);
}
for(i = 0; i < num_threads; ++i) {
workersArr[i] = std::thread( workerGSW, std::ref(jobs), data1, data2,
disparityMap, width, height, winSize,
padding, minDisparity, maxDisparity, gamma, fMax, iterations, bins);
}
// Join threads
for(i = 0; i < num_threads; ++i) {
workersArr[i].join();
}
return PyArray_Return(disparityMapObj);
}
/*____________________PYTHON MODULE INITIALIZATION____________________*/
static struct PyMethodDef module_methods[] = {
/* {name (external), function, calling, doc} */
{"computeASW", computeASW, METH_VARARGS, NULL},
{"computeGSW", computeGSW, METH_VARARGS, NULL},
{NULL,NULL,0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_passive",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit__passive(void)
{
PyObject *m;
import_array(); //This function must be called to use Numpy C-API
m = PyModule_Create(&moduledef);
if (m == NULL) {
return NULL;
}
return m;
}