二值化基本概念:通俗的講就是把一副彩色圖像處理成一副黑白圖像,一般是作為后續復雜圖像處理操作的預處理。
二值化算法思路:遍歷圖像的所有像素點,計算每個像素點的灰度值。通過迭代法收斂得到一個最佳閾值,灰度值大於最佳閾值的像素點設為白色,灰度值小於最佳閾值的像素點設為黑色。(我這里的二值化處理結果是,背景是白色,前景是黑色)
迭代法獲取最佳閾值思路:
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 }