Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.51 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3. import glob
  4.  
  5.  
  6.  
  7. def RunAll():
  8. #Part A, finding how to undistort image
  9.  
  10. # termination criteria
  11. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  12.  
  13. WIDTH, HEIGHT = 6, 9
  14.  
  15. objp = np.zeros((WIDTH*HEIGHT,3), np.float32)
  16. objp[:,:2] = np.mgrid[0:HEIGHT,0:WIDTH].T.reshape(-1,2)
  17. #scaling up points
  18. objp *= 100
  19.  
  20. # Arrays to store object points and image points from all the images.
  21. objpoints = [] # 3d point in real world space
  22. imgpoints = [] # 2d points in image plane.
  23. images = glob.glob("images/sample_*.jpg")
  24.  
  25. for filename in images:
  26. img = cv2.imread(filename)
  27. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  28.  
  29. # Find the chess board corners
  30. ret, corners = cv2.findChessboardCorners(gray, (HEIGHT,WIDTH),None)
  31. # If found, add object points, image points (after refining them)
  32. if ret:
  33. objpoints.append(objp)
  34. cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
  35. imgpoints.append(corners)
  36.  
  37. # Draw and display the corners
  38. cv2.drawChessboardCorners(img, (HEIGHT,WIDTH), corners,ret)
  39. cv2.imshow('img', img)
  40. cv2.waitKey(10)
  41. cv2.destroyAllWindows()
  42. ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1])
  43.  
  44. image = cv2.imread('images/test_001.jpg')
  45. h, w = image.shape[:2]
  46. newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
  47. # undistort
  48. dst = cv2.undistort(image, mtx, dist, None, newcameramtx)
  49. # crop the image
  50. x,y,w,h = roi
  51. dst = dst[y:y+h, x:x+w]
  52. cv2.imwrite('CalibrateResult.png',dst)
  53.  
  54.  
  55. #PartB and C
  56. cap = cv2.VideoCapture(0)
  57. image_to_place1 = cv2.imread("Show_me_the_image.jpg")
  58. #resize to fit on board
  59. image_to_place = cv2.resize(image_to_place1, ((HEIGHT-1)*100,(WIDTH-1)*100))
  60. #Whitespace to act as canvas for out image
  61. white_space1 = cv2.imread("white.jpg")
  62. #resize to fit on board
  63. white_space = cv2.resize(white_space1, ((HEIGHT-1)*100,(WIDTH-1)*100))
  64.  
  65. while cv2.waitKey(1) & 0xFF != ord('q'):
  66. #capture a frame
  67. ret, img = cap.read()
  68. h, w = img.shape[:2]
  69. newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
  70. undst = cv2.undistort(img, mtx, dist, None, newcameramtx)
  71. # Our operations on the frame come here
  72. gray = cv2.cvtColor(undst, cv2.COLOR_BGR2GRAY)
  73.  
  74. # Find the chess board corners
  75. ret, corners = cv2.findChessboardCorners(gray, (HEIGHT,WIDTH),None)
  76. # If found, add object points and image points
  77. if ret:
  78. cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
  79. #Draw and display the corners
  80. cv2.drawChessboardCorners(undst, (HEIGHT,WIDTH), corners,ret)
  81. projection = CalibrateCamera3D(np.hstack([objp, np.reshape(corners, (54, 2))]))
  82. image_to_place_warp = cv2.warpPerspective(image_to_place, projection, (w,h))
  83. white_warp = cv2.bitwise_not(cv2.warpPerspective(white_space, projection, (w,h)));
  84. undst = cv2.bitwise_and(undst, white_warp) + image_to_place_warp
  85.  
  86. cv2.imshow('img',undst)
  87.  
  88. # release everything
  89. cap.release()
  90. cv2.destroyAllWindows()
  91.  
  92. #Previous Assignments Camera Calibration
  93. def insertOne(data):
  94. return np.insert(data, 2, 1, axis=1)
  95.  
  96. def CalibrateCamera3D(data):
  97. """ copy of data to work with"""
  98. data=np.delete(data, 2, 1)
  99. datacopy= insertOne(data).copy()
  100. """getting XYZ1, x and y respectively"""
  101. P, x, y = datacopy[:,:3], datacopy[:,-2], datacopy[:,-1]
  102. """blank array to fill with the new matrix"""
  103. totalarr = []
  104. """looping over each row in P so can get each line of XY10... and 000X... """
  105. for i, row in enumerate(P):
  106. arr = np.hstack([row,np.zeros(3),-x[i]*row])
  107. arr1 = np.hstack([np.zeros(3), row , -y[i]*row])
  108. totalarr.append(np.vstack([arr, arr1]))
  109. totalarr = np.vstack(totalarr)
  110. """array Transpose by array"""
  111. AtA = totalarr.T.dot(totalarr)
  112. """getting the eignvectors"""
  113. eigvals, eigvectors = np.linalg.eig(AtA)
  114. """ eigenvectors are columns so Transpose matrix"""
  115. #make sure the eigenvector is always the smallest, as eigvectors[-1] sometimes is not.
  116. M = eigvectors.T[np.argmin(eigvals)]
  117. """reshape to correct shape"""
  118. return M.reshape((3, 3))
  119.  
  120. if __name__ == "__main__":
  121. RunAll()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement