Using Java to mark a connected field with a binary image
Each block of connected fields is marked with a different number
1 Public Static voidMain (String [] args)throwsIOException {2 //two value of3BufferedImage image = Imageio.read (NewFile ("F:/mycode/liantongyu/specialgray.jpg"));4 intW =image.getwidth ();5 inth =image.getheight ();6 7 intRGB = Image.getrgb (0, 0);8 intArr[][] =New int[h][w];9 //get the grayscale value for each pixel of a pictureTen for(inti = 0; I < H; i++) { One for(intj = 0; J < W; J + +) { A //getRGB () returns the default RGB color model (decimal) - //Arr[i][j] = Image.getrgb (i, j) = =-1? 0:1;//the grayscale value of the point - inttmp=Image.getrgb (J, i); theARR[I][J] =tmp==-1? 0:1; - } - } - intres=GetCount (arr); + System.out.println (res); - } + A Public Static intGetCount (int[] A) { at intresult = 0; - for(inti = 0; i < a.length; i++) { - for(intj = 0; J < A[0].length; J + +) { - if(A[i][j] = = 1) { -result++; -Erase (A, I, j,result+1); in } - } to } + - //Statistical Values the intArrsum[] =New int[Result+2]; * //Read Matrix $ for(inti = 0; i < a.length; i++) {Panax Notoginseng for(intj = 0; J < A[0].length; J + +) { - if(a[i][j]!=0) theArrsum[a[i][j]]+=1; +System.out.print (a[i][j]+ ""); A } the System.out.println (); + } - $ //the value of the output statistic $ for(inti = 0; i < arrsum.length; i++) { - System.out.println (Arrsum[i]); - } the - returnresult;Wuyi } the - Public Static voidEraseint[] A,intIintJintres1) { WuA[I][J] =res1; - while(i-1 >= 0 && a[i-1][j] = = 1) { AboutErase (A, i-1, j,res1); $ } - while(i + 1 < a.length && a[i + 1][j] = = 1) { -Erase (A, i + 1, j,res1); - } A while(j-1 >= 0 && a[i][j-1] = = 1) { +Erase (A, I, j-1, res1); the } - while(j + 1 < a[0].length && A[i][j + 1] = = 1) { $Erase (A, I, J + 1), res1); the } the the } the}
Image:
Results:
@[email protected]
Java two-valued image recognition connected domain