## 图像二值化处理Java

1.设最小灰度值为Gmin，最大灰度值为Gmax，阈值初始化为T(0)=(Gmin+Gmax)/2。

2.以阈值T(k)将图像分割为前景和背景，求出整个前景像素的平均灰度值Gf和整个背景像素的平均灰度值Gb，此时阈值T(k)=(Gf+Gb)/2 (k=0,1,2...);

3.若此时T(k)=T(k+1)，那么此时收敛，得到最佳阈值。否则回到步骤2，直到阈值收敛到某一个值。

 1 public class Binary {
2     public static int[] getBinaryImg(int w, int h, int[] inputs) {
3         int[] gray = new int[w * h];
4         int[] newpixel = new int[w * h];
5         for (int index = 0; index < w * h; index++) {
6             int red = (inputs[index] & 0x00FF0000) >> 16;
7             int green = (inputs[index] & 0x0000FF00) >> 8;
8             int blue = inputs[index] & 0x000000FF;
9             gray[index] = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
10         }
11         //求出最大灰度值zmax和最小灰度值zmin
12         int Gmax = gray[0], Gmin = gray[0];
13         for (int index = 0; index < w * h; index++) {
14             if (gray[index] > Gmax) {
15                 Gmax = gray[index];
16             }
17             if (gray[index] < Gmin) {
18                 Gmin = gray[index];
19             }
20         }
21
22         //获取灰度直方图
23         int i, j, t, count1 = 0, count2 = 0, sum1 = 0, sum2 = 0;
24         int bp, fp;
25         int[] histogram = new int[256];
26         for (t = Gmin; t <= Gmax; t++) {
27             for (int index = 0; index < w * h; index++) {
28                 if (gray[index] == t)
29                     histogram[t]++;
30             }
31         }
32
33         /*
34         * 迭代法求出最佳分割阈值
35         * */
36         int T = 0;
37         int newT = (Gmax + Gmin) / 2;//初始阈值
38         while (T != newT)
39         //求出背景和前景的平均灰度值bp和fp
40         {
41             for (i = 0; i < T; i++) {
42                 count1 += histogram[i];//背景像素点的总个数
43                 sum1 += histogram[i] * i;//背景像素点的灰度总值
44             }
45             bp = (count1 == 0) ? 0 : (sum1 / count1);//背景像素点的平均灰度值
46
47             for (j = i; j < histogram.length; j++) {
48                 count2 += histogram[j];//前景像素点的总个数
49                 sum2 += histogram[j] * j;//前景像素点的灰度总值
50             }
51             fp = (count2 == 0) ? 0 : (sum2 / count2);//前景像素点的平均灰度值
52             T = newT;
53             newT = (bp + fp) / 2;
54         }
55         int finestYzt = newT; //最佳阈值
56
57         //二值化
58         for (int index = 0; index < w * h; index++) {
59             if (gray[index] > finestYzt)
60                 newpixel[index] = Color.WHITE;
61             else newpixel[index] = Color.BLACK;
62         }
63         return newpixel;
64     }
65 }

posted on 2017-05-28 20:13  萌虾  阅读(5162)  评论(0编辑  收藏

• 随笔 - 13
• 文章 - 0
• 评论 - 1
• 引用 - 0