I am currently trying to iterate over every pixel of a black and white image in OpenCV 4.1.2 in Java and to store e 3x3 Matrix for every pixel, which should have a 1, if the pixel currently worked with has e neighbouring pixel there, and an 0 if there is no neighbour at this position. So the value in the center of the Mat should always be 1. Currently im working with that nested for-loops, that should iterate through the Mat.
Mat bwDrawing = new Mat(drawing.size(), CvType.CV_8UC3);
Imgproc.cvtColor(drawing, bwDrawing, Imgproc.COLOR_RGB2GRAY);
List<MatOfInt> freemanChains = new ArrayList<>();
for (double y = 2; y-2 < bwDrawing.size().height; y++) {
for (double x = 2; x-2 < bwDrawing.size().width; x++) {
MatOfInt freemanMat = new MatOfInt();
if (bwDrawing.get((int)y-1, (int)x-1)[0] != 0) {
freemanMat.put(0, 0, 1);
} else {
freemanMat.put(0,0, 0);
}
if (bwDrawing.get((int)y-1, (int)x)[0] != 0) {
freemanMat.put(0, 1, 1);
} else {
freemanMat.put(0,1, 0);
}
if (bwDrawing.get((int)y-1, (int)x+1)[0] == 0) { //right here is the NullPointer Exception
freemanMat.put(0, 2, 1);
} else {
freemanMat.put(0,2, 0);
}
if (bwDrawing.get((int)y, (int)x-1)[0] != 0) {
freemanMat.put(1, 0, 1);
} else {
freemanMat.put(1,0, 0);
}
if (bwDrawing.get((int)y, (int)x)[0] != 0) {
freemanMat.put(1, 1, 1);
} else {
freemanMat.put(1,1, 0);
}
if (bwDrawing.get((int)y, (int)x+1)[0] != 0) {
freemanMat.put(1, 2, 1);
} else {
freemanMat.put(1,2, 0);
}
if (bwDrawing.get((int)y+1, (int)x-1)[0] != 0) {
freemanMat.put(2, 0, 1);
} else {
freemanMat.put(2,0, 0);
}
if (bwDrawing.get((int)y+1, (int)x)[0] != 0) {
freemanMat.put(2, 1, 1);
} else {
freemanMat.put(2,1, 0);
}
if (bwDrawing.get((int)y+1, (int)x+1)[0] != 0) {
freemanMat.put(2, 2, 1);
} else {
freemanMat.put(2,2, 0);
}
freemanChains.add(freemanMat);
// System.out.println(freemanMat.get(2, 2)[0]);
}
}
As marked by the comment in the code, im getting an NullPointer Exception the first time im checking for a pixel at x+1. And i do not understand why.
My overall goal is tho calculate a Freeman Chain Code of some contours, and i hope to achieve it with that somehow. Are there any other options in OpenCV to get the Freeman Chain Code since they removed it from the findContours() function?
Any help to both problems is much appreciated. Thank you.