fourier_descriptors_demo.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import numpy as np
  2. import cv2 as cv
  3. import math
  4. class ThParameters:
  5. def __init__(self):
  6. self.levelNoise=6
  7. self.angle=45
  8. self.scale10=5
  9. self.origin=10
  10. self.xg=150
  11. self.yg=150
  12. self.update=True
  13. def UpdateShape(x ):
  14. p.update = True
  15. def union(a,b):
  16. x = min(a[0], b[0])
  17. y = min(a[1], b[1])
  18. w = max(a[0]+a[2], b[0]+b[2]) - x
  19. h = max(a[1]+a[3], b[1]+b[3]) - y
  20. return (x, y, w, h)
  21. def intersection(a,b):
  22. x = max(a[0], b[0])
  23. y = max(a[1], b[1])
  24. w = min(a[0]+a[2], b[0]+b[2]) - x
  25. h = min(a[1]+a[3], b[1]+b[3]) - y
  26. if w<0 or h<0: return () # or (0,0,0,0) ?
  27. return (x, y, w, h)
  28. def NoisyPolygon(pRef,n):
  29. # vector<Point> c
  30. p = pRef;
  31. # vector<vector<Point> > contour;
  32. p = p+n*np.random.random_sample((p.shape[0],p.shape[1]))-n/2.0
  33. if (n==0):
  34. return p
  35. c = np.empty(shape=[0, 2])
  36. minX = p[0][0]
  37. maxX = p[0][0]
  38. minY = p[0][1]
  39. maxY = p[0][1]
  40. for i in range( 0,p.shape[0]):
  41. next = i + 1;
  42. if (next == p.shape[0]):
  43. next = 0;
  44. u = p[next] - p[i]
  45. d = int(cv.norm(u))
  46. a = np.arctan2(u[1], u[0])
  47. step = 1
  48. if (n != 0):
  49. step = d // n
  50. for j in range( 1,int(d),int(max(step, 1))):
  51. while True:
  52. pAct = (u*j) / (d)
  53. r = n*np.random.random_sample()
  54. theta = a + 2*math.pi*np.random.random_sample()
  55. # pNew = Point(Point2d(r*cos(theta) + pAct.x + p[i].x, r*sin(theta) + pAct.y + p[i].y));
  56. pNew = np.array([(r*np.cos(theta) + pAct[0] + p[i][0], r*np.sin(theta) + pAct[1] + p[i][1])])
  57. if (pNew[0][0]>=0 and pNew[0][1]>=0):
  58. break
  59. if (pNew[0][0]<minX):
  60. minX = pNew[0][0]
  61. if (pNew[0][0]>maxX):
  62. maxX = pNew[0][0]
  63. if (pNew[0][1]<minY):
  64. minY = pNew[0][1]
  65. if (pNew[0][1]>maxY):
  66. maxY = pNew[0][1]
  67. c = np.append(c,pNew,axis = 0)
  68. return c
  69. #static vector<Point> NoisyPolygon(vector<Point> pRef, double n);
  70. #static void UpdateShape(int , void *r);
  71. #static void AddSlider(String sliderName, String windowName, int minSlider, int maxSlider, int valDefault, int *valSlider, void(*f)(int, void *), void *r);
  72. def AddSlider(sliderName,windowName,minSlider,maxSlider,valDefault, update):
  73. cv.createTrackbar(sliderName, windowName, valDefault,maxSlider-minSlider+1, update)
  74. cv.setTrackbarMin(sliderName, windowName, minSlider)
  75. cv.setTrackbarMax(sliderName, windowName, maxSlider)
  76. cv.setTrackbarPos(sliderName, windowName, valDefault)
  77. # vector<Point> ctrRef;
  78. # vector<Point> ctrRotate, ctrNoisy, ctrNoisyRotate, ctrNoisyRotateShift;
  79. # // build a shape with 5 vertex
  80. ctrRef = np.array([(250,250),(400, 250),(400, 300),(250, 300),(180, 270)])
  81. cg = np.mean(ctrRef,axis=0)
  82. p=ThParameters()
  83. cv.namedWindow("FD Curve matching");
  84. # A rotation with center at (150,150) of angle 45 degrees and a scaling of 5/10
  85. AddSlider("Noise", "FD Curve matching", 0, 20, p.levelNoise, UpdateShape)
  86. AddSlider("Angle", "FD Curve matching", 0, 359, p.angle, UpdateShape)
  87. AddSlider("Scale", "FD Curve matching", 5, 100, p.scale10, UpdateShape)
  88. AddSlider("Origin", "FD Curve matching", 0, 100, p.origin, UpdateShape)
  89. AddSlider("Xg", "FD Curve matching", 150, 450, p.xg, UpdateShape)
  90. AddSlider("Yg", "FD Curve matching", 150, 450, p.yg, UpdateShape)
  91. code = 0
  92. img = np.zeros((300,512,3), np.uint8)
  93. print ("******************** PRESS g TO MATCH CURVES *************\n")
  94. while (code!=27):
  95. code = cv.waitKey(60)
  96. if p.update:
  97. p.levelNoise=cv.getTrackbarPos('Noise','FD Curve matching')
  98. p.angle=cv.getTrackbarPos('Angle','FD Curve matching')
  99. p.scale10=cv.getTrackbarPos('Scale','FD Curve matching')
  100. p.origin=cv.getTrackbarPos('Origin','FD Curve matching')
  101. p.xg=cv.getTrackbarPos('Xg','FD Curve matching')
  102. p.yg=cv.getTrackbarPos('Yg','FD Curve matching')
  103. r = cv.getRotationMatrix2D((p.xg, p.yg), angle=p.angle, scale=10.0/ p.scale10);
  104. ctrNoisy= NoisyPolygon(ctrRef,p.levelNoise)
  105. ctrNoisy1 = np.reshape(ctrNoisy,(ctrNoisy.shape[0],1,2))
  106. ctrNoisyRotate = cv.transform(ctrNoisy1,r)
  107. ctrNoisyRotateShift = np.empty([ctrNoisyRotate.shape[0],1,2],dtype=np.int32)
  108. for i in range(0,ctrNoisy.shape[0]):
  109. k=(i+(p.origin*ctrNoisy.shape[0])//100)% ctrNoisyRotate.shape[0]
  110. ctrNoisyRotateShift[i] = ctrNoisyRotate[k]
  111. # To draw contour using drawcontours
  112. cc= np.reshape(ctrNoisyRotateShift,[ctrNoisyRotateShift.shape[0],2])
  113. c = [ ctrRef,cc]
  114. p.update = False;
  115. rglobal =(0,0,0,0)
  116. for i in range(0,2):
  117. r = cv.boundingRect(c[i])
  118. rglobal = union(rglobal,r)
  119. r = list(rglobal)
  120. r[2] = r[2]+10
  121. r[3] = r[3]+10
  122. rglobal = tuple(r)
  123. img = np.zeros((2 * rglobal[3], 2 * rglobal[2], 3), np.uint8)
  124. cv.drawContours(img, c, 0, (255,0,0),1);
  125. cv.drawContours(img, c, 1, (0, 255, 0),1);
  126. cv.circle(img, tuple(c[0][0]), 5, (255, 0, 0),3);
  127. cv.circle(img, tuple(c[1][0]), 5, (0, 255, 0),3);
  128. cv.imshow("FD Curve matching", img);
  129. if code == ord('d') :
  130. cv.destroyWindow("FD Curve matching");
  131. cv.namedWindow("FD Curve matching");
  132. # A rotation with center at (150,150) of angle 45 degrees and a scaling of 5/10
  133. AddSlider("Noise", "FD Curve matching", 0, 20, p.levelNoise, UpdateShape)
  134. AddSlider("Angle", "FD Curve matching", 0, 359, p.angle, UpdateShape)
  135. AddSlider("Scale", "FD Curve matching", 5, 100, p.scale10, UpdateShape)
  136. AddSlider("Origin%%", "FD Curve matching", 0, 100, p.origin, UpdateShape)
  137. AddSlider("Xg", "FD Curve matching", 150, 450, p.xg, UpdateShape)
  138. AddSlider("Yg", "FD Curve matching", 150, 450, p.yg, UpdateShape)
  139. if code == ord('g'):
  140. fit = cv.ximgproc.createContourFitting(1024,16);
  141. # sampling contour we want 256 points
  142. cn= np.reshape(ctrRef,[ctrRef.shape[0],1,2])
  143. ctrRef2d = cv.ximgproc.contourSampling(cn, 256)
  144. ctrRot2d = cv.ximgproc.contourSampling(ctrNoisyRotateShift, 256)
  145. fit.setFDSize(16)
  146. c1 = ctrRef2d
  147. c2 = ctrRot2d
  148. alphaPhiST, dist = fit.estimateTransformation(ctrRot2d, ctrRef2d)
  149. print( "Transform *********\n Origin = ", 1-alphaPhiST[0,0] ," expected ", p.origin / 100. ,"\n")
  150. print( "Angle = ", alphaPhiST[0,1] * 180 / math.pi ," expected " , p.angle,"\n")
  151. print( "Scale = " ,alphaPhiST[0,2] ," expected " , p.scale10 / 10.0 , "\n")
  152. dst = cv.ximgproc.transformFD(ctrRot2d, alphaPhiST,cn, False);
  153. ctmp= np.reshape(dst,[dst.shape[0],2])
  154. cdst=ctmp.astype(int)
  155. c = [ ctrRef,cc,cdst]
  156. cv.drawContours(img, c, 2, (0,0,255),1);
  157. cv.circle(img, (int(c[2][0][0]),int(c[2][0][1])), 5, (0, 0, 255),5);
  158. cv.imshow("FD Curve matching", img);