SHARE
TWEET

l5

a guest Dec 16th, 2018 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import cv2
  2. import numpy as np
  3. from matplotlib import pyplot as plt
  4.  
  5.  
  6. # template (pattern) matching
  7. img = cv2.imread('test.jpg', 1)
  8. temp = cv2.imread('template.jpg', 1)
  9.  
  10. w = temp.shape[1]
  11. h = temp.shape[0]
  12.  
  13. # check docs for rest of template matching methods
  14. method = cv2.TM_CCORR_NORMED
  15.  
  16. res = cv2.matchTemplate(img, temp, method)
  17. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
  18.  
  19. # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
  20. if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
  21.     top_left = min_loc
  22. else:
  23.     top_left = max_loc
  24. bottom_right = (top_left[0] + w, top_left[1] + h)
  25.  
  26. cv2.rectangle(img,top_left, bottom_right, (0, 0, 255), 2)
  27.  
  28. cv2.imshow('res', img)
  29. cv2.imshow('template', temp)
  30. cv2.waitKey()
  31.  
  32.  
  33.  
  34. # contour matching
  35. img = cv2.imread('bottles.jpg', 0)
  36. temp = cv2.imread('bottle.jpg', 0)
  37.  
  38. kernel = np.ones((5,5), np.uint8)
  39.  
  40. val, img_thresh = cv2.threshold(img, 130, 255, cv2.THRESH_BINARY_INV)
  41. val, temp_thresh = cv2.threshold(temp, 130, 255, cv2.THRESH_BINARY_INV)
  42.  
  43. _, img_contours, _ = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  44. _, temp_contours, _ = cv2.findContours(temp_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  45.  
  46. temp_contours.sort(key=lambda c:cv2.contourArea(c), reverse=True)
  47. temp_contour = temp_contours[0]
  48.  
  49. best_contour = None
  50. best_result = float('inf')
  51.  
  52. for ic in img_contours:
  53.     d = cv2.matchShapes(ic, temp_contour, cv2.CONTOURS_MATCH_I1, 0)
  54.     if d < best_result:
  55.         best_result = d
  56.         best_contour = ic
  57.  
  58. cv2.drawContours(img, best_contour, -1, (0, 255, 0), 3)
  59. cv2.drawContours(temp, temp_contours[0], -1, (0, 255, 0), 3)
  60.  
  61.  
  62. # print image
  63. cv2.imshow('img', img)
  64. cv2.imshow('temp', temp)
  65.  
  66. cv2.waitKey()
  67.  
  68.  
  69.  
  70. # Feature matching
  71.  
  72. MIN_MATCH_COUNT = 10
  73.  
  74. img1 = cv2.imread('box.png',0)          # queryImage
  75. img2 = cv2.imread('box_in_scene.png',0) # trainImage
  76.  
  77.  
  78. # Initiate SIFT detector
  79. sift = cv2.ORB_create()
  80.  
  81. # find the keypoints and descriptors with SIFT
  82. kp1, des1 = sift.detectAndCompute(img1,None)
  83. kp2, des2 = sift.detectAndCompute(img2,None)
  84.  
  85.  
  86. FLANN_INDEX_KDTREE = 1
  87. index_params = dict(algorithm = 6, trees = 5)
  88.  
  89. search_params = dict(checks = 50)
  90.  
  91. flann = cv2.FlannBasedMatcher(index_params, search_params)
  92.  
  93. matches = flann.knnMatch(des1, des2, k=2)
  94.  
  95.  
  96. # store all the good matches as per Lowe's ratio test.
  97. good = []
  98.  
  99. for l in matches:
  100.     if (len(l) < 2):
  101.         continue
  102.     m = l[0]
  103.     n = l[1]
  104.  
  105.     if m.distance/n.distance < 0.7:
  106.         good.append(m)
  107.  
  108.  
  109. if len(good) > MIN_MATCH_COUNT:
  110.     src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  111.     dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  112.  
  113.     M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
  114.     matchesMask = mask.ravel().tolist()
  115.  
  116.     h, w = img1.shape
  117.     pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
  118.     dst = cv2.perspectiveTransform(pts, M)
  119.  
  120.     img2 = cv2.polylines(img2, [np.int32(dst)], True, 0, 3, cv2.LINE_AA)
  121.  
  122.  
  123. else:
  124.     matchesMask = None
  125.     print ('Not enough matches are found')
  126.  
  127.  
  128. draw_params = dict(matchColor=(0, 255, 0),  # draw matches in green color
  129.                    matchesMask=matchesMask,  # draw only inliers
  130.                    flags=2)
  131.  
  132. img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **draw_params)
  133.  
  134. plt.imshow(img3, 'gray'), plt.show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top