BitmapGray.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Drawing;
  2. namespace HNWD.Pregrant.Common
  3. {
  4. public class BitmapGray
  5. {
  6. public static void ToGrey(Bitmap img1)
  7. {
  8. for (int i = 0; i < img1.Width; i++)
  9. {
  10. for (int j = 0; j < img1.Height; j++)
  11. {
  12. Color pixelColor = img1.GetPixel(i, j);
  13. //计算灰度值
  14. int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B);
  15. Color newColor = Color.FromArgb(grey, grey, grey);
  16. img1.SetPixel(i, j, newColor);
  17. }
  18. }
  19. }
  20. public static void Thresholding(Bitmap img1)
  21. {
  22. int[] histogram = new int[256];
  23. int minGrayValue = 255, maxGrayValue = 0;
  24. //求取直方图
  25. for (int i = 0; i < img1.Width; i++)
  26. {
  27. for (int j = 0; j < img1.Height; j++)
  28. {
  29. Color pixelColor = img1.GetPixel(i, j);
  30. histogram[pixelColor.R]++;
  31. if (pixelColor.R > maxGrayValue) maxGrayValue = pixelColor.R;
  32. if (pixelColor.R < minGrayValue) minGrayValue = pixelColor.R;
  33. }
  34. }
  35. //迭代计算阀值
  36. int threshold = -1;
  37. int newThreshold = (minGrayValue + maxGrayValue) / 2;
  38. for (int iterationTimes = 0; threshold != newThreshold && iterationTimes < 255; iterationTimes++)
  39. {
  40. threshold = newThreshold;
  41. int lP1 = 0;
  42. int lP2 = 0;
  43. int lS1 = 0;
  44. int lS2 = 0;
  45. //求两个区域的灰度的平均值
  46. for (int i = minGrayValue; i < threshold; i++)
  47. {
  48. lP1 += histogram[i] * i;
  49. lS1 += histogram[i];
  50. }
  51. int mean1GrayValue = (lP1 / lS1);
  52. for (int i = threshold + 1; i < maxGrayValue; i++)
  53. {
  54. lP2 += histogram[i] * i;
  55. lS2 += histogram[i];
  56. }
  57. int mean2GrayValue = 0;
  58. if (lS2 != 0)
  59. {
  60. mean2GrayValue = (lP2 / lS2);
  61. }
  62. newThreshold = (mean1GrayValue + mean2GrayValue) / 2;
  63. }
  64. //计算二值化
  65. for (int i = 0; i < img1.Width; i++)
  66. {
  67. for (int j = 0; j < img1.Height; j++)
  68. {
  69. Color pixelColor = img1.GetPixel(i, j);
  70. if (pixelColor.R > threshold) img1.SetPixel(i, j, Color.FromArgb(255, 255, 255));
  71. else img1.SetPixel(i, j, Color.FromArgb(0, 0, 0));
  72. }
  73. }
  74. }
  75. }
  76. }