-
Notifications
You must be signed in to change notification settings - Fork 0
/
spt.cc
2126 lines (1876 loc) · 56.1 KB
/
spt.cc
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
//
// SST Pattern Test
//
/*
TODO:
Let C be the cluster
Let R be the restored pixels within C
Let F be the front
The size of restoration |R| should not be greater than |F|**2
*/
/*
* TODO: relabels the fronts:
* fronts = fronts * [dilated fronts]
* Then, remove smalls fronts by connected components, etc.
*/
#include "spt.h"
#include "fastBilateral.hpp"
// features
enum {
FEAT_LAT,
FEAT_LON,
FEAT_SST,
FEAT_DELTA,
FEAT_OMEGA,
NFEAT,
};
// front statistics
typedef struct FrontStat FrontStat;
struct FrontStat {
int size; // front size in pixels
double sstmag; // average SST gradient magnitude
int lsize, rsize; // size of left and right sides
double lsst, rsst; // average SST of left and right sides
double ldelta, rdelta; // average delta of left and right sides
double lsstanom, rsstanom; // average SST anomaly
int lcloud, rcloud; // number of ACSPO cloud pixels
int ndiff;
double sstdiffmean; // mean of SST difference between left and right sides
double sstdiffvar; // variance of SST difference between left and right sides
bool ok; // do we want this front?
};
typedef struct Front Front;
struct Front {
vector<int> ind;
vector<int> leftind, rightind;
bool accept;
};
// thernal fronts and their sides
enum {
FRONT_INVALID = -1,
FRONT_INIT = 0, // initial fronts (stage 1)
FRONT_BIG, // big enough fronts (stage 2)
FRONT_OK, // final fronts (stage 3)
FRONT_THIN, // thinned fronts (stage 4)
FRONT_LEFT, // left side
FRONT_RIGHT, // right side
};
void
frontstatsmat(vector<FrontStat> &v, Mat &dst)
{
dst.create(v.size(), 9, CV_32FC1);
for(int i = 0; i < (int)v.size(); i++){
dst.at<float>(i, 0) = v[i].lsst;
dst.at<float>(i, 1) = v[i].rsst;
dst.at<float>(i, 2) = v[i].ldelta;
dst.at<float>(i, 3) = v[i].rdelta;
dst.at<float>(i, 4) = v[i].lsstanom;
dst.at<float>(i, 5) = v[i].rsstanom;
dst.at<float>(i, 6) = v[i].lcloud / (double)v[i].lsize;
dst.at<float>(i, 7) = v[i].rcloud / (double)v[i].rsize;
dst.at<float>(i, 8) = v[i].sstdiffvar;
}
}
class Var // variable
{
public:
bool inrange(float val) {
return !isnan(val) && min <= val && val <= max;
};
virtual int quantize(float val) = 0;
Mat mat;
float min, max;
double scalefeat; // scale feature by
bool avgfeat; // use average for a cluster as feature
};
class SST : public Var
{
public:
SST(Mat &m) {
mat = m;
min = SST_LOW;
max = SST_HIGH;
avgfeat = true;
scalefeat = 1.0;
};
int quantize(float val) {
return cvRound((val - SST_LOW) * (1.0/TQ_STEP));
};
};
class Delta : public Var
{
public:
Delta(Mat &m) {
mat = m;
min = DELTA_LOW;
max = DELTA_HIGH;
avgfeat = true;
scalefeat = 1.0;
};
int quantize(float val) {
return cvRound((val - DELTA_LOW) * (1.0/DQ_STEP));
};
};
class Omega : public Var
{
public:
Omega(Mat &m) {
mat = m;
min = OMEGA_LOW;
max = OMEGA_HIGH;
avgfeat = true;
scalefeat = 1.0;
};
int quantize(float val) {
return cvRound((val - OMEGA_LOW) * (1.0/OQ_STEP));
};
};
class CMCAnom : public Var
{
public:
CMCAnom(Mat &m) {
mat = m;
min = ANOMALY_LOW;
max = ANOMALY_HIGH;
avgfeat = true;
scalefeat = 1.0;
};
int quantize(float val) {
return cvRound((val - ANOMALY_LOW) * (1.0/AQ_STEP));
};
};
class SSTAnom : public Var
{
public:
SSTAnom(Mat &m) {
mat = m;
min = -999;
max = 999;
avgfeat = true;
scalefeat = 1.0;
};
int quantize(float val) {
return val <= 0 ? 0 : 1;
};
};
class Lat : public Var
{
public:
Lat(Mat &m) {
mat = m;
min = -90;
max = 90;
avgfeat = false;
scalefeat = 10.0;
};
int quantize(float val) {
float la = abs(val);
if(la < 30)
return 0;
if(la < 45)
return 1;
if(la < 60)
return 2;
return 3;
};
};
class Lon : public Var
{
public:
Lon(Mat &m) {
mat = m;
min = -180;
max = 180;
avgfeat = false;
scalefeat = 10.0;
}
int quantize(float val) { abort(); }
};
class QVar // quantized variable
{
public:
QVar(Mat &m) { mat = m; };
Mat mat;
int min, max;
};
// Quantize variables.
//
// n -- number of variables
// src -- images of variables (source) that needs to be quantized
// _omega, _sstmag -- omega and gradient magnitude image
// _deltamag -- delta image
// dst -- destination where quantized images are stored (output)
//
static void
quantize(int n, Var **src, const Mat &_easyclouds, const Mat &_deltarange,
const Mat &_omega, const Mat &_sstmag,
const Mat &_deltamag, QVar **dst)
{
int i, k;
bool ok;
uchar *easyclouds;
float *deltarange, *omega, *sstmag, *deltamag;
CV_Assert(n > 0);
Size size = src[0]->mat.size();
for(k = 0; k < n; k++)
CHECKMAT(src[k]->mat, CV_32FC1);
for(k = 0; k < n; k++){
dst[k]->mat.create(size, CV_16SC1);
dst[k]->mat = Scalar(-1);
}
CHECKMAT(_easyclouds, CV_8UC1);
CHECKMAT(_deltarange, CV_32FC1);
CHECKMAT(_omega, CV_32FC1);
CHECKMAT(_sstmag, CV_32FC1);
CHECKMAT(_deltamag, CV_32FC1);
easyclouds = _easyclouds.data;
deltarange = (float*)_deltarange.data;
omega = (float*)_omega.data;
sstmag = (float*)_sstmag.data;
deltamag = (float*)_deltamag.data;
// quantize variables
for(i = 0; i < (int)size.area(); i++){
if(easyclouds[i]
|| deltarange[i] > DELTARANGE_THRESH
|| sstmag[i] > GRAD_LOW // || delta[i] < -0.5
|| deltamag[i] > DELTAMAG_LOW
|| (omega[i] < OMEGA_LOW || omega[i] > OMEGA_HIGH))
continue;
ok = true;
for(k = 0; k < n; k++){
float *s = (float*)src[k]->mat.data;
if(!src[k]->inrange(s[i])){
ok = false;
break;
}
}
if(ok){
for(k = 0; k < n; k++){
float *s = (float*)src[k]->mat.data;
short *d = (short*)dst[k]->mat.data;
d[i] = src[k]->quantize(s[i]);
}
}
}
for(k = 0; k < n; k++){
dst[k]->min = src[k]->quantize(src[k]->min);
dst[k]->max = src[k]->quantize(src[k]->max);
}
}
// Connected components wrapper that limits the minimum size of components.
//
// mask -- the image to be labeled
// connectivity -- 8 or 4 for 8-way or 4-way connectivity respectively
// lim -- limit on the minimum size of components
// _cclabels -- destination labeled image (output)
//
static int
connectedComponentsWithLimit(const Mat &mask, int connectivity, int lim, Mat &_cclabels)
{
Mat stats, centoids, _ccrename;
int i, ncc, lab, newlab, *cclabels, *ccrename;
ncc = connectedComponentsWithStats(mask, _cclabels, stats, centoids, connectivity, CV_32S);
if(ncc <= 1)
return 0;
CHECKMAT(_cclabels, CV_32SC1);
_ccrename.create(ncc, 1, CV_32SC1);
cclabels = (int*)_cclabels.data;
ccrename = (int*)_ccrename.data;
// Remove small connected components and rename labels to be contiguous.
// Also, set background label 0 (where mask is 0) to -1.
newlab = 0;
ccrename[0] = COMP_INVALID;
for(lab = 1; lab < ncc; lab++){
if(stats.at<int>(lab, CC_STAT_AREA) >= lim)
ccrename[lab] = newlab++;
else
ccrename[lab] = COMP_SPECKLE;
}
ncc = newlab;
for(i = 0; i < (int)mask.total(); i++)
cclabels[i] = ccrename[cclabels[i]];
return ncc;
}
// Run connected component for v1 == q1 and v2 == q2, and save the features
// for the connected components in feat. Returns the number of connected
// components labeled in _cclabels.
//
// size -- size of image
// v1, v2 -- quantized values
// q1, q2 -- quantized images
// _vars -- variables used as features
// _cclabels -- label assigned to pixels where (v1 == q1 && v2 == q2) (output)
// feat -- features corresponding to _cclabels (output)
//
static int
clusterbin(Size size, int v1, int v2, const short *q1, const short *q2,
Var **_vars, Mat &_cclabels, float *feat)
{
Mat _mask, _count, _avg[NFEAT];
double *avg[NFEAT];
float *vars[NFEAT];
int i, ncc, lab, *cclabels, *count;
uchar *mask;
// create mask for (v1, v2) == (q1, q2)
_mask.create(size, CV_8UC1);
mask = (uchar*)_mask.data;
for(i = 0; i < (int)_mask.total(); i++)
mask[i] = q1[i] == v1 && q2[i] == v2 ? 255 : 0;
// run connected components on the mask
ncc = connectedComponentsWithLimit(_mask, 4, 200, _cclabels);
if(ncc <= 0)
return 0;
CHECKMAT(_cclabels, CV_32SC1);
cclabels = (int*)_cclabels.data;
// allocate temporary matrices for computing average per component
_count = Mat::zeros(ncc, 1, CV_32SC1);
count = (int*)_count.data;
for(int k = 0; k < NFEAT; k++){
vars[k] = (float*)_vars[k]->mat.data;
avg[k] = NULL;
if(_vars[k]->avgfeat){
_avg[k] = Mat::zeros(ncc, 1, CV_64FC1);
avg[k] = (double*)_avg[k].data;
}
}
// compute average per component
for(i = 0; i < size.area(); i++){
lab = cclabels[i];
if(lab < 0)
continue;
bool ok = true;
for(int k = 0; k < NFEAT; k++){
if(avg[k] && isnan(vars[k][i])){
ok = false;
break;
}
}
if(ok){
for(int k = 0; k < NFEAT; k++){
if(avg[k])
avg[k][lab] += vars[k][i];
}
count[lab]++;
}
}
for(lab = 0; lab < ncc; lab++){
for(int k = 0; k < NFEAT; k++){
if(avg[k])
avg[k][lab] /= count[lab];
}
}
/*
TODO:
where ACSPO says water: (acspo>>6) == 0,
create 2D histogram of SST vs. Delta
remove clusters for which (average SST, average delta)
fall in a low dense area in the histogram
*/
// compute features for each variables
for(i = 0; i < size.area(); i++){
lab = cclabels[i];
if(lab >= 0){
for(int k = 0; k < NFEAT; k++){
double scale = _vars[k]->scalefeat;
if(avg[k])
feat[k] = scale * avg[k][lab];
else
feat[k] = scale * vars[k][i];
}
}
feat += NFEAT;
}
return ncc;
}
// Cluster and find features. Returns the number of clusters labeled in _glabels.
//
// Q1, Q2 -- quantized variables
// vars -- variables used as features
// _glabels -- global labels (output)
// _feat -- features (output)
//
static int
cluster(QVar *Q1, QVar *Q2, Var **vars, Mat &_glabels, Mat &_feat)
{
int i, glab, *glabels;
float *feat;
short *q1, *q2;
CHECKMAT(Q1->mat, CV_16SC1);
CHECKMAT(Q2->mat, CV_16SC1);
for(int k = 0; k < NFEAT; k++)
CHECKMAT(vars[k]->mat, CV_32FC1);
Size size = vars[0]->mat.size();
_glabels.create(size, CV_32SC1);
_feat.create(size.area(), NFEAT, CV_32FC1);
q1 = (short*)Q1->mat.data;
q2 = (short*)Q2->mat.data;
feat = (float*)_feat.data;
glabels = (int*)_glabels.data;
for(i = 0; i < (int)_feat.total(); i++)
feat[i] = NAN;
for(i = 0; i < (int)_glabels.total(); i++)
glabels[i] = -1;
glab = 0;
#pragma omp parallel for
for(int v1 = Q1->min; v1 <= Q1->max; v1++){
#pragma omp parallel for
for(int v2 = Q2->min; v2 <= Q2->max; v2++){
Mat _cclabels;
int ncc, lab, *cclabels;
ncc = clusterbin(size, v1, v2, q1, q2, vars, _cclabels, feat);
CHECKMAT(_cclabels, CV_32SC1);
cclabels = (int*)_cclabels.data;
#pragma omp critical
if(ncc > 0){
for(i = 0; i < (int)_cclabels.total(); i++){
lab = cclabels[i];
if(lab >= 0)
glabels[i] = glab + lab;
else if(lab == COMP_SPECKLE)
glabels[i] = COMP_SPECKLE;
}
glab += ncc;
}
}
}
return glab;
}
// Remove features from _feat that are not on the border of clusters defined
// by the clustering labels in _glabels.
//
static void
removeinnerfeats(Mat &_feat, const Mat &_glabels)
{
int i, k;
Mat elem, _labero;
uchar *labero;
float *feat, *vs;
CHECKMAT(_feat, CV_32FC1);
CV_Assert(_feat.cols == NFEAT);
CHECKMAT(_glabels, CV_32SC1);
if(DEBUG){
k = 0;
for(i = 0; i < _feat.rows; i++){
vs = (float*)_feat.ptr(i);
if(!isnan(vs[FEAT_LAT])){
k++;
}
}
logprintf("labelnbrs: number of feature before inner feats are removed: %d\n", k);
}
// erode clusters to remove borders from clusters
elem = getStructuringElement(MORPH_RECT, Size(3, 3));
erode(_glabels >= 0, _labero, elem);
CHECKMAT(_labero, CV_8UC1);
// remove features if the pixel is in the eroded mask
labero = _labero.data;
feat = (float*)_feat.data;
for(i = 0; i < (int)_glabels.total(); i++){
if(labero[i]){
for(k = 0; k < NFEAT; k++)
feat[k] = NAN;
}
feat += NFEAT;
}
}
// Update labels by nearest label training.
//
// _feat -- features (rows containing NaNs are removed)
// _var -- varibles used to query for nearest neighbor
// _easyclouds -- easyclouds mask
// _sstmag -- gradient magnitude
// _glabels -- global labels (input & output)
//
static void
labelnbrs(Mat &_feat, Var **_vars, const Mat &_easyclouds,
const Mat &_sstmag, Mat &_glabels)
{
int i, k, *indices, *glabels;
float *vs, *vd, *vars[NFEAT], *sstmag;
Mat _indices, _labdil;
std::vector<float> q(NFEAT), dists(1);
std::vector<int> ind(1);
flann::SearchParams sparam(4);
uchar *easyclouds, *labdil;
CHECKMAT(_feat, CV_32FC1);
CV_Assert(_feat.cols == NFEAT);
CHECKMAT(_easyclouds, CV_8UC1);
CHECKMAT(_sstmag, CV_32FC1);
CHECKMAT(_glabels, CV_32SC1);
for(k = 0; k < NFEAT; k++)
CHECKMAT(_vars[k]->mat, CV_32FC1);
removeinnerfeats(_feat, _glabels);
// Remove features (rows in _feat) containing NaNs.
// There are two cases: either all the features are NaN or
// none of the features are NaN.
_indices.create(_feat.rows, 1, CV_32SC1);
indices = (int*)_indices.data;
k = 0;
for(i = 0; i < _feat.rows; i++){
vs = (float*)_feat.ptr(i);
if(!isnan(vs[FEAT_LAT]) && i != k){
vd = (float*)_feat.ptr(k);
memmove(vd, vs, NFEAT*sizeof(*vd));
indices[k] = i;
k++;
}
}
_feat = _feat.rowRange(0, k);
logprintf("labelnbrs: reduced number of features: %d\n", k);
logprintf("labelnbrs: building nearest neighbor indices...\n");
flann::Index idx(_feat, flann::KMeansIndexParams(16, 1));
logprintf("labelnbrs: searching nearest neighbor indices...\n");
// dilate all the clusters
dilate(_glabels >= 0, _labdil, getStructuringElement(MORPH_RECT, Size(101, 101)));
CHECKMAT(_labdil, CV_8UC1);
glabels = (int*)_glabels.data;
easyclouds = (uchar*)_easyclouds.data;
sstmag = (float*)_sstmag.data;
labdil = (uchar*)_labdil.data;
for(k = 0; k < NFEAT; k++)
vars[k] = (float*)_vars[k]->mat.data;
Size size = _vars[0]->mat.size();
// label based on nearest neighbor
for(i = 0; i < (int)size.area(); i++){
if(!labdil[i] || glabels[i] >= 0 // not regions added by dilation
|| easyclouds[i]
)//|| (sstmag[i] < GRAD_LOW && glabels[i] != COMP_SPECKLE))
continue;
bool ok = true;
for(k = 0; k < NFEAT; k++){
if(!_vars[k]->inrange(vars[k][i])){
ok = false;
break;
}
}
if(ok){
for(k = 0; k < NFEAT; k++){
q[k] = _vars[k]->scalefeat * vars[k][i];
}
idx.knnSearch(q, ind, dists, 1, sparam);
if(dists[0] < 5)
glabels[i] = glabels[indices[ind[0]]];
}
}
logprintf("labelnbrs: done searching nearest neighbors\n");
// TODO: erode glabels by 21, but not where sstmag < GRAD_LOW
}
// Write spt into NetCDF dataset ncid as variable named "spt_mask".
//
static void
writespt(int ncid, const Mat &spt)
{
int i, n, varid, ndims, dimids[2];
nc_type xtype;
size_t len;
CHECKMAT(spt, CV_8UC1);
const char varname[] = "spt_mask";
const char varunits[] = "none";
const char vardescr[] = "SPT mask packed into 1 byte: bits1-2 (00=clear; 01=probably clear; 10=cloudy; 11=clear-sky mask undefined); bit3 (0=no thermal front; 1=thermal front)";
// chunk sizes used by acspo_mask
const size_t chunksizes[] = {1024, 3200};
// It's not possible to delete a NetCDF variable, so attempt to use
// the variable if it already exists. Create the variable if it does not exist.
n = nc_inq_varid(ncid, varname, &varid);
if(n != NC_NOERR){
n = nc_inq_dimid(ncid, "scan_lines_along_track", &dimids[0]);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimid failed");
n = nc_inq_dimid(ncid, "pixels_across_track", &dimids[1]);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimid failed");
n = nc_def_var(ncid, varname, NC_UBYTE, nelem(dimids), dimids, &varid);
if(n != NC_NOERR)
ncfatal(n, "nc_def_var failed");
n = nc_def_var_chunking(ncid, varid, NC_CHUNKED, chunksizes);
if(n != NC_NOERR)
ncfatal(n, "nc_def_var_chunking failed");
n = nc_def_var_deflate(ncid, varid, 0, 1, 1);
if(n != NC_NOERR)
ncfatal(n, "setting deflate parameters failed");
n = nc_put_att_text(ncid, varid, "UNITS", nelem(varunits)-1, varunits);
if(n != NC_NOERR)
ncfatal(n, "setting attribute UNITS failed");
n = nc_put_att_text(ncid, varid, "Description", nelem(vardescr)-1, vardescr);
if(n != NC_NOERR)
ncfatal(n, "setting attribute Description failed");
}
// Varify that the netcdf variable has correct type and dimensions.
n = nc_inq_var(ncid, varid, NULL, &xtype, &ndims, dimids, NULL);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_var failed");
if(xtype != NC_UBYTE)
eprintf("variable type is %d, want %d\n", xtype, NC_UBYTE);
if(ndims != 2)
eprintf("variable dims is %d, want 2\n", ndims);
for(i = 0; i < 2; i++){
n = nc_inq_dimlen(ncid, dimids[i], &len);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimlen failed");
if(len != (size_t)spt.size[i])
eprintf("dimension %d is %d, want %d\n", i, len, spt.size[i]);
}
// Write data into netcdf variable.
n = nc_put_var_uchar(ncid, varid, spt.data);
if(n != NC_NOERR)
ncfatal(n, "nc_putvar_uchar failed");
}
nc_type
cv2nctype(int cvtype)
{
nc_type t;
switch(cvtype){
default:
t = NC_NAT; // not a type
break;
case CV_32FC1:
t = NC_FLOAT;
break;
case CV_8UC1:
t = NC_UBYTE;
break;
}
return t;
}
static void
createvar(int ncid, const char *varname, const Mat &data)
{
int i, n, varid, ndims, dimids[2];
nc_type xtype;
size_t len;
CV_Assert(data.isContinuous());
// It's not possible to delete a NetCDF variable, so attempt to use
// the variable if it already exists. Create the variable if it does not exist.
n = nc_inq_varid(ncid, varname, &varid);
if(n != NC_NOERR){
const char varunits[] = "none";
const char vardescr[] = "";
n = nc_inq_dimid(ncid, "scan_lines_along_track", &dimids[0]);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimid failed");
n = nc_inq_dimid(ncid, "pixels_across_track", &dimids[1]);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimid failed");
xtype = cv2nctype(data.type());
if(xtype == NC_NAT){
eprintf("unsupported type %s\n", type2str(data.type()));
}
n = nc_def_var(ncid, varname, xtype, nelem(dimids), dimids, &varid);
if(n != NC_NOERR)
ncfatal(n, "nc_def_var failed");
n = nc_def_var_deflate(ncid, varid, 0, 1, 1);
if(n != NC_NOERR)
ncfatal(n, "setting deflate parameters failed");
n = nc_put_att_text(ncid, varid, "UNITS", nelem(varunits)-1, varunits);
if(n != NC_NOERR)
ncfatal(n, "setting attribute UNITS failed");
n = nc_put_att_text(ncid, varid, "Description", nelem(vardescr)-1, vardescr);
if(n != NC_NOERR)
ncfatal(n, "setting attribute Description failed");
}
// Varify that the netcdf variable has correct type and dimensions.
n = nc_inq_var(ncid, varid, NULL, &xtype, &ndims, dimids, NULL);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_var failed");
if(cv2nctype(data.type()) != xtype)
eprintf("invalid variable type %d\n", xtype);
if(ndims != 2)
eprintf("variable dims is %d, want 2\n", ndims);
for(i = 0; i < 2; i++){
n = nc_inq_dimlen(ncid, dimids[i], &len);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimlen failed");
if(len != (size_t)data.size[i])
eprintf("dimension %d is %d, want %d\n", i, len, data.size[i]);
}
// Write data into netcdf variable.
n = nc_put_var(ncid, varid, data.data);
if(n != NC_NOERR)
ncfatal(n, "nc_put_var failed");
}
static void
writevar(int ncid, const char *varname, const Mat &data)
{
int n, varid, ndims, dimids[2];
nc_type xtype;
size_t len;
CV_Assert(data.isContinuous());
n = nc_inq_varid(ncid, varname, &varid);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_varid failed");
// Varify that the netcdf variable has correct type and dimensions.
n = nc_inq_var(ncid, varid, NULL, &xtype, &ndims, dimids, NULL);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_var failed");
switch(xtype){
default:
eprintf("invalid variable type %d\n", xtype);
break;
case NC_UBYTE:
if(data.type() != CV_8UC1)
eprintf("invalid Mat type %s", type2str(data.type()));
break;
case NC_FLOAT:
if(data.type() != CV_32FC1)
eprintf("invalid Mat type %s", type2str(data.type()));
break;
}
if(ndims != 2)
eprintf("variable dims is %d, want 2\n", ndims);
for(int i = 0; i < 2; i++){
n = nc_inq_dimlen(ncid, dimids[i], &len);
if(n != NC_NOERR)
ncfatal(n, "nc_inq_dimlen failed");
if(len != (size_t)data.size[i])
eprintf("dimension %d is %d, want %d\n", i, len, data.size[i]);
}
// Write data into netcdf variable.
n = nc_put_var(ncid, varid, data.data);
if(n != NC_NOERR)
ncfatal(n, "nc_put_var failed");
}
// Find thermal fronts.
//
// _lam2 -- local max
// _sstmag -- gradient magnitude
// _stdf -- stdfilter(sst - medianBlur(sst))
// _deltamag -- gradient magnitude of delta
// _glabels -- cluster labels before nearest neighbor lookup
// _glabelsnn -- cluster labels after nearest neighbor lookup
// _easyclouds -- easy clouds
// _anomzero -- zero crossings of anomaly
// _fronts -- thermal fronts (output)
//
static void
findfronts(const Mat &_lam2, const Mat &_sstmag, const Mat &_sstanom, const Mat &_stdf,
const Mat &_deltamag, const Mat &easyclouds, const Mat &_anomzero, Mat &_fronts)
{
Mat _dilc, _dilq;
float *lam2, *sstmag, *stdf, *deltamag;
double m, llam, lmag, lstdf, ldel;
int i;
uchar *dilc, *anomzero;
schar *fronts;
CHECKMAT(_lam2, CV_32FC1);
CHECKMAT(_sstmag, CV_32FC1);
CHECKMAT(_sstanom, CV_32FC1);
CHECKMAT(_stdf, CV_32FC1);
CHECKMAT(_deltamag, CV_32FC1);
CHECKMAT(easyclouds, CV_8UC1);
CHECKMAT(_anomzero, CV_8UC1);
_fronts.create(_sstmag.size(), CV_8SC1);
lam2 = (float*)_lam2.data;
sstmag = (float*)_sstmag.data;
float *sstanom = (float*)_sstanom.data;
stdf = (float*)_stdf.data;
deltamag = (float*)_deltamag.data;
fronts = (schar*)_fronts.data;
anomzero = _anomzero.data;
// dilate easyclouds
dilate(easyclouds, _dilc, getStructuringElement(MORPH_RECT, Size(7, 7)));
CHECKMAT(_dilc, CV_8UC1);
dilc = _dilc.data;
/*
float *_dilq = 100*(_deltamag - 0.05);
exp(_dilq, _dilq);
erode(1.0/(1+_dilq) > 0.5, _dilq, getStructuringElement(MORPH_RECT, Size(7, 7)));
CHECKMAT(_dilq, CV_32FC1);
dilq = (float*)_dilq.data;
*/
// compute thermal fronts image
for(i = 0; i < (int)_sstmag.total(); i++){
fronts[i] = FRONT_INVALID;
// continue if in (dilated) easyclouds
// or not in domain added by nearest neighbor
if(dilc[i]) // || glabelsnn[i] < 0 || glabels[i] >= 0)
continue;
// detect front based on sstmag, deltamag, anomaly
if(anomzero[i] && sstmag[i] > 0.1 && sstmag[i]/deltamag[i] > 10){
fronts[i] = FRONT_INIT;
continue;
}
// detect front based on sstmag, deltamag, lam2
m = sstmag[i];
if(m > 1)
m = 1;
ldel = 1.0/(1+exp(100*(deltamag[i]-0.05)));
llam = 1.0/(1+exp(100*(lam2[i]+0.01)));
if(m*ldel*llam > 0.5){
fronts[i] = FRONT_INIT;
continue;
}
// detect front based on sstmag, deltamag, lam2, stdf
lmag = 1.0/(1+exp(-30*(sstmag[i]-0.15)));
ldel = 1.0/(1+exp(100*(deltamag[i]-0.1)));
lstdf = 1.0/(1+exp(30*(stdf[i]-0.15)));
if(lmag*ldel*llam*lstdf > 0.5)
fronts[i] = FRONT_INIT;
}
}
// Attempt to connect broken fronts by using cos-similarity of gradient vectors.
// Each pixels within a window is compared to the pixel at the center of the
// window.
// Prototype: matlab/front_connect.m
//
// _fronts -- fronts containing only initial fronts (FRONT_INIT) (intput & output)
// _dX -- gradient in x direction
// _dY -- gradient in y direction
// _sstmag -- SST gradient magnitude
// _easyclouds -- guaranteed cloud based on various thresholds
// lam2 -- local max
//
void
connectfronts(Mat &_fronts, const Mat &_dX, const Mat &_dY,
const Mat &_sstmag, const Mat &_easyclouds, const Mat &lam2)
{
CHECKMAT(_fronts, CV_8SC1);
CHECKMAT(_dX, CV_32FC1);
CHECKMAT(_dY, CV_32FC1);
CHECKMAT(_sstmag, CV_32FC1);
CHECKMAT(_easyclouds, CV_8UC1);
char *fronts = (char*)_fronts.data;
float *dX = (float*)_dX.data;
float *dY = (float*)_dY.data;
enum {
W = 21, // window width/height
};
// pixel at center of window
const int mid = _fronts.cols*(W/2) + (W/2);
for(int iter = 0; iter < 5; iter++){
//Mat _valid = (_fronts != FRONT_INIT) & (_sstmag > 0.05)
// & (_easyclouds == 0) & (lam2 < LAM2_THRESH);
Mat _valid = (_fronts != FRONT_INIT) & (_easyclouds == 0);
CHECKMAT(_valid, CV_8UC1);
uchar *valid = (uchar*)_valid.data;
int i = 0;
// For each pixel with full window, where the pixel
// is top left corner of the window
for(int y = 0; y < _fronts.rows-W+1; y++){
for(int x = 0; x < _fronts.cols-W+1; x++){
if(fronts[i + mid] == FRONT_INIT){
double cdY = dY[i + mid];
double cdX = dX[i + mid];
double max = 0;
int k = i;
int argmax = i + mid;
for(int yy = y; yy < y+W; yy++){
for(int xx = x; xx < x+W; xx++){
// cos-similarity
double sim = dY[k]*cdY + dX[k]*cdX;
if(valid[k] != 0 && sim > max){
max = sim;
argmax = k;
}
k++;
}
k += _fronts.cols - W;
}
fronts[argmax] = FRONT_INIT;
}
i++;
}
}
}
}
void
dilatefronts(const Mat &fronts, const Mat &_sstmag, const Mat &_easyclouds, Mat &dst)
{
Mat _tmp, _bigfronts;
CHECKMAT(fronts, CV_8SC1);
CHECKMAT(_sstmag, CV_32FC1);
CHECKMAT(_easyclouds, CV_8UC1);
_tmp.create(fronts.size(), CV_32FC1);
float *sstmag = (float*)_sstmag.data;
uchar *easyclouds = _easyclouds.data;
float *tmp = (float*)_tmp.data;
connectedComponentsWithLimit(fronts==FRONT_INIT, 8, 9, _bigfronts);
CHECKMAT(_bigfronts, CV_32SC1);
int *bigfronts = (int*)_bigfronts.data;