aboutsummaryrefslogtreecommitdiff
path: root/gabor.cpp
blob: 24822b987f3fd4410f84e9b5c9a37ffa86d927c3 (plain)
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
/***************************************************************************
 *
 * Real-time SLO image registration
 *
 * Copyright (C) 2019 Franklin Wei
 *
 ****************************************************************************/

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>
#include <vector>

using namespace cv;
using namespace std;

// uncomment for headless mode -- for benchmarking
//#define imshow(a, b)

// Perform a maximal Gabor filtering of in with nfilts oriented
// filters at ksize x ksize kernel size. Parameters were lifted off
// the internet and need fine-tuning.
Mat maximalGaborFilter(Mat in, int nfilts = 10,
                       int ksize = 9, // kernel size
                       double sig = 3, // variance -- how wide the filter is
                       double lm = 8, // wavelength ?
                       double gm = 0.02, // aspect ratio (smaller = longer vessels), 1 : square, >1 : bad
                       double ps = 0) { // phase shift -- don't change?
    Mat filtered[nfilts];
    double dtheta = 2 * M_PI / nfilts;

    // Gabor filtering
    for(int i = 0; i < nfilts; i++)
    {
        //double theta = 0;
        Mat kern = getGaborKernel(Size(ksize, ksize), sig, i * dtheta, lm, gm, ps, CV_32F);
        Mat dest;
        filter2D(in, dest, CV_32FC1, kern);
        normalize(dest, dest, 0, 1, NORM_MINMAX);
        //imshow(string("filt") + to_string(theta), dest);
        filtered[i] = dest;
    }

    Size sz = filtered[0].size();

    Mat result = Mat(sz, CV_32F, Scalar(0));

    float *rows[nfilts];
    for(int y = 0; y < sz.height; y++) {
        for(int i = 0; i < nfilts; i++)
            rows[i] = (float*)filtered[i].ptr<float>(y);
        float *outrow = (float*)result.ptr(y);
        for(int x = 0; x < sz.width; x++) {
            float v = -1;
            for(int i = 0; i < nfilts; i++)
                v = std::max(v, rows[i][x]);
            outrow[x] = v;
        }
    }
    return result;
}

// Normalized sum of maximal gabor filtered image with varied kernel
// size.
Mat summedGaborFilter(Mat in, int nfilts, int start, int stop, int step) {
    assert(!(step & 1) && (start & 1) && (stop & 1));
    int n = (stop - start) / step + 2;
    double sf = 1. / n;

    Mat result = Mat(in.size(), CV_32F, Scalar(0));
    for(int i = start; i <= stop; i += step) {
        Mat m = maximalGaborFilter(in, nfilts, i);
        result += sf * m;
    }
    return result;
}

// Get a list of intensity frequencies for all intensities
// 0-255. *hist should point to a 256-element int array.
int getHist(Mat img, int *hist) {
    assert(img.type() == CV_8U);
    memset(hist, 0, sizeof(int) * 256);
    unsigned char *ptr = img.ptr<unsigned char>(0);
    int ymax = 0;
    for(int i = 0; i < img.size().height * img.size().width; i++)
        ymax = std::max(++hist[*ptr++], ymax);
    return ymax;
}

void dumpHist(int *hist) {
    for(int i = 0; i < 256; i+=1)
        cout << setw(4) << i << " " << hist[i] << endl;
}

// Plot a histogram. highlight is a column to be highlighted in red.
Mat plotHist(int *hist, int ymax, int highlight) {
    Mat img = Mat(Size(256, 256), CV_8UC3, Scalar(0xff,0xff,0xff));
    for(int x = 0; x < 256; x++) {
        line(img, Point(x, 255), Point(x, 255 - hist[x] / (double)ymax * 255), x == highlight ? Scalar(0, 0, 0xff) : Scalar(0,0,0));
    }
    return img;
}

// Return a 512-element integer array giving the "prominence" of each
// element of hist with its preceding index -- that is, the minimum
// distance in either direction that one needs to travel to find an
// element of equal or greater value (for the maximum value in the
// array, it will have prominence 256).
//
// Sorting the array by pairs of ints will give the peaks by
// prominence.

// TODO: refactor with a struct
void getPeakProminences(const int *hist, int *out) {
    for(int i = 0; i < 256; i++) {
        *out++ = i;
        int elem = hist[i];
        if(!elem)
            *out = 1;
        else
        {
            bool done = false;
            for(int j = 1; !done && (i - j >= 0 || i + j < 256); j++)
            {
                if(i - j >= 0 && hist[i - j] > elem)
                    *out = j, done = true;
                else if(i + j < 256 && hist[i + j] > elem)
                *out = j, done = true;
            }
            if(!done)
                *out = 999;
        }
        out++;
    }
}

int compare_pair(const void *a, const void *b) {
    const int *l = (const int*)a + 1, *r = (const int*)b + 1;
    if(*l < *r) return 1;
    if(*l > *r) return -1;
    return 0;
}

#define ABS(x) (((x) < 0) ? (-(x)) : (x))

// sorted_peak_proms is a 512-element int array of (peak, prominence)
// tuples. This function looks for numerically adjacent peaks of equal
// prominence and filters them. Might not work.
void dedupe_adjacent(int *sorted_peak_proms) {
    int out[512];
    int out_idx = 0;
    for(int i = 0; i < 512;) {
        out[out_idx] = sorted_peak_proms[i];
        out[out_idx + 1] = sorted_peak_proms[i + 1];
        out_idx += 2;
        int j;
        for(j = i + 2; j < 512 && sorted_peak_proms[j + 1] == sorted_peak_proms[i + 1] && ABS(sorted_peak_proms[j] - sorted_peak_proms[i]) == 1; j += 2);
        i = j;
    }
    memcpy(sorted_peak_proms, out, sizeof(out));
}

// get the threshold to filter out the periphial blind spots (will not
// go past maxLum, which is the threshold returned by Otsu's method,
// which is consistently an overestimate).
int getThreshold(const int *hist) {
    int peak_proms[512];
    getPeakProminences(hist, peak_proms);
    qsort(peak_proms, 256, sizeof(int) * 2, compare_pair);

    cout << "Peaks by prominence (before):" << endl;
    for(int i = 0; i < 4; i++) {
        cout << "x=" << peak_proms[2 * i + 0] << "(" << peak_proms[2 * i + 1] << ")" << endl;
    }

    dedupe_adjacent(peak_proms);

    cout << "Peaks by prominence:" << endl;
    for(int i = 0; i < 4; i++) {
        cout << "x=" << peak_proms[2 * i + 0] << "(" << peak_proms[2 * i + 1] << ")" << endl;
    }

    int idx1 = peak_proms[0], idx2 = peak_proms[2];
    cout << "Minimum of interest lies between " << idx2 << ", " << idx1 << endl;

    if(!(idx2 < idx1)) {
        cout << "WARNING: peak finding failed" << endl;
        int tmp = idx1;
        idx1 = idx2;
        idx2 = tmp;
    }
    //assert(idx2 < idx1);

    // find minimum
    int min_idx = idx2;
    for(int i = idx2 + 1; i < idx1; i++)
        if(hist[i] < hist[min_idx])
            min_idx = i;

    return min_idx;
}

bool inBounds(int x, int y, Size sz) {
    return (0 <= x && x < sz.width) && (0 <= y && y < sz.height);
}

#define ARRAYLEN(x) (sizeof(x) / sizeof(x[0]))

// Iterative flood fill to clean up an image mask.
void floodFill(int x, int y,
               Mat map, Mat visited,
               unsigned char target, unsigned char replace)
{
    queue<pair<int, int> > q;

    q.push(pair<int, int>(x, y));

    // BFS
    while(q.size() > 0) {
        pair<int, int> p = q.front();
        q.pop();
        x = p.first;
        y = p.second;
        if(!inBounds(x, y, map.size()))
            continue;

        if(visited.at<unsigned char>(y, x) == replace || map.at<unsigned char>(y, x) == target)
            continue;

        visited.at<unsigned char>(y, x) = replace;

        int delts[] = { -1, 0, 1, 0, 0, -1, 0, 1 };
        for(int i = 0; i < ARRAYLEN(delts); i += 2) {
            int xp = x + delts[i + 0],
                yp = y + delts[i + 1];
            q.push(pair<int, int>(xp, yp));
        }

#if 0
        imshow("progress", visited);
        waitKey(1);
#endif
    }
}

// Flood fill in from the border to isolate the center region.
// in visited, != 0 means not visited, 0 means visited
void borderFlood(Mat map, Mat visited) {
    Size sz = map.size();
    int w = sz.width, h = sz.height;

    for(int x = 0; x < w; x++) {
        floodFill(x, 0, map, visited, 255, 0);
        floodFill(x, h - 1, map, visited, 255, 0);
    }
    for(int y = 1; y < h - 1; y++) {
        floodFill(0, y, map, visited, 255, 0);
        floodFill(w - 1, y, map, visited, 255, 0);
    }
}

// Clean up our raw mask, produced by thresholding the MOG filtered
// images, by removing outside "islands" of white and "holes" of
// black.
Mat cleanMask(Mat initial) {
    int h = initial.size().height, w = initial.size().width;

    // white = ROI
    Mat mask = Mat(h, w, CV_8U, Scalar(255));

    // flood fill from the four boundaries to get the region
    // we want
    borderFlood(initial, mask);

    // Now to get rid of disconnected blobs, we flood fill from the
    // center (this assumes the center point is in the largest region
    // -- but this can be changed in a "real" algorithm to find the
    // largest connected region)
    Mat mask2 = Mat(h, w, CV_8U, Scalar(0));
    floodFill(w / 2, h / 2, mask, mask2, 0, 255);

    return mask2;
}

// Prompt the user to select the saturation image in orig. Zeroes the
// corresponding region in mask.
Mat removeSatRegion(Mat mask, Mat orig) {
    static bool firstRun = true;

    static Rect roi;
    if(firstRun)
        roi = selectROI("select saturation region", orig), firstRun = false;

    rectangle(mask, roi, Scalar(0), FILLED);
    return mask;
}

// Generate a red-green overlay.
Mat redGreenOverlay(Mat rPlane, Mat gPlane) {
    assert(rPlane.size() == gPlane.size());
    Mat planes[3] = { Mat::zeros(rPlane.size(), CV_8U),
                      gPlane * .6,
                      rPlane };
    Mat out;
    merge(planes, 3, out);
    return out;
}

// Perform automatic segmentation. Returns the masked initial frame,
// along with auxilliary outputs.
struct processed_frame {
    Mat masked_frame,
        masked_frame_filtered;
    Mat mask;
};

processed_frame preprocessFrame(Mat frame)
{
    // filtering parameters
    const int nfilts = 10;

    resize(frame, frame, Size(500, 500));

    // grayscale conversion
    Mat frame_gray;
    cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
    //GaussianBlur(frame_gray, frame_gray, Size(15, 15), 0, 0);

    imshow("orig", frame_gray);

    Mat gray_inverted = Scalar::all(255) - frame_gray;

    // convert to float
    gray_inverted.convertTo(gray_inverted, CV_32F, 1.0, 0);
    normalize(gray_inverted, gray_inverted, 0, 1, NORM_MINMAX);

    // Gabor filtering
    Mat filter_result = summedGaborFilter(gray_inverted, nfilts, 5, 13, 2);
    filter_result.convertTo(filter_result, CV_8UC1, -255, 255); // cast back to char, uninvert while we're at it
    imshow("filtered", filter_result);

    // calculate histogram
    int hist[256];
    int ymax = getHist(filter_result, hist);
    //dumpHist(hist);

    // blur filtered filter_result
    Mat blurred;
    GaussianBlur(filter_result, blurred, Size(5, 5), 0, 0);

    // threshold out background
    Mat threshed;

    // Otsu's method doesn't work -- too high of a threshold
    //double t = threshold(blurred, threshed, 0, 255, THRESH_BINARY | THRESH_OTSU);
    //imshow("thresholded", threshed);
    //cout << "Otsu threshold: " << t << endl;

    int t = getThreshold(hist);

    cout << "Our threshold: " << t << endl;

    // get initial mask by thresholding the filtered image
    threshold(blurred, threshed, t, 255, THRESH_BINARY);
    imshow("thresholded", threshed);

    // clean up mask -- remove islands and holes
    Mat mask = cleanMask(threshed);

    // remove saturation region from mask
    mask = removeSatRegion(mask, frame_gray);

    imshow("mask", mask);

    // if you want a magenta background
    Mat masked_result = Mat(mask.size(), CV_8UC3, Scalar(0xff, 0, 0xff));
    //Mat masked_result;
    frame_gray.copyTo(masked_result, mask);

    imshow("masked result", masked_result);

    Mat masked_filter_result = Mat(mask.size(), CV_8UC3, Scalar(0xff, 0, 0xff));
    //Mat masked_filter_result;
    filter_result.copyTo(masked_filter_result, mask);

    imshow("extracted & filtered", masked_filter_result);

    // plot histogram
    Mat histplot = plotHist(hist, ymax, t);
    imshow("hist", histplot);

    processed_frame ret = { masked_result, masked_filter_result, mask };

    return ret;
}

Mat alignFrames(Mat reference_filtered, processed_frame moving)
{
    int ecc_iters = 100;
    double ecc_eps = 1e-5;

    // Translation works best. Higher DoF modes (affine, homography)
    // are slow and introduce errors.
    int warp_mode = MOTION_TRANSLATION;

    Mat warp_matrix;
    if(warp_mode == MOTION_HOMOGRAPHY)
        warp_matrix = Mat::eye(3, 3, CV_32F);
    else
        warp_matrix = Mat::eye(2, 3, CV_32F);

    double coeff;

    try
    {
        coeff = findTransformECC(reference_filtered,
                                 moving.masked_frame_filtered,
                                 warp_matrix,
                                 warp_mode,
                                 TermCriteria (TermCriteria::COUNT+TermCriteria::EPS,
                                               ecc_iters, ecc_eps),
                                 moving.mask);

        Mat warped_image = Mat(reference_filtered.rows, reference_filtered.cols, CV_32FC1);

        if (warp_mode != MOTION_HOMOGRAPHY)
            warpAffine(moving.masked_frame, warped_image, warp_matrix, warped_image.size(),
                       INTER_LINEAR + WARP_INVERSE_MAP);
        else
            warpPerspective(moving.masked_frame, warped_image, warp_matrix, warped_image.size(),
                            INTER_LINEAR + WARP_INVERSE_MAP);

        imshow("aligned", warped_image);

        cout << "ECC coef: " << coeff << endl;

        return warped_image;
    }
    catch(cv::Exception e) {
        cerr << "Alignment failed: " << e.what() << endl;
    }

    return Mat();
}

Mat averageStack(vector<Mat> aligned_frames)
{
    double sf = 1. / aligned_frames.size();

    Mat result = Mat(aligned_frames[0].size(), CV_32F, Scalar(0));
    for(Mat i : aligned_frames)
    {
        Mat scaled;
        i.convertTo(scaled, CV_32F, sf / 255.0);
        result += scaled;
    }

    return result;
}

Mat produceMosaic(vector<Mat> frames)
{
    vector<processed_frame> preproc(frames.size());

    for(int i = 0; i < frames.size(); i++) {
        preproc[i] = preprocessFrame(frames[i]);
    }

    // align all to first frame and mosaic
    vector<Mat> aligned(frames.size()), overlays(frames.size());

    for(int i = 0; i < frames.size(); i++) {
        aligned[i] = alignFrames(preproc[0].masked_frame, preproc[i]);
        overlays[i] = redGreenOverlay(aligned[i], preproc[0].masked_frame);
        imshow("overlay", overlays[i]);
    }

    // now average
    Mat mosaic = averageStack(aligned);

    imshow("mosaic", mosaic);

    waitKey(0);

    return mosaic;
}

#define NFRAMES 22

vector<Mat> loadData()
{
    vector<Mat> stack(NFRAMES);

    for(int i = 1; i <= NFRAMES; i++)
    {
        char buf[128];
        snprintf(buf, sizeof(buf), "SLO Data for registration/SLO001/SLO_subject001_frame%d.png", i);

        stack[i - 1] = imread(buf);
    }

    return stack;
}

int main()
{
    vector<Mat> stack = loadData();

    produceMosaic(stack);
}