Advertisement
Guest User

Untitled

a guest
Nov 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.52 KB | None | 0 0
  1. public static List<Point> Find(Bitmap bigBmp, Bitmap smallbmp, int tolerance)
  2. {
  3. List<Point> res = new List<Point>();
  4. BitmapData smallData = smallbmp.LockBits(new Rectangle(0, 0, smallbmp.Width, smallbmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  5. BitmapData bigData = bigBmp.LockBits(new Rectangle(0, 0, bigBmp.Width, bigBmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  6.  
  7. int smallStride = smallData.Stride;
  8. int bigStride = bigData.Stride;
  9.  
  10. int bigWidth = bigBmp.Width;
  11. int bigHeight = bigBmp.Height - smallbmp.Height + 1;
  12. int smallWidth = smallbmp.Width * 3;
  13. int smallHeight = smallbmp.Height;
  14.  
  15. Point location = new Point();
  16. int margin = tolerance;
  17. unsafe
  18. {
  19. byte* pSmall = (byte*)(void*)smallData.Scan0;
  20. byte* pBig = (byte*)(void*)bigData.Scan0;
  21.  
  22. int smallOffset = smallStride - smallbmp.Width * 3;
  23. int bigOffset = bigStride - bigBmp.Width * 3;
  24.  
  25. bool matchFound = true;
  26.  
  27. for (int y = 0; y < bigHeight; y++)
  28. {
  29. for (int x = 0; x < bigWidth; x++)
  30. {
  31. byte* pBigBackup = pBig;
  32. byte* pSmallBackup = pSmall;
  33.  
  34. //Look for the small picture.
  35. for (int i = 0; i < smallHeight; i++)
  36. {
  37. int j = 0;
  38. matchFound = true;
  39. for (j = 0; j < smallWidth; j++)
  40. {
  41. //With tolerance: pSmall value should be between margins.
  42. int inf = pBig[0] - margin;
  43. int sup = pBig[0] + margin;
  44. if (sup < pSmall[0] || inf > pSmall[0])
  45. {
  46. matchFound = false;
  47. break;
  48. }
  49.  
  50. pBig++;
  51. pSmall++;
  52. }
  53.  
  54. if (!matchFound) break;
  55.  
  56. //We restore the pointers.
  57. pSmall = pSmallBackup;
  58. pBig = pBigBackup;
  59.  
  60. //Next rows of the small and big pictures.
  61. pSmall += smallStride * (1 + i);
  62. pBig += bigStride * (1 + i);
  63. }
  64.  
  65. //If match found, we return.
  66. if (matchFound)
  67. {
  68. location.X = x;
  69. location.Y = y;
  70. res.Add(location);
  71. }
  72. //If no match found, we restore the pointers and continue.
  73. pBig = pBigBackup;
  74. pSmall = pSmallBackup;
  75. pBig += 3;
  76. }
  77. if (matchFound) break;
  78. pBig += bigOffset;
  79. }
  80. bigBmp.UnlockBits(bigData);
  81. smallbmp.UnlockBits(smallData);
  82. return res;
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement