I am at wits end with this problem.
Please note I am a really novice coder (although I'm sure you will see by my code).
The basics:
I have an image that I would like to count the number of objects in. Objects in this instance are just joined up pixels (the image has been threshold-ed and undergone binarization and binary erosion to get to this stage, code not included).
My problem:
I am trying to write some code to count how many objects there are left in this image, and within that method I call another method which is meant to remove any objects that have already been included by searching for neighbouring pixels to which they are attached. However, my current implementation of this removal method is throwing up an error: "coordinates out of bounds". I'm asking for any help solving this issue.
Code for overall object counting:
/**
* countObjects in image
*
* @param binary image to count objects in
* @param original image to put labels on
*
* @return labelled original image for graphics overlay
*/
public static BufferedImage countObjects(BufferedImage image, BufferedImage original){
BufferedImage target = copyImage(image);
int rgbBand = 0;
boolean finished = false;
Graphics labelColour = original.getGraphics();
labelColour.setColor(Color.RED);
while(!finished){
finished = false;
for ( int i=0; i<= target.getRaster().getWidth() - 1; i++ ) {
for( int j=0; j< target.getRaster().getHeight() - 1; j++ ) {
int clrz = target.getRaster().getSample(i, j, rgbBand);
if (clrz == 1) {
System.out.println(clrz);
removeObject(i, j, target);
labelColour.drawString( ""+count, i, j);
finished=true;
}
}
}
}
return original;
Code for object removal:
/**
*
* @param x
* @param y
* @param newImage
*
*/
private static void removeObject( int x, int y, BufferedImage newImage ){
int rgbBand = 0;
int[] zero = new int[] { 0 };
newImage.getRaster().setPixel(x, y, zero);
for (int a = Math.max(0, x - 1); a <= Math.min(x + 1, newImage.getRaster().getWidth()); a++) {
for (int b = Math.max(0, y - 1); b <= Math.min(y + 1, newImage.getRaster().getHeight()); b++) {
int na = a;
int nb = b;
if (newImage.getRaster().getSample(na, nb, rgbBand) == 1) {
removeObject( nc, nd, newImage );
}
}
}
}
In the above removeObject method, I am trying to use a recursive technique to remove pixel coordinates from the image being counted once either they or neighbouring pixels have been labelled.
If any of this is unclear (and I know there are probably more than a few confusing parts of my code, please ask and I will explain further).
Thanks for any help.