aboutsummaryrefslogtreecommitdiff
path: root/gabor.cpp
blob: a8105b9594cacef1a90ff1a2e04f8085610078b4 (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
/***************************************************************************
 *
 * 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>

using namespace cv;
using namespace std;

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

// parameters were lifted off the internet
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();

    cout << "Result size: " << sz << endl;

    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]);
            //cout << y << ", " << x << endl;
            outrow[x] = v;
        }
    }
    return result;
}

// hist out must have size 256
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;
}

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.
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;
}

// 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) {
#if 0
    // "cross section" the histogram
    for(int y = 20; y < 256; y++) {
        int colorchanges = 0;
        int first_end = -1;
        bool last = hist[0] >= y;
        for(int x = 1; x < 256; x++) {
            bool curr = hist[x] >= y;
            if(curr != last)
            {
                cout << "Color changes at " << x << ", " << y << endl;
                colorchanges++;
                if(first_end < 0 && last && !curr)
                    first_end = x;
            }
            last = curr;
        }

        cout << "y" << y << " has " << colorchanges << "changes" << endl;

        int sections = (colorchanges + 1) / 2;
        if(sections == 2) {
            return first_end;
        }
    }
    return -1;
#else
    // use this version
    int peak_proms[512];
    getPeakProminences(hist, peak_proms);
    qsort(peak_proms, 256, sizeof(int) * 2, compare_pair);

    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;
    }
//    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;
#endif
}

// 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;
}

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]))

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
    }
}

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;
}

// 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);
    }
}

Mat cleanMask(Mat initial) {
    // now filter the thresholded mask to extract the region
    // we care about
    int h = initial.size().height, w = initial.size().width;

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

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

    //return mask;

    // now to get rid of disconnected blobs we flood fill from
    // the center (for now we assume the center point is in
    // the largest region -- this can be changed with 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;
}

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

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;
}

int main()
{
    // filtering parameters
    const int nfilts = 10;
    Mat reference, reference_filtered;

    // alignment parameters
    //bool

    bool homography = false;
    int ecc_iters = 100;
    double ecc_eps = 1e-5;
    int warp_mode = MOTION_TRANSLATION;

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

            Mat img_c3;
            img_c3 = imread(buf);

            resize(img_c3, img_c3, Size(500, 500));

            // grayscale conversion
            Mat img;
            cvtColor(img_c3, img, COLOR_BGR2GRAY);
            //GaussianBlur(img, img, Size(15, 15), 0, 0);

            imshow("orig", img);

            Mat inverted = Scalar::all(255) - img;

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

            // Gabor filtering
            Mat result = summedGaborFilter(inverted, nfilts, 5, 13, 2);
            result.convertTo(result, CV_8UC1, -255, 255); // uninvert while we're at it
            imshow("filtered", result);

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

            // blur filtered result
            Mat blurred;
            GaussianBlur(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, img);

            imshow("mask", mask);

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

            imshow("extracted", masked);

            Mat masked_filter_result = Mat(mask.size(), CV_8UC3, Scalar(0xff, 0, 0xff));
            //Mat masked_filter_result;
            result.copyTo(masked_filter_result, mask);
            imshow("extracted & filtered", masked_filter_result);

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

            // try alignment
            if(reference.empty())
            {
                reference = masked;
                reference_filtered = masked_filter_result;
            }
            else
            {
                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 = findTransformECC(/*reference,*/ reference_filtered,
                                                /*masked,*/ masked_filter_result,
                                                warp_matrix,
                                                warp_mode,
                                                TermCriteria (TermCriteria::COUNT+TermCriteria::EPS,
                                                              ecc_iters, ecc_eps),
                                                mask);

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

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

                imshow("aligned", warped_image);

                cout << "ECC coef: " << coeff << endl;
                cout << "Sizes: " << warped_image.size() << ", " << reference.size() << endl;

                // create red/green overlay
                Mat overlay = redGreenOverlay(warped_image, reference);
                imshow("overlay", overlay);
            }

            waitKey(0);
        }
    }
}