def calibrate(): criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) Nx_cor = 9 Ny_cor = 6 objp = np.zeros((Nx_cor * Ny_cor, 3), np.float32) objp[:, :2] = np.mgrid[0:Nx_cor, 0:Ny_cor].T.reshape(-1, 2) objpoints = [] # 3d points in real world space imgpoints = [] # 2d points in image plane. count = 0 # count 用来标志成功检测到的棋盘格画面数量 while (True): ret, frame = cap.read() if cv2.waitKey(1) & 0xFF == ord(' '): # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, (Nx_cor, Ny_cor), None) # Find the corners # If found, add object points, image points if ret == True: corners = cv2.cornerSubPix(gray, corners, (5, 5), (-1, -1), criteria) objpoints.append(objp) imgpoints.append(corners) cv2.drawChessboardCorners(frame, (Nx_cor, Ny_cor), corners, ret) count += 1 if count > 20: break # Display the resulting frame cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break global mtx, dist ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) print(mtx, dist) mean_error = 0 for i in range(len(objpoints)): imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist) error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2) / len(imgpoints2) mean_error += error print("total error: ", mean_error / len(objpoints)) # # When everything done, release the capture np.savez('calibrate.npz', mtx=mtx, dist=dist[0:4])
def getEulerAngle(rotationVector): # calculate rotation angles theta = cv2.norm(rotationVector, cv2.NORM_L2) # transformed to quaterniond w = math.cos(theta / 2) x = math.sin(theta / 2) * rotationVector[0] / theta y = math.sin(theta / 2) * rotationVector[1] / theta z = math.sin(theta / 2) * rotationVector[2] / theta ysqr = y * y # pitch (x-axis rotation) t0 = 2.0 * (w * x + y * z) t1 = 1.0 - 2.0 * (x * x + ysqr) # print('t0:{}, t1:{}'.format(t0, t1)) pitch = math.atan2(t0, t1) # yaw (y-axis rotation) t2 = 2.0 * (w * y - z * x) if t2 > 1.0: t2 = 1.0 if t2 < -1.0: t2 = -1.0 yaw = math.asin(t2) # roll (z-axis rotation) t3 = 2.0 * (w * z + x * y) t4 = 1.0 - 2.0 * (ysqr + z * z) roll = math.atan2(t3, t4) # print('pitch:{}, yaw:{}, roll:{}'.format(pitch, yaw, roll)) # convert to degree Y = int((pitch / math.pi) * 180) X = int((yaw / math.pi) * 180) Z = int((roll / math.pi) * 180) return 0, Y, X, Z
def cos_dist(a, b): return 1 - np.dot(a, b) / (norm(a) * norm(b))
np.save("./camera_params/dist", dist) np.save("./camera_params/rvecs", rvecs) np.save("./camera_params/tvecs", tvecs) #Get exif data in order to get focal length. exif_img = PIL.Image.open(calibration_paths[0]) stuff = exif_img.getexif().items() exif_data = { PIL.ExifTags.TAGS[k]:v for k, v in exif_img.getexif().items() if k in PIL.ExifTags.TAGS} #Get focal length in tuple form focal_length_exif = exif_data['FocalLength'] #Get focal length in decimal form focal_length = focal_length_exif[0]/focal_length_exif[1] #Save focal length np.save("./camera_params/FocalLength", focal_length) #Calculate projection error. mean_error = 0 for i in range(len(obj_points)): img_points2, _ = cv2.projectPoints(obj_points[i],rvecs[i],tvecs[i], K, dist) error = cv2.norm(img_points[i], img_points2, cv2.NORM_L2)/len(img_points2) mean_error += error total_error = mean_error/len(obj_points) print (total_error)
from cv2 import cv2 as cv import numpy as np img = cv.imread("Practica/Input/lake.jpg", 1) #Ecualización Conjunta gris = cv.cvtColor(img, cv.COLOR_BGR2GRAY) #conversion gris hist = cv.calcHist(images = [gris], channels = [0], mask = None, histSize = [256], ranges = [0, 256]) hist *= 255.0/cv.norm(hist, cv.NORM_L1) # MAT CV_8UC1 lut = np.zeros((1, 256), dtype = "uint8") acum = 0.0 for i in range (0,256): lut[0][i] = acum acum += hist[i] res = cv.LUT(img,lut) cv.imshow("Entrada", img) cv.imshow("Ecualizada", res) cv.waitKey(0)
def calibration(images): # termination criteria criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((7 * 10, 3), np.float32) objp[:, :2] = np.mgrid[0:7, 0:10].T.reshape(-1, 2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. for fname in images: img = cv.imread(fname) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv.findChessboardCorners(gray, (7, 10), None) # If found, add object points, image points (after refining them) if ret == True: objpoints.append(objp) corners2 = cv.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) imgpoints.append(corners) # Draw and display the corners cv.drawChessboardCorners(img, (7, 10), corners2, ret) img_resized = cv.resize(img, (1400, 700)) cv.imshow('img', img_resized) cv.waitKey(10) cv.destroyAllWindows() ret, K, dist, rvecs, tvecs, std_int, std_ext, pVE = \ cv.calibrateCameraExtended(objpoints, imgpoints, gray.shape[::-1], None, None) mean_error = [] error_vecs = np.zeros( (70 * len(images), 2)) # vertical stack of [x, y] errors for all points in all pictures for i in range(len(objpoints)): # calculating errors imgpoints2, _ = cv.projectPoints(objpoints[i], rvecs[i], tvecs[i], K, dist) error = cv.norm(imgpoints[i], imgpoints2, cv.NORM_L2) / len(imgpoints2) mean_error.append(error) imgpoints2 = np.array(imgpoints2) imgpoints2 = imgpoints2[:, 0, :] imgpoints1 = np.array(imgpoints[i]) imgpoints1 = imgpoints1[:, 0, :] error_vecs[i * 70:(i + 1) * 70, :] = imgpoints1 - imgpoints2 fig = plt.figure(1) # mean reprojection error plot img_nr = [f"{i+1}" for i in range(len(images))] plt.bar(img_nr, mean_error) plt.ylabel("mean reprojection error") plt.xlabel("image number") plt.savefig("Calibration_errors") plt.show() fig2 = plt.figure(2) plt.scatter(error_vecs[:, 0], error_vecs[:, 1]) plt.ylabel("y error") plt.xlabel("x error") plt.savefig("Reprojection_scatter") plt.show() print('Standard errors') print('Focal length and principal point') print('--------------------------------') print('fx: %g +/- %g' % (K[0, 0], std_int[0])) print('fy: %g +/- %g' % (K[1, 1], std_int[1])) print('cx: %g +/- %g' % (K[0, 2], std_int[2])) print('cy: %g +/- %g' % (K[1, 2], std_int[3])) print('Distortion coefficients') print('--------------------------------') print('k1: %g +/- %g' % (dist[0, 0], std_int[4])) print('k2: %g +/- %g' % (dist[0, 1], std_int[5])) print('p1: %g +/- %g' % (dist[0, 2], std_int[6])) print('p2: %g +/- %g' % (dist[0, 3], std_int[7])) print('k3: %g +/- %g' % (dist[0, 4], std_int[8])) np.savetxt('cam_matrix.txt', K) np.savetxt('dist.txt', dist) np.savetxt('stdInt.txt', std_int) np.savetxt('stdExt.txt', std_ext)