Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. from matplotlib import pyplot as plt
  4.  
  5. img1 = cv2.imread('/home/alex/Downloads/snapshot (2).jpg',0) #queryimage # left image
  6. img2 = cv2.imread('/home/alex/Downloads/snapshot (1).jpg',0) #trainimage # right image
  7.  
  8. sift = cv2.xfeatures2d.SIFT_create()
  9.  
  10. # find the keypoints and descriptors with SIFT
  11. kp1, des1 = sift.detectAndCompute(img1,None)
  12. kp2, des2 = sift.detectAndCompute(img2,None)
  13.  
  14. # FLANN parameters
  15. FLANN_INDEX_KDTREE = 0
  16. index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
  17. search_params = dict(checks=50)
  18.  
  19. flann = cv2.FlannBasedMatcher(index_params,search_params)
  20. matches = flann.knnMatch(des1,des2,k=2)
  21.  
  22. good = []
  23. pts1 = []
  24. pts2 = []
  25.  
  26. # ratio test as per Lowe's paper
  27. for i,(m,n) in enumerate(matches):
  28. if m.distance < 0.8*n.distance:
  29. good.append(m)
  30. pts2.append(kp2[m.trainIdx].pt)
  31. pts1.append(kp1[m.queryIdx].pt)
  32.  
  33. pts1 = np.int32(pts1)
  34. pts2 = np.int32(pts2)
  35. F, mask = cv2.findFundamentalMat(pts1,pts2,cv2.FM_LMEDS)
  36.  
  37. # We select only inlier points
  38. pts1 = pts1[mask.ravel()==1]
  39. pts2 = pts2[mask.ravel()==1]
  40.  
  41. def drawlines(img1,img2,lines,pts1,pts2):
  42. ''' img1 - image on which we draw the epilines for the points in img2
  43. lines - corresponding epilines '''
  44. r,c = img1.shape
  45. img1 = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)
  46. img2 = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR)
  47. for r,pt1,pt2 in zip(lines,pts1,pts2):
  48. color = tuple(np.random.randint(0,255,3).tolist())
  49. x0,y0 = map(int, [0, -r[2]/r[1] ])
  50. x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ])
  51. img1 = cv2.line(img1, (x0,y0), (x1,y1), color,1)
  52. img1 = cv2.circle(img1,tuple(pt1),5,color,-1)
  53. img2 = cv2.circle(img2,tuple(pt2),5,color,-1)
  54. return img1,img2
  55.  
  56. print(F)
  57.  
  58. # Find epilines corresponding to points in right image (second image) and
  59. # drawing its lines on left image
  60. lines1 = cv2.computeCorrespondEpilines(pts2.reshape(-1,1,2), 2,F)
  61. lines1 = lines1.reshape(-1,3)
  62. img5,img6 = drawlines(img1,img2,lines1,pts1,pts2)
  63.  
  64. # Find epilines corresponding to points in left image (first image) and
  65. # drawing its lines on right image
  66. lines2 = cv2.computeCorrespondEpilines(pts1.reshape(-1,1,2), 1,F)
  67. lines2 = lines2.reshape(-1,3)
  68. img3,img4 = drawlines(img2,img1,lines2,pts2,pts1)
  69.  
  70. print(img1.shape == img2.shape)
  71.  
  72. cv2.imshow('combined', np.hstack([img5, img3]))
  73. cv2.waitKey(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement