PDComparer.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System;
  2. using System.Drawing;
  3. using System.Collections;
  4. namespace DrawingTestHelper
  5. {
  6. /// <summary>
  7. /// Summary description for PDComparer.
  8. /// </summary>
  9. public class PDComparer
  10. {
  11. static int SearchRectSize = 10;
  12. static double [,] ltDistances = new double[SearchRectSize,SearchRectSize];
  13. static PDComparer()
  14. {
  15. for (int x = 0; x < SearchRectSize; x++)
  16. for (int y = 0; y < SearchRectSize; y++)
  17. {
  18. ltDistances[x,y] = Math.Sqrt(x*x + y*y);
  19. }
  20. }
  21. public PDComparer()
  22. {
  23. }
  24. public static double Compare(Bitmap b1, Bitmap b2)
  25. {
  26. Point [] shapePoints = GetPointFromImage(b1);
  27. double [] pointsDistance = new double[ shapePoints.Length ];
  28. for (int i = 0; i < shapePoints.Length; i++)
  29. {
  30. pointsDistance[i] = DistanceToClosestPoint( shapePoints[i], b2 );
  31. }
  32. return Max( pointsDistance );
  33. }
  34. private static double DistanceToClosestPoint(Point p, Bitmap b)
  35. {
  36. if (IsPixelExist( b.GetPixel(p.X, p.Y) ))
  37. return 0;
  38. Rectangle r = new Rectangle(
  39. p.X - SearchRectSize / 2,
  40. p.Y - SearchRectSize / 2,
  41. SearchRectSize,
  42. SearchRectSize);
  43. double min_distance = SearchRectSize;
  44. for (int x = r.X; x < r.X + SearchRectSize; x++)
  45. for (int y = r.Y; y < r.Y + SearchRectSize; y++)
  46. if ((x < b.Width) && (y < b.Height) && (x >= 0) && (y >= 0))
  47. {
  48. if ( IsPixelExist( b.GetPixel(x, y) ) )
  49. {
  50. double d = CalculateDistance(p.X, p.Y, x, y);
  51. if (d < min_distance)
  52. min_distance = d;
  53. }
  54. }
  55. return min_distance;
  56. }
  57. private static double CalculateDistance(Point a, Point b)
  58. {
  59. return CalculateDistance(a.X, a.Y, b.X, b.Y);
  60. }
  61. private static double CalculateDistance(int x1, int y1, int x2, int y2)
  62. {
  63. int delta_x = Math.Abs(x2 - x1);
  64. int delta_y = Math.Abs(y2 - y1);
  65. return ltDistances[delta_x, delta_y];
  66. }
  67. private static double Max(double [] a)
  68. {
  69. double max = 0;
  70. for (int i = 0; i < a.Length; i++)
  71. if (a[i] > max)
  72. max = a[i];
  73. return max;
  74. }
  75. private static Point [] GetPointFromImage(Bitmap b)
  76. {
  77. ArrayList points = new ArrayList();
  78. for(int x = 0; x < b.Width; x++)
  79. for(int y = 0; y < b.Height; y++)
  80. if (IsPixelExist ( b.GetPixel(x, y) ))
  81. points.Add( new Point(x, y) );
  82. return (Point [])points.ToArray( typeof(Point) );
  83. }
  84. private static bool IsPixelExist(Color c)
  85. {
  86. return c.A > 0;
  87. }
  88. }
  89. }