cmarkers.py 5.9 KB

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