1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using System.Drawing;
- namespace HNWD.Pregrant.Common
- {
- public class BitmapGray
- {
- public static void ToGrey(Bitmap img1)
- {
- for (int i = 0; i < img1.Width; i++)
- {
- for (int j = 0; j < img1.Height; j++)
- {
- Color pixelColor = img1.GetPixel(i, j);
- //计算灰度值
- int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B);
- Color newColor = Color.FromArgb(grey, grey, grey);
- img1.SetPixel(i, j, newColor);
- }
- }
- }
- public static void Thresholding(Bitmap img1)
- {
- int[] histogram = new int[256];
- int minGrayValue = 255, maxGrayValue = 0;
- //求取直方图
- for (int i = 0; i < img1.Width; i++)
- {
- for (int j = 0; j < img1.Height; j++)
- {
- Color pixelColor = img1.GetPixel(i, j);
- histogram[pixelColor.R]++;
- if (pixelColor.R > maxGrayValue) maxGrayValue = pixelColor.R;
- if (pixelColor.R < minGrayValue) minGrayValue = pixelColor.R;
- }
- }
- //迭代计算阀值
- int threshold = -1;
- int newThreshold = (minGrayValue + maxGrayValue) / 2;
- for (int iterationTimes = 0; threshold != newThreshold && iterationTimes < 255; iterationTimes++)
- {
- threshold = newThreshold;
- int lP1 = 0;
- int lP2 = 0;
- int lS1 = 0;
- int lS2 = 0;
- //求两个区域的灰度的平均值
- for (int i = minGrayValue; i < threshold; i++)
- {
- lP1 += histogram[i] * i;
- lS1 += histogram[i];
- }
- int mean1GrayValue = (lP1 / lS1);
- for (int i = threshold + 1; i < maxGrayValue; i++)
- {
- lP2 += histogram[i] * i;
- lS2 += histogram[i];
- }
- int mean2GrayValue = 0;
- if (lS2 != 0)
- {
- mean2GrayValue = (lP2 / lS2);
- }
- newThreshold = (mean1GrayValue + mean2GrayValue) / 2;
- }
- //计算二值化
- for (int i = 0; i < img1.Width; i++)
- {
- for (int j = 0; j < img1.Height; j++)
- {
- Color pixelColor = img1.GetPixel(i, j);
- if (pixelColor.R > threshold) img1.SetPixel(i, j, Color.FromArgb(255, 255, 255));
- else img1.SetPixel(i, j, Color.FromArgb(0, 0, 0));
- }
- }
- }
- }
- }
|