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.contour;
31
32 import org.openimaj.image.FImage;
33 import org.openimaj.image.pixel.Pixel;
34
35
36
37
38
39
40
41 enum Direction {
42 NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NORTH_WEST;
43 static int[] dirx = new int[] { 0, 1, 1, 1, 0, -1, -1, -1 };
44 static int[] diry = new int[] { -1, -1, 0, 1, 1, 1, 0, -1 };
45 static Direction[] entry = new Direction[] {
46 WEST, WEST, NORTH, NORTH, EAST, EAST, SOUTH, SOUTH
47 };
48 static Direction[] ccentry = new Direction[] {
49 EAST, SOUTH, SOUTH, WEST, WEST, NORTH, NORTH, EAST
50 };
51
52
53
54
55 public Direction clockwise() {
56 final Direction[] vals = Direction.values();
57 final Direction dir = vals[(ordinal() + 1) % vals.length];
58
59 return dir;
60 }
61
62
63
64
65 public Direction counterClockwise() {
66 final Direction[] vals = Direction.values();
67 final int desired = ordinal() - 1;
68 final Direction dir = vals[desired == -1 ? desired + vals.length : desired];
69 return dir;
70 }
71
72
73
74
75
76
77
78 public Pixel active(FImage img, Pixel point) {
79 final int ord = ordinal();
80 final int yy = point.y + diry[ord];
81 final int xx = point.x + dirx[ord];
82 if (xx < 0 || xx >= img.width || yy < 0 || yy >= img.height)
83 return null;
84 final float pix = img.pixels[yy][xx];
85 return pix != 0 ? new Pixel(xx, yy) : null;
86 }
87
88
89
90
91
92 public Direction clockwiseEntryDirection() {
93 return entry[ordinal()];
94 }
95
96
97
98
99
100 public Direction counterClockwiseEntryDirection() {
101 return ccentry[ordinal()];
102 }
103
104
105
106
107
108
109 public static Direction fromTo(Pixel from, Pixel to) {
110 if (from.equals(to))
111 return null;
112 if (from.y == to.y) {
113 if (from.x < to.x)
114 return EAST;
115 else
116 return WEST;
117 }
118 else if (from.y < to.y) {
119 if (from.x == to.x)
120 return SOUTH;
121 else if (from.x < to.x)
122 return SOUTH_EAST;
123 else
124 return SOUTH_WEST;
125 }
126 else {
127 if (from.x == to.x)
128 return NORTH;
129 if (from.x < to.x)
130 return NORTH_EAST;
131 else
132 return NORTH_WEST;
133 }
134 }
135
136
137
138
139
140 public Pixel pixel(Pixel from) {
141 return new Pixel(from.x + dirx[ordinal()], from.y + diry[ordinal()]);
142 }
143 }