1. 程式人生 > >Win8 Metro(C#)數字圖像處理--2.56簡單統計法圖像二值化

Win8 Metro(C#)數字圖像處理--2.56簡單統計法圖像二值化

public 分割 ola 0.11 orm http statistic weight segment

原文:Win8 Metro(C#)數字圖像處理--2.56簡單統計法圖像二值化



[函數名稱]

簡單統計法圖像二值化 WriteableBitmap StatisticalThSegment(WriteableBitmap src)

技術分享圖片

      /// <summary>
        /// Statistical method of image segmention.
        /// </summary>
        /// <param name="src">The source image.</param>
        /// <returns></returns>
        public static WriteableBitmap StatisticalThSegment(WriteableBitmap src) ////Ostu法閾值分割
        {
            if (src != null)
            {
                int w = src.PixelWidth;
                int h = src.PixelHeight;
                WriteableBitmap dstImage = new WriteableBitmap(w, h);
                byte[] temp = src.PixelBuffer.ToArray();
                byte[] tempMask = (byte[])temp.Clone();
                //定義灰度圖像信息存儲變量
                int[] srcData = new int[w * h];
                int eX = 0;
                int eY = 0;
                int sumEF = 0;
                int sumE = 0;
                int eMax = 0;
                //定義閾值變量
                int Th = 0;
                for (int j = 0; j < h; j++)
                {
                    for (int i = 0; i < w; i++)
                    {
                        srcData[i + j * w] = (int)((double)tempMask[i * 4 + j * w * 4] * 0.114 + (double)tempMask[i * 4 + 1 + j * w * 4] * 0.587 + (double)tempMask[i * 4 + 2 + j * w * 4] * 0.299);
                    }
                }
                for (int j = 1; j < h - 1; j++)
                {
                    for (int i = 1; i < w - 1; i++)
                    {
                        eX = srcData[i - 1 + j * w] - srcData[i + 1 + j * w];
                        eY = srcData[i + (j - 1) * w] - srcData[i + (j + 1) * w];
                        eMax = Math.Max(eX, eY);
                        sumE += eMax;
                        sumEF += eMax * srcData[i + j * w];
                    }
                }
                Th = (int)(sumEF / sumE);
                for (int j = 0; j < h; j++)
                {
                    for (int i = 0; i < w; i++)
                    {
                        temp[i * 4 + j * w * 4] = temp[i * 4 + 1 + j * w * 4] = temp[i * 4 + 2 + j * w * 4] = (byte)(srcData[i + j * w] < Th ? 0 : 255);
                    }
                }
                Stream sTemp = dstImage.PixelBuffer.AsStream();
                sTemp.Seek(0, SeekOrigin.Begin);
                sTemp.Write(temp, 0, w * 4 * h);
                return dstImage;
            }
            else
            {
                return null;
            }
        }
技術分享圖片

Win8 Metro(C#)數字圖像處理--2.56簡單統計法圖像二值化