Guest User

Untitled

a guest
Mar 5th, 2021
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.64 KB | None | 0 0
  1. # python -m pip install opencv-python
  2. import cv2 as cv
  3. # python -m pip install numpy==1.19.3
  4. import numpy as np
  5. # python -m pip install matplotlib
  6. from matplotlib import pyplot as plt
  7.  
  8. # We already have individual calibrations for each "camera" from Calib.py
  9. # The stereoCalibrate function should thus skip finding them
  10. stereoflags = cv.CALIB_FIX_INTRINSIC
  11. # To do this we need to import the previously found camera properties
  12. # Left
  13. retL = np.load('./calibParams/retL.npy', None, True)
  14. CmatrixL = np.load('./calibParams/CmatrixL.npy', None, True)
  15. distCoeffsL = np.load('./calibParams/distCoeffsL.npy', None, True)
  16. rvecsL = np.load('./calibParams/rvecsL.npy', None, True)
  17. tvecsL = np.load('./calibParams/tvecsL.npy', None, True)
  18. img_pointsL = np.load('./calibParams/img_pointsL.npy', None, True)
  19. # Right
  20. retR = np.load('./calibParams/retR.npy', None, True)
  21. CmatrixR = np.load('./calibParams/CmatrixR.npy', None, True)
  22. distCoeffsR = np.load('./calibParams/distCoeffsR.npy', None, True)
  23. rvecsR = np.load('./calibParams/rvecsR.npy', None, True)
  24. tvecsR = np.load('./calibParams/tvecsR.npy', None, True)
  25. img_pointsR = np.load('./calibParams/img_pointsR.npy', None, True)
  26. # Shared
  27. obj_points = np.load('./calibParams/obj_points.npy', None, True)
  28.  
  29. # Set the criteria
  30. criteria_stereo = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  31.  
  32. # Need an image to calculate the translation and rotation of the two cameras
  33. image = cv.imread('../IMAGES/calib3/IMGP1882.jpg')
  34. # Make sure it is grayscale
  35. image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
  36. Y, X = image.shape
  37. # Split the image
  38. imageL = image[0:int(Y), 0:int(X/2)-100]
  39. imageR = image[0:int(Y), int(X/2)+100:int(X)]
  40.  
  41. print(image.shape[::-1])
  42.  
  43. # Commented out to save runtime, parameters are saved and loaded in after the first run
  44. # Run the cv.stereoCalibrate function to find the Essential and Fundamental matrix
  45. # Note that ROTmatrix and TRANSmatrix are the position of the first (left) camera with respect to the second (right) camera coordinate system
  46. # retS, NMatrixL, distCoeffsL, NMatrixR, distCoeffsR, ROTmatrix, TRANSmatrix, Essmatrix, Fundmatrix = cv.stereoCalibrate(
  47. #     obj_points, img_pointsL, img_pointsR, CmatrixL, distCoeffsL, CmatrixR, distCoeffsR, image.shape[::-1], stereoflags, criteria_stereo)
  48.  
  49. # Show some output
  50. # print("Finished stereoCalibrate")
  51. # print(Essmatrix)
  52. # print(Fundmatrix)
  53.  
  54.  
  55. Fundmatrix = np.load('./epiParams/fundmatrix.npy')
  56. Essmatrix = np.load('./epiParams/essmatrix.npy')
  57. TRANSmatrix = np.load('./epiParams/transmatrix.npy')
  58. ROTmatrix = np.load('./epiParams/rotmatrix.npy')
  59. distCoeffsR = np.load('./epiParams/distR.npy')
  60. NMatrixR = np.load('./epiParams/nmatrixR.npy')
  61. distCoeffsL = np.load('./epiParams/distL.npy')
  62. NMatrixL = np.load('./epiParams/nmatrixL.npy')
  63.  
  64. # Save outputs, this script takes some time to run
  65. np.save('./epiParams/fundmatrix', Fundmatrix)
  66. np.save('./epiParams/essmatrix', Essmatrix)
  67. np.save('./epiParams/transmatrix', TRANSmatrix)
  68. np.save('./epiParams/rotmatrix', ROTmatrix)
  69. np.save('./epiParams/distR', distCoeffsR)
  70. np.save('./epiParams/nmatrixR', NMatrixR)
  71. np.save('./epiParams/distL', distCoeffsL)
  72. np.save('./epiParams/nmatrixL', NMatrixL)
  73. print("Saved params")
  74.  
  75.  
  76. # Another way of doing it: https://docs.opencv.org/master/da/de9/tutorial_py_epipolar_geometry.html
  77. # Point matching to create the fundamental matrix
  78. img1 = imageL  #queryimage # left image
  79. img2 = imageR #trainimage # right image
  80.  
  81. sift = cv.SIFT_create()
  82. # find the keypoints and descriptors with SIFT
  83. kp1, des1 = sift.detectAndCompute(img1,None)
  84. kp2, des2 = sift.detectAndCompute(img2,None)
  85. # FLANN parameters
  86. FLANN_INDEX_KDTREE = 1
  87. index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
  88. search_params = dict(checks=50)
  89. flann = cv.FlannBasedMatcher(index_params,search_params)
  90. matches = flann.knnMatch(des1,des2,k=2)
  91. matchesMask = [[0,0] for i in range(len(matches))]
  92. pts1 = []
  93. pts2 = []
  94. # ratio test as per Lowe's paper
  95. for i,(m,n) in enumerate(matches):
  96.     if m.distance < 0.8*n.distance:
  97.         pts2.append(kp2[m.trainIdx].pt)
  98.         pts1.append(kp1[m.queryIdx].pt)
  99.  
  100. # Draw the keypoint matches between both pictures
  101. draw_params = dict(matchColor=(0, 255, 0),
  102.     singlePointColor=(255, 0, 0),
  103.     matchesMask=matchesMask[300:500],
  104.     flags=cv.DrawMatchesFlags_DEFAULT)
  105.  
  106. keypoint_matches = cv.drawMatchesKnn(img1, kp1, img2, kp2, matches[300:500], None, **draw_params)
  107. keypoint_matches = cv.resize(keypoint_matches, (1000,1000))
  108. cv.imshow("Keypoint matches", keypoint_matches)
  109.  
  110.  
  111. pts1 = np.int32(pts1)
  112. pts2 = np.int32(pts2)
  113. F, mask = cv.findFundamentalMat(pts1,pts2,cv.FM_LMEDS)
  114. # We select only inlier points
  115. pts1 = pts1[mask.ravel()==1]
  116. pts2 = pts2[mask.ravel()==1]
  117.  
  118. print(F)
  119.  
  120. def drawlines(img1,img2,lines,pts1,pts2):
  121.     ''' img1 - image on which we draw the epilines for the points in img2
  122.        lines - corresponding epilines '''
  123.     r,c = img1.shape
  124.     img1 = cv.cvtColor(img1,cv.COLOR_GRAY2BGR)
  125.     img2 = cv.cvtColor(img2,cv.COLOR_GRAY2BGR)
  126.     np.random.seed(0)
  127.     for r,pt1,pt2 in zip(lines,pts1,pts2):
  128.         color = tuple(np.random.randint(0,255,3).tolist())
  129.         x0,y0 = map(int, [0, -r[2]/r[1] ])
  130.         x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ])
  131.         img1 = cv.line(img1, (x0,y0), (x1,y1), color,1)
  132.         img1 = cv.circle(img1,tuple(pt1),5,color,-1)
  133.         img2 = cv.circle(img2,tuple(pt2),5,color,-1)
  134.     return img1,img2
  135.  
  136. # Find epilines corresponding to points in right image (second image) and
  137. # drawing its lines on left image
  138. lines1 = cv.computeCorrespondEpilines(pts2.reshape(-1,1,2), 2,F)
  139. lines1 = lines1.reshape(-1,3)
  140. img5,img6 = drawlines(img1,img2,lines1,pts1,pts2)
  141. # Find epilines corresponding to points in left image (first image) and
  142. # drawing its lines on right image
  143. lines2 = cv.computeCorrespondEpilines(pts1.reshape(-1,1,2), 1,F)
  144. lines2 = lines2.reshape(-1,3)
  145. img3,img4 = drawlines(img2,img1,lines2,pts2,pts1)
  146. plt.subplot(121),plt.imshow(img5)
  147. plt.subplot(122),plt.imshow(img3)
  148. plt.show()
  149.  
  150. h1, w1 = img1.shape
  151. h2, w2 = img2.shape
  152. _, H1, H2 = cv.stereoRectifyUncalibrated(np.float32(pts1), np.float32(pts2), Fundmatrix, imgSize=(w1, h2))
  153.  
  154. img1_rect = cv.warpPerspective(img1, H1, (w1, h1))
  155. img2_rect = cv.warpPerspective(img2, H2, (w2, h2))
  156. img1_rectg = cv.resize(img1_rect, (1000,1000))
  157. img2_rectg = cv.resize(img2_rect, (1000,1000))
  158. cv.imshow("rectified_1",img1_rectg)
  159. cv.imshow("rectified_2",img2_rectg)
  160. cv.waitKey(0)
  161.  
  162. # Draw the rectified images
  163. fig, axes = plt.subplots(1, 2, figsize=(15, 10))
  164. axes[0].imshow(img1_rect, cmap="gray")
  165. axes[1].imshow(img2_rect, cmap="gray")
  166. axes[0].axhline(250)
  167. axes[1].axhline(250)
  168. axes[0].axhline(450)
  169. axes[1].axhline(450)
  170. axes[0].axhline(900)
  171. axes[1].axhline(900)
  172. axes[0].axhline(1250)
  173. axes[1].axhline(1250)
  174. axes[0].axhline(1800)
  175. axes[1].axhline(1800)
  176.  
  177. plt.suptitle("Rectified images")
  178. plt.savefig("rectified_images.png")
  179. plt.show()
  180.  
  181. imgL = img1_rect        # The rectified left image
  182. imgR = img2_rect        # The rectified right image
  183.  
  184. # Settings for cv.StereoSGBM_create
  185. minDisparity = 1
  186. numDisparities = 64
  187. blockSize = 1
  188. disp12MaxDiff = 1
  189. uniquenessRatio = 10
  190. speckleWindowSize = 0
  191. speckleRange = 8
  192. stereo = cv.StereoSGBM_create(minDisparity=minDisparity, numDisparities=numDisparities, blockSize=blockSize, disp12MaxDiff=disp12MaxDiff, uniquenessRatio=uniquenessRatio,
  193.     speckleWindowSize=speckleWindowSize, speckleRange=speckleRange)
  194.  
  195. # Calculate the disparity map
  196. disp = stereo.compute(imgL, imgR).astype(np.float32)
  197. # Normalize the values to spread them across the viewable range
  198. disp = cv.normalize(disp,0,255,cv.NORM_MINMAX)
  199.  
  200. # Resize for display
  201. disp = cv.resize(disp, (1000,1000))
  202. cv.imshow("disparity",disp)
  203. cv.waitKey(0)
Advertisement
Add Comment
Please, Sign In to add comment