简体   繁体   中英

Connected Component Labelling in Java

I am currently trying to create some Java code to do Connected Component Labelling.

a sort of explanation of how it works is here: http://aishack.in/tutorials/labelling-connected-components-example/

I have gotten to the point in my code where i am looking at a pixel and comparing all the pixels around it. I am utterly lost now, I am having great difficulty finding out what i use to store whether a pixel is a background pixel, an object previously discovered or a new object.

My question is what do i call or change to allow me to store these values. Thank you in advance.

(here's my code so far for clarity)

private void connectedComponentLabelling(ImageProcessor ip) {

    int w = ip.getWidth();
    int h = ip.getHeight();
    int background = 255; //black
    int foreground = 0;   //white
    int nextLabel = 1;

    int [] linked;
    int [][] NEIGHBOUR = new int [w][h];

    for (int v=0; v<h; v++){
        for (int u=0; u<w; u++){
            if (ip.getPixel(v,u) != background){

                for (int j=-1; j<=1; j++){
                    for (int i=-1; i<=1; i++){

                        int p = ip.getPixel(v+j, u+i);

                        if (p != background){

                            //linked[nextLabel];
                            NEIGHBOUR[v][u] = nextLabel;

                    }else{
                     nextLabel++;
                    }



                }
            }
        }
    }
    }

Some tips:

  • Since you are scanning pixels from top-left to bottom-right, then you should compare only pixels you have alredy scanned. So you should only compare up-left,up,up-right and left pixels.

  • Then, if all these pixels are a background (this means you don't know to what connect this new pixel) you create a new label for this pixel: NEIGHBOUR[v][u] = nextLabel++

  • If, on the other way, you find that one of these pixels are not background, then you assign their label to this pixel. For instace, if you find that the up-left pixel is not part of the backgroun, then you propagate its label to the current pixel: NEIGHBOUR[v][u] = NEIGHBOUR[v-1][u-1] .

  • When you do this check, you may also found that more than one neighbors have different NEIGHBOUR[v][u] value. Eg NEIGHBOUR[v-1][u-1]!=NEIGHBOUR[v-1][u+1] . In this case, you add this information to a map, say connections.put(NEIGHBOUR[v-1][u-1],NEIGHBOUR[v-1][u+1]) . but this is worth a new question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM