I am trying to mask my binary image in a way, that it only shows certain labels (selected by me).
This piece of code does what I want. Can someone please tell me the better way to achieve this? I suppose you can do it with masks without iterating over each pixel, but the code examples that I find are always in C++ and I can't find out how to do it in Java.
Mat labels = new Mat();
Mat stats = new Mat();
Mat centroids = new Mat();
List<Integer> labelsToKeep = new ArrayList<>();
Imgproc.connectedComponentsWithStats(binary, labels, stats, centroids, 4);
for (int i=0; i < stats.height(); i++) {
// for each label
if (someCondition)
labelsToKeep.add(i);
}
Mat mask = new Mat(binary.rows(), binary.cols(), binary.type());
for (int i=0; i < binary.rows(); i++) {
for (int j=0; j < binary.cols(); j++) {
// for each pixel
double[] data = new double[1];
if (labelsToKeep.contains((int)labels.get(i,j)[0]))
data[0] = 255;
else
data[0] = 0;
mask.put(i,j, channels);
}
}
Mat masked = new Mat();
binary.copyTo(masked, mask);
Regards