cmarkers.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import cv2
  2. import numpy as np
  3. import math
  4. def getCMarkers (img):
  5. e1 = cv2.getTickCount()
  6. markers = []
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8. img3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
  9. #cv2.imshow("m3", img3)
  10. print("threshold", (cv2.getTickCount() - e1)/ cv2.getTickFrequency())
  11. kernel = np.ones((6,6),np.uint8)
  12. img2 = cv2.morphologyEx(img3, cv2.MORPH_CLOSE, kernel)
  13. print("close", (cv2.getTickCount() - e1)/ cv2.getTickFrequency())
  14. # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
  15. # img2 = cv2.dilate(img2,kernel,iterations = 2)
  16. kernel = np.ones((3,3),np.uint8)
  17. img2 = cv2.dilate(img2,kernel, 2)
  18. print("dilate", (cv2.getTickCount() - e1)/ cv2.getTickFrequency())
  19. # Setup SimpleBlobDetector parameters.
  20. params = cv2.SimpleBlobDetector_Params()
  21. params.filterByInertia = False
  22. params.filterByConvexity = False
  23. # # Change thresholds
  24. # params.minThreshold = 240
  25. # params.maxThreshold = 255
  26. # params.thresholdStep = 1
  27. # Filter by Area.
  28. params.filterByArea = True
  29. params.minArea = 10
  30. params.minDistBetweenBlobs = 1
  31. # Filter by Circularity
  32. params.filterByCircularity = True
  33. params.minCircularity = 0.2
  34. # # Filter by Convexity
  35. # params.filterByConvexity = True
  36. # params.minConvexity = 0.90
  37. # Filter by Inertia
  38. params.filterByInertia = True
  39. params.minInertiaRatio = 0.2
  40. params.filterByColor = False
  41. # Create a detector with the parameters
  42. detector = cv2.SimpleBlobDetector_create(params)
  43. # Detect blobs.
  44. keypoints = detector.detect(img2)
  45. print("blob", (cv2.getTickCount() - e1)/ cv2.getTickFrequency())
  46. # Draw detected blobs as red circles.
  47. # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures
  48. # the size of the circle corresponds to the size of blob
  49. k = []
  50. kk = []
  51. #print(len(keypoints))
  52. for point in keypoints:
  53. count = []
  54. for p in keypoints:
  55. if p == point:
  56. continue
  57. elif (p.pt[0]-point.pt[0])**2+(p.pt[1]-point.pt[1])**2 <= (point.size*4.5)**2 and (abs(point.size/p.size-1) <= 0.3):
  58. count.append(p.pt)
  59. if len(count) >= 2:
  60. k.append((point.pt, count))
  61. kk.append(point)
  62. print("near", (cv2.getTickCount() - e1)/ cv2.getTickFrequency())
  63. for point in k:
  64. p, near = point
  65. # distance open the angre and 90 degree
  66. midistance = math.pi/10.0
  67. bottom = []
  68. rigth = []
  69. for p1 in near:
  70. for p2 in near:
  71. if p1 == p2:
  72. continue
  73. u = np.array([p1[0]-p[0], p1[1]-p[1]])
  74. v = np.array([p2[0]-p[0], p2[1]-p[1]])
  75. angle = np.math.atan2(np.linalg.det([u,v]),np.dot(u,v))
  76. if abs(angle-math.pi/2.0) < math.pi/10.0:
  77. bottom = p1
  78. rigth = p2
  79. conner = rigth+u
  80. addu = u/6.0
  81. addv = v/6.0
  82. conners = [p-addu-addv, bottom+addu-addv, rigth-addu+addv, conner+addu+addv]
  83. trans = get_transform_matrix_points(conners, [10, 10], 10)
  84. code = cv2.warpPerspective(gray, trans, dsize=(100, 100))
  85. number = getNumber(code, 130)
  86. if number == False:
  87. continue
  88. #cv2.imshow("m2", code)
  89. uu = np.array([0, 1])
  90. angle = np.math.atan2(np.linalg.det([v,uu]),np.dot(v,uu))
  91. mid = p+u*0.5+v*0.5
  92. if number != 0:
  93. markers.append([number, mid, angle])
  94. #img2 = cv2.drawKeypoints(img2, kk, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
  95. #cv2.imshow("m3", img2)
  96. return markers
  97. def getNumber(img, threshold):
  98. vsplit = np.vsplit(img, 4)
  99. mean = []
  100. for vs in vsplit:
  101. m = []
  102. hsplit = np.hsplit(vs, 4)
  103. for hs in hsplit:
  104. m.append(np.mean(hs))
  105. mean.append(m)
  106. #print(np.array(mean).astype(np.uint8))
  107. #print(mean)
  108. mean = np.array(mean) >= threshold
  109. valid = mean[0, 0] == False
  110. valid = valid and mean[0, 3] == False
  111. valid = valid and mean[0, 3] == False
  112. valid = valid and mean[1, 0] == True
  113. valid = valid and mean[0, 1] == True
  114. valid = valid and mean[2, 0] == True
  115. valid = valid and mean[0, 2] == True
  116. valid = valid and mean[3, 3] == True
  117. valid = valid and mean[1, 3] == True
  118. valid = valid and mean[3, 1] == True
  119. valid = valid and mean[2, 3] == True
  120. valid = valid and mean[3, 2] == True
  121. if valid == False:
  122. return False
  123. number = 0
  124. if not mean[1, 1]:
  125. number += 1
  126. if not mean[1, 2]:
  127. number += 2
  128. if not mean[2, 1]:
  129. number += 4
  130. if not mean[2, 2]:
  131. number += 8
  132. return number
  133. def get_transform_matrix_points(corners, board_size, dpi):
  134. # Read a frame from the video device
  135. # Close the calibration window:
  136. # cv2.destroyWindow("Calibrate")
  137. # If the user selected 4 points
  138. if (len(corners) == 4):
  139. # Do calibration
  140. # src is a list of 4 points on the original image selected by the user
  141. # in the order [TOP_LEFT, BOTTOM_LEFT, TOP_RIGHT, BOTTOM_RIGHT]
  142. src = np.array(corners, np.float32)
  143. # dest is a list of where these 4 points should be located on the
  144. # rectangular board (in the same order):
  145. dest = np.array( [ (0, 0), (0, board_size[1]*dpi), (board_size[0]*dpi, 0), (board_size[0]*dpi, board_size[1]*dpi) ], np.float32)
  146. # Calculate the perspective transform matrix
  147. trans = cv2.getPerspectiveTransform(src, dest)
  148. # If we were given a calibration filename, save this matrix to a file
  149. return trans
  150. else:
  151. return None