用Java 对 已经 二值化了的图片 标记连通域
每块的连通域都标记不一样的数字
public static void main(String [] args) throws IOException {
//二值化
BufferedImage image = ImageIO.read(new File("F:/MyCode/LianTongYu/specialGray.jpg"));
int w = image.getWidth();
int h = image.getHeight(); int rgb = image.getRGB(0, 0);
int arr[][] = new int[h][w];
// 获取图片每一像素点的灰度值
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// getRGB()返回默认的RGB颜色模型(十进制)
// arr[i][j] = image.getRGB(i, j) == -1 ?0 : 1 ;//该点的灰度值
int tmp= image.getRGB(j, i);
arr[i][j] =tmp==-1? 0:1;
}
}
int res=getCount(arr);
System.out.println(res);
} public static int getCount(int[][] A) {
int result = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
if (A[i][j] == 1) {
result++;
erase(A, i, j,result+1);
}
}
} // 统计数值
int arrsum[] = new int [result+2];
// 读取矩阵
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
if(A[i][j]!=0)
arrsum[A[i][j]]+=1;
System.out.print(A[i][j]+" ");
}
System.out.println();
} //输出统计的数值
for (int i = 0; i < arrsum.length; i++) {
System.out.println(arrsum[i]);
} return result;
} public static void erase(int[][] A, int i, int j,int res1) {
A[i][j] = res1;
while (i - 1 >= 0 && A[i - 1][j] == 1) {
erase(A, i - 1, j,res1);
}
while (i + 1 < A.length && A[i + 1][j] == 1) {
erase(A, i + 1, j,res1);
}
while (j - 1 >= 0 && A[i][j - 1] == 1) {
erase(A, i, j - 1,res1);
}
while (j + 1 < A[0].length && A[i][j + 1] == 1) {
erase(A, i, j + 1,res1);
} }
}
图片:
结果:
@_@