1 module preprocessor;
2 
3 import mir.ndslice, mir.rc;
4 import oclcv;
5 import dplug.core;
6 
7 // Hue is 0..180
8 immutable int Hmin1 = 52, Smin1 = 50, Vmin1 = 0;
9 immutable int Hmax1 = 104, Smax1 = 255, Vmax1 = 125;
10 
11 /////////////////////////// set above for a desired color ////////////////////
12 enum a1 = 3; // kernel size and interations of Morphology Transform
13 enum i1 = 1;
14 enum a2 = 3; 
15 enum i2 = 1;
16 
17 
18 struct Preprocessor {
19     @disable this();
20 private:
21     CLContext clctx;
22     CLBuffer d_rgb;
23     HSVConv rgb2hsvconv;
24     INRANGE3 thresholder;
25     MorphED eroder;
26     MorphED dilater;
27 
28     Slice!(RCI!ubyte, 3, Contiguous) hsv;
29 public:
30     Slice!(RCI!ubyte, 2, Contiguous) thresh1;
31     
32     this(int height, int width){
33         hsv = rcslice!ubyte([height, width, 3], 0);
34         thresh1 = rcslice!ubyte([height, width], 0);
35 
36         clctx = mallocNew!CLContext;
37         eroder = mallocNew!MorphED(height, width, ERODE, a1, clctx);
38         dilater = mallocNew!MorphED(height, width, DILATE, a1, clctx);
39         rgb2hsvconv = mallocNew!HSVConv(height, width, RGB2HSV, clctx);
40         thresholder = mallocNew!INRANGE3(height, width, clctx);
41         d_rgb = mallocNew!CLBuffer(clctx, BufferMeta(UBYTE, height, width, 3));
42     }
43     
44     ~this(){
45         destroyFree(d_rgb);
46         destroyFree(thresholder);
47         destroyFree(rgb2hsvconv);
48         destroyFree(dilater); 
49         destroyFree(eroder);
50         destroyFree(clctx);
51     }
52     
53     void binarize(ref Slice!(ubyte*, 3, Contiguous) frame){
54         d_rgb.upload(frame.ptr[0..frame.elementCount]);
55 
56         auto d_hsv = rgb2hsvconv.run(d_rgb);
57         scope(exit) destroyFree(d_hsv);
58 
59         auto d_thresh1 = thresholder.run(d_hsv, Hmin1, Hmax1, Smin1, Smax1, Vmin1, Vmax1);
60         scope(exit) destroyFree(d_thresh1);
61 
62         auto d_eroded = eroder.run(d_thresh1);
63         scope(exit) destroyFree(d_eroded);
64 
65         auto d_dilated = dilater.run(d_eroded);
66         scope(exit) destroyFree(d_dilated);
67         
68         auto d_dilated2 = dilater.run(d_dilated);
69         scope(exit) destroyFree(d_dilated2);
70 
71         auto d_eroded2 = eroder.run(d_dilated2);
72         scope(exit) destroyFree(d_eroded2);
73         
74         d_eroded2.download(thresh1.ptr[0..thresh1.elementCount]);
75     }
76     
77 }