1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| import numpy as np import time import cv2 import cv2.aruco as aruco import math
cv_file = cv2.FileStorage("yuyan.yaml", cv2.FILE_STORAGE_READ) camera_matrix = cv_file.getNode("camera_matrix").mat() dist_matrix = cv_file.getNode("dist_coeff").mat() cv_file.release()
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
while True: ret, frame = cap.read() h1, w1 = frame.shape[:2] newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_matrix, (h1, w1), 0, (h1, w1)) dst1 = cv2.undistort(frame, camera_matrix, dist_matrix, None, newcameramtx) x, y, w1, h1 = roi dst1 = dst1[y:y + h1, x:x + w1] frame=dst1
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create()
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray,aruco_dict,parameters=parameters)
if ids is not None: rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, 0.05, camera_matrix, dist_matrix) (rvec-tvec).any()
for i in range(rvec.shape[0]): aruco.drawAxis(frame, camera_matrix, dist_matrix, rvec[i, :, :], tvec[i, :, :], 0.03) aruco.drawDetectedMarkers(frame, corners,ids)
cv2.putText(frame, "Id: " + str(ids), (0,64), font, 1, (0,255,0),2,cv2.LINE_AA)
deg=rvec[0][0][2]/math.pi*180 R=np.zeros((3,3),dtype=np.float64) cv2.Rodrigues(rvec,R) sy=math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0]) singular=sy< 1e-6 if not singular: x = math.atan2(R[2, 1], R[2, 2]) y = math.atan2(-R[2, 0], sy) z = math.atan2(R[1, 0], R[0, 0]) else: x = math.atan2(-R[1, 2], R[1, 1]) y = math.atan2(-R[2, 0], sy) z = 0 rx = x * 180.0 / 3.141592653589793 ry = y * 180.0 / 3.141592653589793 rz = z * 180.0 / 3.141592653589793
cv2.putText(frame,'deg_z:'+str(ry)+str('deg'),(0, 140), font, 1, (0, 255, 0), 2, cv2.LINE_AA)
distance = ((tvec[0][0][2] + 0.02) * 0.0254) * 100
cv2.putText(frame, 'distance:' + str(round(distance, 4)) + str('m'), (0, 110), font, 1, (0, 255, 0), 2, cv2.LINE_AA)
else: cv2.putText(frame, "No Ids", (0,64), font, 1, (0,255,0),2,cv2.LINE_AA)
cv2.imshow("frame",frame)
key = cv2.waitKey(1)
if key == 27: print('esc break...') cap.release() cv2.destroyAllWindows() break
if key == ord(' '):
filename = str(time.time())[:10] + ".jpg" cv2.imwrite(filename, frame)
|