The equivalence table can be implemented using a HashMap
. Each time you find a label that is equivalent to another label, just add that relation to the hash map.
final Map<Integer, Integer> equivalenceTable = new HashMap<>();
So whenever you find two labels that are equal, just put them in the equivalence table.
private void storeEquivalence(final Integer label0, final Integer label1, final Map<Integer, Integer> table) {
if (table.keySet().contains(label0)) {
table.put(label1, table.get(label0));
}
else if (table.keySet().contains(label1)) {
table.put(label0, table.get(label1));
}
else {
table.put(label0, label1);
}
}
So when you identify that region[x-1][y]
and region[x][y-1]
are equal, you should check if the labels are different (they should be) and update the equivalence table if the are by calling
storeEquivalence(region[x-1][y], region[x][y-1], equivalenceTable);
Then in the second pass you simply replace each label that has a value in the equivalence table.
for (int x = 1; x < imageTwo.getWidth(); x++) {
for (int y =1; y < imageTwo.getHeight(); y++) {
if (equivalenceTable.keySet().contains(region[x][y])) {
region[x][y] = equivalenceTable.get(region[x][y]);
}
}
}