標籤:static nes new 背景 遍曆 灰階 min 迭代 計算
二值化基本概念:通俗的講就是把一副彩色影像處理成一副黑白映像,一般是作為後續複雜影像處理操作的預先處理。
二值化演算法思路:遍曆映像的所有像素點,計算每個像素點的灰階值。通過迭代法收斂得到一個最佳閾值,灰階值大於最佳閾值的像素點設為白色,灰階值小於最佳閾值的像素點設為黑色。(我這裡的二值化處理結果是,背景是白色,前景是黑色)
迭代法擷取最佳閾值思路:
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和最小灰階值zmin12 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和fp40 {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 }
映像二值化處理Java