Guest User

Untitled

a guest
Jul 13th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4.  
  5. def find_segment(db_img, querry_img, threshold=100, return_area=False):
  6. grayscale_db = cv2.cvtColor(db_img, cv2.COLOR_BGR2GRAY)
  7. gray_scale_querry = cv2.cvtColor(querry_img, cv2.COLOR_BGR2GRAY)
  8. # Initiate SIFT detector
  9. sift = cv2.xfeatures2d.SIFT_create()
  10. kp1, des1 = sift.detectAndCompute(grayscale_db, None)
  11. kp2, des2 = sift.detectAndCompute(gray_scale_querry, None)
  12.  
  13. FLANN_INDEX_KDTREE = 0
  14. index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
  15. search_params = dict(checks=50)
  16.  
  17. flann = cv2.FlannBasedMatcher(index_params, search_params)
  18.  
  19. matches = flann.knnMatch(des1, des2, k=2)
  20. good = [m for m, n in matches if m.distance < 0.7 * n.distance]
  21. result_area = None
  22. h, w = grayscale_db.shape
  23. if len(good) > threshold:
  24. dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
  25. if return_area:
  26. return cv2.minAreaRect(dst_pts)
  27.  
  28. src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
  29.  
  30. M, mask = cv2.findHomography(dst_pts, src_pts, cv2.RANSAC, 5.0)
  31. result_area = cv2.warpPerspective(querry_img, M, (w, h), borderMode=cv2.BORDER_CONSTANT,
  32. borderValue=(255, 255, 255), flags=cv2.INTER_LINEAR)
  33.  
  34. # `c
  35. # else:
  36. # print("Not enough matches are found - %d/%d" % (len(good), threshold))
  37. return result_area
  38.  
  39.  
  40. querry = cv2.imread("E:/querry.jpg")
  41. db = cv2.imread("E:/db_img.jpg")
  42. segment = find_segment(db, querry)
  43. diff = cv2.absdiff(db, segment)
  44. cv2.imwrite("E:/diff.jpg", diff)
Add Comment
Please, Sign In to add comment