用Java 对 已经 二值化了的图片 标记连通域
每块的连通域都标记不一样的数字
1 public static void main(String [] args) throws IOException { 2 //二值化 3 BufferedImage image = ImageIO.read(new File("F:/MyCode/LianTongYu/specialGray.jpg")); 4 int w = image.getWidth(); 5 int h = image.getHeight(); 6 7 int rgb = image.getRGB(0, 0); 8 int arr[][] = new int[h][w]; 9 // 获取图片每一像素点的灰度值 10 for (int i = 0; i < h; i++) { 11 for (int j = 0; j < w; j++) { 12 // getRGB()返回默认的RGB颜色模型(十进制) 13 // arr[i][j] = image.getRGB(i, j) == -1 ?0 : 1 ;//该点的灰度值 14 int tmp= image.getRGB(j, i); 15 arr[i][j] =tmp==-1? 0:1; 16 } 17 } 18 int res=getCount(arr); 19 System.out.println(res); 20 } 21 22 public static int getCount(int[][] A) { 23 int result = 0; 24 for (int i = 0; i < A.length; i++) { 25 for (int j = 0; j < A[0].length; j++) { 26 if (A[i][j] == 1) { 27 result++; 28 erase(A, i, j,result+1); 29 } 30 } 31 } 32 33 // 统计数值 34 int arrsum[] = new int [result+2]; 35 // 读取矩阵 36 for (int i = 0; i < A.length; i++) { 37 for (int j = 0; j < A[0].length; j++) { 38 if(A[i][j]!=0) 39 arrsum[A[i][j]]+=1; 40 System.out.print(A[i][j]+" "); 41 } 42 System.out.println(); 43 } 44 45 //输出统计的数值 46 for (int i = 0; i < arrsum.length; i++) { 47 System.out.println(arrsum[i]); 48 } 49 50 return result; 51 } 52 53 public static void erase(int[][] A, int i, int j,int res1) { 54 A[i][j] = res1; 55 while (i - 1 >= 0 && A[i - 1][j] == 1) { 56 erase(A, i - 1, j,res1); 57 } 58 while (i + 1 < A.length && A[i + 1][j] == 1) { 59 erase(A, i + 1, j,res1); 60 } 61 while (j - 1 >= 0 && A[i][j - 1] == 1) { 62 erase(A, i, j - 1,res1); 63 } 64 while (j + 1 < A[0].length && A[i][j + 1] == 1) { 65 erase(A, i, j + 1,res1); 66 } 67 68 } 69 }
图片:
结果: