gmc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is based on https://github.com/WWangYuHsiang/SMILEtrack/blob/main/BoT-SORT/tracker/gmc.py
  16. """
  17. import cv2
  18. import matplotlib.pyplot as plt
  19. import numpy as np
  20. import copy
  21. import time
  22. class GMC:
  23. def __init__(self, method='sparseOptFlow', downscale=2, verbose=None):
  24. super(GMC, self).__init__()
  25. self.method = method
  26. self.downscale = max(1, int(downscale))
  27. if self.method == 'orb':
  28. self.detector = cv2.FastFeatureDetector_create(20)
  29. self.extractor = cv2.ORB_create()
  30. self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
  31. elif self.method == 'sift':
  32. self.detector = cv2.SIFT_create(
  33. nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
  34. self.extractor = cv2.SIFT_create(
  35. nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
  36. self.matcher = cv2.BFMatcher(cv2.NORM_L2)
  37. elif self.method == 'ecc':
  38. number_of_iterations = 5000
  39. termination_eps = 1e-6
  40. self.warp_mode = cv2.MOTION_EUCLIDEAN
  41. self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
  42. number_of_iterations, termination_eps)
  43. elif self.method == 'sparseOptFlow':
  44. self.feature_params = dict(
  45. maxCorners=1000,
  46. qualityLevel=0.01,
  47. minDistance=1,
  48. blockSize=3,
  49. useHarrisDetector=False,
  50. k=0.04)
  51. # self.gmc_file = open('GMC_results.txt', 'w')
  52. elif self.method == 'file' or self.method == 'files':
  53. seqName = verbose[0]
  54. ablation = verbose[1]
  55. if ablation:
  56. filePath = r'tracker/GMC_files/MOT17_ablation'
  57. else:
  58. filePath = r'tracker/GMC_files/MOTChallenge'
  59. if '-FRCNN' in seqName:
  60. seqName = seqName[:-6]
  61. elif '-DPM' in seqName:
  62. seqName = seqName[:-4]
  63. elif '-SDP' in seqName:
  64. seqName = seqName[:-4]
  65. self.gmcFile = open(filePath + "/GMC-" + seqName + ".txt", 'r')
  66. if self.gmcFile is None:
  67. raise ValueError("Error: Unable to open GMC file in directory:"
  68. + filePath)
  69. elif self.method == 'none' or self.method == 'None':
  70. self.method = 'none'
  71. else:
  72. raise ValueError("Error: Unknown CMC method:" + method)
  73. self.prevFrame = None
  74. self.prevKeyPoints = None
  75. self.prevDescriptors = None
  76. self.initializedFirstFrame = False
  77. def apply(self, raw_frame, detections=None):
  78. if self.method == 'orb' or self.method == 'sift':
  79. return self.applyFeaures(raw_frame, detections)
  80. elif self.method == 'ecc':
  81. return self.applyEcc(raw_frame, detections)
  82. elif self.method == 'sparseOptFlow':
  83. return self.applySparseOptFlow(raw_frame, detections)
  84. elif self.method == 'file':
  85. return self.applyFile(raw_frame, detections)
  86. elif self.method == 'none':
  87. return np.eye(2, 3)
  88. else:
  89. return np.eye(2, 3)
  90. def applyEcc(self, raw_frame, detections=None):
  91. # Initialize
  92. height, width, _ = raw_frame.shape
  93. frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)
  94. H = np.eye(2, 3, dtype=np.float32)
  95. # Downscale image (TODO: consider using pyramids)
  96. if self.downscale > 1.0:
  97. frame = cv2.GaussianBlur(frame, (3, 3), 1.5)
  98. frame = cv2.resize(frame, (width // self.downscale,
  99. height // self.downscale))
  100. width = width // self.downscale
  101. height = height // self.downscale
  102. # Handle first frame
  103. if not self.initializedFirstFrame:
  104. # Initialize data
  105. self.prevFrame = frame.copy()
  106. # Initialization done
  107. self.initializedFirstFrame = True
  108. return H
  109. # Run the ECC algorithm. The results are stored in warp_matrix.
  110. # (cc, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria)
  111. try:
  112. (cc,
  113. H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode,
  114. self.criteria, None, 1)
  115. except:
  116. print('Warning: find transform failed. Set warp as identity')
  117. return H
  118. def applyFeaures(self, raw_frame, detections=None):
  119. # Initialize
  120. height, width, _ = raw_frame.shape
  121. frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)
  122. H = np.eye(2, 3)
  123. # Downscale image (TODO: consider using pyramids)
  124. if self.downscale > 1.0:
  125. # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)
  126. frame = cv2.resize(frame, (width // self.downscale,
  127. height // self.downscale))
  128. width = width // self.downscale
  129. height = height // self.downscale
  130. # find the keypoints
  131. mask = np.zeros_like(frame)
  132. # mask[int(0.05 * height): int(0.95 * height), int(0.05 * width): int(0.95 * width)] = 255
  133. mask[int(0.02 * height):int(0.98 * height), int(0.02 * width):int(
  134. 0.98 * width)] = 255
  135. if detections is not None:
  136. for det in detections:
  137. tlbr = (det[:4] / self.downscale).astype(np.int_)
  138. mask[tlbr[1]:tlbr[3], tlbr[0]:tlbr[2]] = 0
  139. keypoints = self.detector.detect(frame, mask)
  140. # compute the descriptors
  141. keypoints, descriptors = self.extractor.compute(frame, keypoints)
  142. # Handle first frame
  143. if not self.initializedFirstFrame:
  144. # Initialize data
  145. self.prevFrame = frame.copy()
  146. self.prevKeyPoints = copy.copy(keypoints)
  147. self.prevDescriptors = copy.copy(descriptors)
  148. # Initialization done
  149. self.initializedFirstFrame = True
  150. return H
  151. # Match descriptors.
  152. knnMatches = self.matcher.knnMatch(self.prevDescriptors, descriptors, 2)
  153. # Filtered matches based on smallest spatial distance
  154. matches = []
  155. spatialDistances = []
  156. maxSpatialDistance = 0.25 * np.array([width, height])
  157. # Handle empty matches case
  158. if len(knnMatches) == 0:
  159. # Store to next iteration
  160. self.prevFrame = frame.copy()
  161. self.prevKeyPoints = copy.copy(keypoints)
  162. self.prevDescriptors = copy.copy(descriptors)
  163. return H
  164. for m, n in knnMatches:
  165. if m.distance < 0.9 * n.distance:
  166. prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt
  167. currKeyPointLocation = keypoints[m.trainIdx].pt
  168. spatialDistance = (
  169. prevKeyPointLocation[0] - currKeyPointLocation[0],
  170. prevKeyPointLocation[1] - currKeyPointLocation[1])
  171. if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and \
  172. (np.abs(spatialDistance[1]) < maxSpatialDistance[1]):
  173. spatialDistances.append(spatialDistance)
  174. matches.append(m)
  175. meanSpatialDistances = np.mean(spatialDistances, 0)
  176. stdSpatialDistances = np.std(spatialDistances, 0)
  177. inliesrs = (spatialDistances - meanSpatialDistances
  178. ) < 2.5 * stdSpatialDistances
  179. goodMatches = []
  180. prevPoints = []
  181. currPoints = []
  182. for i in range(len(matches)):
  183. if inliesrs[i, 0] and inliesrs[i, 1]:
  184. goodMatches.append(matches[i])
  185. prevPoints.append(self.prevKeyPoints[matches[i].queryIdx].pt)
  186. currPoints.append(keypoints[matches[i].trainIdx].pt)
  187. prevPoints = np.array(prevPoints)
  188. currPoints = np.array(currPoints)
  189. # Draw the keypoint matches on the output image
  190. if 0:
  191. matches_img = np.hstack((self.prevFrame, frame))
  192. matches_img = cv2.cvtColor(matches_img, cv2.COLOR_GRAY2BGR)
  193. W = np.size(self.prevFrame, 1)
  194. for m in goodMatches:
  195. prev_pt = np.array(
  196. self.prevKeyPoints[m.queryIdx].pt, dtype=np.int_)
  197. curr_pt = np.array(keypoints[m.trainIdx].pt, dtype=np.int_)
  198. curr_pt[0] += W
  199. color = np.random.randint(0, 255, (3, ))
  200. color = (int(color[0]), int(color[1]), int(color[2]))
  201. matches_img = cv2.line(matches_img, prev_pt, curr_pt,
  202. tuple(color), 1, cv2.LINE_AA)
  203. matches_img = cv2.circle(matches_img, prev_pt, 2,
  204. tuple(color), -1)
  205. matches_img = cv2.circle(matches_img, curr_pt, 2,
  206. tuple(color), -1)
  207. plt.figure()
  208. plt.imshow(matches_img)
  209. plt.show()
  210. # Find rigid matrix
  211. if (np.size(prevPoints, 0) > 4) and (
  212. np.size(prevPoints, 0) == np.size(prevPoints, 0)):
  213. H, inliesrs = cv2.estimateAffinePartial2D(prevPoints, currPoints,
  214. cv2.RANSAC)
  215. # Handle downscale
  216. if self.downscale > 1.0:
  217. H[0, 2] *= self.downscale
  218. H[1, 2] *= self.downscale
  219. else:
  220. print('Warning: not enough matching points')
  221. # Store to next iteration
  222. self.prevFrame = frame.copy()
  223. self.prevKeyPoints = copy.copy(keypoints)
  224. self.prevDescriptors = copy.copy(descriptors)
  225. return H
  226. def applySparseOptFlow(self, raw_frame, detections=None):
  227. t0 = time.time()
  228. # Initialize
  229. height, width, _ = raw_frame.shape
  230. frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)
  231. H = np.eye(2, 3)
  232. # Downscale image
  233. if self.downscale > 1.0:
  234. # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)
  235. frame = cv2.resize(frame, (width // self.downscale,
  236. height // self.downscale))
  237. # find the keypoints
  238. keypoints = cv2.goodFeaturesToTrack(
  239. frame, mask=None, **self.feature_params)
  240. # Handle first frame
  241. if not self.initializedFirstFrame:
  242. # Initialize data
  243. self.prevFrame = frame.copy()
  244. self.prevKeyPoints = copy.copy(keypoints)
  245. # Initialization done
  246. self.initializedFirstFrame = True
  247. return H
  248. if self.prevFrame.shape != frame.shape:
  249. self.prevFrame = frame.copy()
  250. self.prevKeyPoints = copy.copy(keypoints)
  251. return H
  252. # find correspondences
  253. matchedKeypoints, status, err = cv2.calcOpticalFlowPyrLK(
  254. self.prevFrame, frame, self.prevKeyPoints, None)
  255. # leave good correspondences only
  256. prevPoints = []
  257. currPoints = []
  258. for i in range(len(status)):
  259. if status[i]:
  260. prevPoints.append(self.prevKeyPoints[i])
  261. currPoints.append(matchedKeypoints[i])
  262. prevPoints = np.array(prevPoints)
  263. currPoints = np.array(currPoints)
  264. # Find rigid matrix
  265. if (np.size(prevPoints, 0) > 4) and (
  266. np.size(prevPoints, 0) == np.size(prevPoints, 0)):
  267. H, inliesrs = cv2.estimateAffinePartial2D(prevPoints, currPoints,
  268. cv2.RANSAC)
  269. # Handle downscale
  270. if self.downscale > 1.0:
  271. H[0, 2] *= self.downscale
  272. H[1, 2] *= self.downscale
  273. else:
  274. print('Warning: not enough matching points')
  275. # Store to next iteration
  276. self.prevFrame = frame.copy()
  277. self.prevKeyPoints = copy.copy(keypoints)
  278. t1 = time.time()
  279. # gmc_line = str(1000 * (t1 - t0)) + "\t" + str(H[0, 0]) + "\t" + str(H[0, 1]) + "\t" + str(
  280. # H[0, 2]) + "\t" + str(H[1, 0]) + "\t" + str(H[1, 1]) + "\t" + str(H[1, 2]) + "\n"
  281. # self.gmc_file.write(gmc_line)
  282. return H
  283. def applyFile(self, raw_frame, detections=None):
  284. line = self.gmcFile.readline()
  285. tokens = line.split("\t")
  286. H = np.eye(2, 3, dtype=np.float_)
  287. H[0, 0] = float(tokens[1])
  288. H[0, 1] = float(tokens[2])
  289. H[0, 2] = float(tokens[3])
  290. H[1, 0] = float(tokens[4])
  291. H[1, 1] = float(tokens[5])
  292. H[1, 2] = float(tokens[6])
  293. return H