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 package org.openimaj.image.processing.morphology;
31
32 import java.util.HashSet;
33 import java.util.Set;
34
35 import org.openimaj.image.FImage;
36 import org.openimaj.image.pixel.ConnectedComponent;
37 import org.openimaj.image.pixel.Pixel;
38 import org.openimaj.image.processing.algorithm.MaxFilter;
39 import org.openimaj.image.processor.KernelProcessor;
40 import org.openimaj.image.processor.connectedcomponent.ConnectedComponentProcessor;
41 import org.openimaj.math.geometry.shape.Rectangle;
42
43
44
45
46
47
48
49 public class Dilate implements ConnectedComponentProcessor, KernelProcessor<Float, FImage> {
50 protected StructuringElement element;
51 protected int cx;
52 protected int cy;
53 protected int sw;
54 protected int sh;
55
56
57
58
59
60
61
62 public Dilate(StructuringElement se) {
63 this.element = se;
64
65 final int[] sz = se.size();
66 sw = sz[0];
67 sh = sz[1];
68 cx = sw / 2;
69 cy = sh / 2;
70 }
71
72
73
74
75 public Dilate() {
76 this(StructuringElement.BOX);
77 }
78
79 @Override
80 public void process(ConnectedComponent cc) {
81
82 final Rectangle cc_bb = cc.calculateRegularBoundingBox();
83
84 final Set<Pixel> newPixels = new HashSet<Pixel>();
85 for (int j = (int) (cc_bb.y - sh); j <= cc_bb.y + sh + cc_bb.height; j++) {
86 for (int i = (int) (cc_bb.x - sw); i <= cc_bb.x + sw + cc_bb.width; i++) {
87 final Pixel p = new Pixel(i, j);
88
89 if (element.intersect(p, cc.getPixels()).size() >= 1) {
90 newPixels.add(p);
91 }
92 }
93 }
94
95 cc.getPixels().addAll(newPixels);
96 }
97
98 @Override
99 public int getKernelHeight() {
100 return sh;
101 }
102
103 @Override
104 public int getKernelWidth() {
105 return sw;
106 }
107
108 @Override
109 public Float processKernel(FImage patch) {
110 for (final Pixel p : element.positive) {
111 final int px = cx - p.x;
112 final int py = cy - p.y;
113 if (px >= 0 && py >= 0 && px < sw && py < sh && patch.pixels[py][px] == 1) {
114 return 1f;
115 }
116 }
117
118 for (final Pixel p : element.negative) {
119 final int px = cx - p.x;
120 final int py = cy - p.y;
121 if (px >= 0 && py >= 0 && px < sw && py < sh && patch.pixels[py][px] == 0)
122 return 1f;
123 }
124
125 return patch.pixels[cy][cx];
126 }
127
128
129
130
131
132
133
134
135
136
137 public static void dilate(FImage img, int times) {
138 final Dilate d = new Dilate();
139 for (int i = 0; i < times; i++)
140 img.processInplace(d);
141 }
142 }