Ejemplo n.º 1
0
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])
Ejemplo n.º 2
0
def calibrate_intrinsic(object_points, image_points, image_size):
    """Calibrate camera intrinsic pattern from input object points(real
    coordinates of points on chessboard calibration rig) and input image
    points(points on the chessboard as seen by camera).
    """

    __, cam_mat, dist_coeff, __, __ = cv2.calibrateCamera(
        object_points, image_points, image_size, 0, 0)

    return cam_mat, dist_coeff
Ejemplo n.º 3
0
def calibrateOne(img_path, cameraParam):
    criteria = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 30, 0.001)
    #设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001
    #获取标定板角点的位置
    objp = np.zeros((4 * 7, 3), np.float32)
    objp[:, :2] = np.mgrid[0:7, 0:4].T.reshape(-1, 2)  #将世界坐标系建在标定板上

    obj_points = []  #3D points
    img_points = []  #2D points

    images = glob.glob(img_path)
    i = 0
    for fname in images:
        img = cv2.imread(fname)
        #print(fname)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        size = gray.shape[::-1]
        h, w = gray.shape[:2]
        ret, corners = cv2.findChessboardCorners(gray, (7, 4), None)
        if ret:
            obj_points.append(objp)

            corners2 = cv2.cornerSubPix(gray, corners, (5, 5), (-1, -1),
                                        criteria)
            #在原角点的基础上寻找亚像素点
            #print(corners2)
            if [corners2]:
                img_points.append(corners2)
            else:
                img_points.append(corners)
            cv2.drawChessboardCorners(img, (7, 4), corners, ret)
            i += 1

    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points,
                                                       size, None, None,
                                                       criteria)
    #dist——>dist coffients(就是k、p的值)

    newcameramtx, roi = cv2.getOptimalNewCameraMatrix(
        mtx, dist, (w, h), 1, (w, h))  #显示更大范围的图片(正常重映射之后会删掉一部分图像)
    #将fx,fy(世界坐标系的焦距)投射到fu,fv(图像坐标系的焦距)上,立体矫正时会用
    #dst = cv2.undistort(img,mtx,dist,None,newcameramtx)
    #x,y,w,h = roi

    cameraParam['ret'] = ret
    cameraParam['mtx'] = mtx
    cameraParam['dist'] = dist
    cameraParam['rvecs'] = rvecs
    cameraParam['tvecs'] = tvecs
    cameraParam['img_points'] = img_points
    cameraParam['obj_points'] = obj_points
    cameraParam['size'] = size
    cameraParam['newmtx'] = newcameramtx
    print("Calibrate One Camera Success")
Ejemplo n.º 4
0
def cal_undistort(img, obj_points, img_points):
    """
    Parameter:
        img:
        obj_points:
        img_points:
    Return:
        dst:
    """
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
        obj_points, img_points, img.shape[1::-1], None, None)
    dst = cv2.undistort(img, mtx, dist, None, mtx)
    return dst
Ejemplo n.º 5
0
def calculate_camera_matrix_and_distortion_coefficients(camera_model_name):
    # termination criteria
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

    # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(7,5,0)
    object_points = np.zeros((6 * 8, 3), np.float32)
    object_points[:, :2] = np.mgrid[0:8, 0:6].T.reshape(-1, 2)

    # Arrays to store object points and image points from all the images.
    real_world_points = []  # 3d point in real world space
    image_points = []  # 2d points in image plane.

    image_paths = glob.glob("calibration_images/*.png")

    for path_to_image in image_paths:
        img = cv2.imread(path_to_image)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Find the chess board corners
        chess_board_successfully_detected, corners = cv2.findChessboardCorners(
            gray, (8, 6), None)
        print("Found chess board in: " + path_to_image + " : " +
              str(chess_board_successfully_detected))

        # If found, add object points, image points (after refining them)
        if chess_board_successfully_detected:
            real_world_points.append(object_points)

            refined_corners = cv2.cornerSubPix(gray, corners, (11, 11),
                                               (-1, -1), criteria)
            image_points.append(refined_corners)

            # Draw and display the corners
            # img = cv2.drawChessboardCorners(img, (7, 6), refined_corners, chess_board_successfully_detected)
            # cv2.imshow('img', resize_image(img, (1920, 1080)))
            # cv2.waitKey()

    cv2.destroyAllWindows()

    ret, camera_matrix, distortion_coeffs, rvecs, tvecs = cv2.calibrateCamera(
        real_world_points, image_points, gray.shape[::-1], None, None)

    h, w = gray.shape[:2]
    camera_matrix_with_crop, roi = cv2.getOptimalNewCameraMatrix(
        camera_matrix, distortion_coeffs, (w, h), 1, (w, h))

    file_name = f"camera_calibration_{camera_model_name}.npz"
    np.savez(file_name,
             camera_matrix=camera_matrix,
             distortion_coeffs=distortion_coeffs,
             camera_matrix_with_crop=camera_matrix_with_crop)
Ejemplo n.º 6
0
def find_calibration_matrix(images):
    # Prepare real world points
    rwp = np.zeros((7 * 9, 3), np.float32)
    rwp[:, :2] = np.mgrid[0:7, 0:9].T.reshape(-1, 2)

    # Arrays to store 3D points in the real world and 2D points in image plane
    rw_points = []
    image_points = []

    for image in images:
        img = cv2.imread(image)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Take in a 8-bit grayscale image and the number of internal corners of chessboard and flags.
        # CLAIB_CV_FAST_CHECK = check quickly for corners and end if none to save time
        found, corners = cv2.findChessboardCorners(
            img_gray, (7, 9), flags=cv2.CALIB_CB_FAST_CHECK
        )

        if found:
            rw_points.append(rwp)
            # Needs accuracy below pixel level
            corners = cv2.cornerSubPix(
                img_gray,
                corners,
                (11, 11),
                (-1, -1),
                (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001),
            )
            image_points.append(corners)

            # Draws the corners on picture
            # cv2.drawChessboardCorners(img, (7, 9), cornersnew, retval)
            # cv2.imshow('img', img)
            # cv2.waitKey()
        else:
            print("no corners found in " + image, file=sys.stderr)

    cv2.destroyAllWindows()

    _, cameramatrix, distortioncoefficients, _, _ = cv2.calibrateCamera(
        rw_points, image_points, img_gray.shape[::-1], None, None
    )
    return cameramatrix, distortioncoefficients
Ejemplo n.º 7
0
 def generate_distortion_config(self, image_shape: Tuple[int, int]):
     """This method should only be called if the distortion matrix and
        coefficients have not been calculated or the calibration images
        have changed
     """
     dist_pickle = pickle.load(
         open(self.uuid + '_' + _OBJ_IMG_PTS_PICKLE_FILE_NAME, "rb"))
     objpoints = dist_pickle["objpoints"]
     imgpoints = dist_pickle["imgpoints"]
     _, mtx, dist, _, _ = cv2.calibrateCamera(objpoints, imgpoints,
                                              image_shape, None, None)
     self._distortion_matrix = mtx
     self._distortion_coefficients = dist
     self._store_config(
         self.uuid + '_' + _DIST_MTX_COE_PICKLE_FILE_NAME, {
             'mtx': self._distortion_matrix,
             'coefficients': self._distortion_coefficients,
             'pattern_size': self.pattern_size
         })
Ejemplo n.º 8
0
def get_callibration_stuff():
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
    cap = cv2.VideoCapture('pictures/ChessboardPattern/11.mp4')
    nx, ny = 8, 6
    objp = np.zeros((8 * 6, 3), np.float32)
    objp[:, :2] = np.mgrid[0:8, 0:6].T.reshape(-1, 2)

    objpoints = []  # 3d point in real world space
    imgpoints = []  # 2d points in image plane.
    fps = get_fps(cap)
    num_frames = get_frames(cap)
    frames_with_corners = 0

    def skip_frame(video):
        ret2, frame2 = video.read()
        if ret2:
            curr_frame = video.get(cv2.CAP_PROP_POS_FRAMES)
            if curr_frame <= num_frames:
                cap.set(cv2.CAP_PROP_POS_FRAMES, curr_frame + 0.5 * fps)
                return frame2

    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            frame = skip_frame(cap)
            r_frame_bw = get_resized_and_bw(frame, 40)
            found_corners, corners = cv2.findChessboardCorners(
                r_frame_bw, (nx, ny), None)
            if found_corners:
                frames_with_corners += 1
                objpoints.append(objp)
                corners2 = cv2.cornerSubPix(r_frame_bw, corners, (11, 11),
                                            (-1, -1), criteria)
                imgpoints.append(corners2)
                if frames_with_corners == 16:
                    break

    cap.release()
    cv2.destroyAllWindows()
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints,
                                                       r_frame_bw.shape[::-1],
                                                       None, None)
    return ret, mtx, dist, rvecs, tvecs
Ejemplo n.º 9
0
    def findcorners(self):
        plt.close('all')

        # 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((11 * 8, 3), np.float32)
        objp[:, :2] = np.mgrid[0:11, 0:8].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 i in range(1, 16):
            img_name = str(i) + '.bmp'
            fname = os.path.join('Datasets/Q2_Image', img_name)

            img = cv.imread(fname)
            gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
            # Find the chess board corners
            ret, corners = cv.findChessboardCorners(gray, (11, 8), 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, (11, 8), corners2, ret)
                plt_img = img[:, :, ::-1]
                plt.figure(fname)
                plt.imshow(plt_img)

        ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(
            objpoints, imgpoints, gray.shape[::-1], None, None)

        np.savez('output.npz', mtx, dist, rvecs, tvecs)
        np.savez('img_obj_points.npz', imgpoints, objpoints)

        plt.show()
Ejemplo n.º 10
0
def calib(imgpath,camroot,nx,ny):
    # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
    objp = np.zeros((ny * nx, 3), np.float32)
    objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)*290
    
    # Arrays to store object points and image points from all the images.
    objpoints = [] # 3d points in real world space
    imgpoints = [] # 2d points in image plane.
    
    images = glob(imgpath+'/*.jpg')
    if len(images) > 0:
        print("images num for calibration : ", len(images))
    else:
        print("No image for calibration.")
        return
    
    ret_count = 0
    for _, fname in enumerate(images):
        img = cv2.imread(fname)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_size = (img.shape[1], img.shape[0])
        # Find the chessboard corners
        ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)
        #cv2.drawChessboardCorners(img,(nx,ny),corners,ret)
 
        # If found, add object points, image points
        if ret == True:
            ret_count += 1
            objpoints.append(objp)
            imgpoints.append(corners)
            print("read image:",ret_count)
    if len(objpoints)==0:
        print("failed to find corners")
        return        
    ret, cameraMatrix, distCoeffs, _, _ = cv2.calibrateCamera(objpoints, imgpoints,img_size, None, None)
    print('Do calibration successfully')
    np.savetxt(camroot+"cameraMatrix.txt",cameraMatrix,fmt="%.18f",delimiter=',')
    np.savetxt(camroot+"distCoeffs.txt",distCoeffs,fmt="%.18f",delimiter=',')
    return ret,cameraMatrix, distCoeffs     
Ejemplo n.º 11
0
    img_name = str(i) + '.bmp'
    fname = os.path.join('Datasets/Q2_Image', img_name)

    img = cv.imread(fname)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv.findChessboardCorners(gray, (11, 8), 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, (11, 8), corners2, ret)

        ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(
            objpoints, imgpoints, gray.shape[::-1], None, None)

        h, w = img.shape[:2]
        newcameramtx, roi = cv.getOptimalNewCameraMatrix(
            mtx, dist, (w, h), 1, (w, h))
        # print(roi)
        mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx,
                                                (w, h), 5)
        dst = cv.remap(img, mapx, mapy, cv.INTER_LINEAR)

        x, y, w, h = roi
        dst = dst[y:y + h, x:x + w]

        npz = np.load('./output.npz')
        print(npz.files)
Ejemplo n.º 12
0
        # print(corners2)
        if [corners2]:
            img_points.append(corners2)
        else:
            img_points.append(corners)
        # 把角点画出来
        cv2.drawChessboardCorners(img, (8, 6), corners,
                                  ret)  # 记住,OpenCV的绘制函数一般无返回值
        # cv2.imwrite('c-'+str(0).zfill(4)+'.png', img) # 文件命名补齐函数zfill
        # 保存绘制角度后的图像
        # cv2.imwrite(image_name +".png", img)
# print(len(img_points))
# cv2.destroyAllWindows()

# 标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points,
                                                   size, None, None)
# print("ret:", ret)
# print("mtx:\n", mtx) # 内参数矩阵
# print("dist:\n", dist)  # 畸变系数   distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
# print("rvecs:\n", rvecs)  # 旋转向量  # 外参数
# print("tvecs:\n", tvecs ) # 平移向量  # 外参数
# print("-----------------------------------------------------")

# img = cv2.imread(images[2])
# h, w = img.shape[:2]
# newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))#显示更大范围的图片(正常重映射之后会删掉一部分图像)
# print (newcameramtx)
# print("------------------使用undistort函数-------------------")
# dst = cv2.undistort(img,mtx,dist,None,newcameramtx)
# x,y,w,h = roi
# dst1 = dst[y:y+h,x:x+w]
Ejemplo n.º 13
0
def calibrate():
    #棋盘角点数col*row
    col = 13
    row = 6

    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

    objp = np.zeros((row * col, 3), np.float32)
    # 用于标定的棋盘每个方格边长为22mm
    objp[:, :2] = 22*np.mgrid[0:col, 0:row].T.reshape(-1, 2)

    objpoints = []  # 世界坐标系下的点坐标
    imgpoints = []  # 像素平面坐标系下的点坐标
    print("请选择标定用到的照片所在的文件夹", "\n")

    root = tkinter.Tk()
    root.withdraw()

    global path  # 用于标定的照片所在目录
    path = tkinter.filedialog.askdirectory(
        title="选择标定用到的照片所在的文件夹")  # 选择标定用到的照片所在的文件夹
    images = glob.glob(path+"/*.jpg")
    found = 0  # 记录用于标定的图像数目
    for k, fname in enumerate(images):
        img = cv2.imread(fname)

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        ret, corners = cv2.findChessboardCorners(gray, (col, row), None)
        # 角点检测

        if ret is True:
            print("读取", fname)
            objpoints.append(objp)

            
            # 角点检测精度会影响标定的精度
            corners2 = cv2.cornerSubPix(
                gray, corners, (11, 11), (-1, -1), criteria)#亚像素角点位置
            # corners2=corners
            #_,corners2=cv2.find4QuadCornerSubpix(gray, corners, (11, 11))

            imgpoints.append(corners2)
            img = cv2.drawChessboardCorners(img, (col, row), corners2, ret)#标记角点
            found += 1
            if len(images) < 16:  # 图片过多时,不在UI中展示,避免弹窗过多
                cv2.namedWindow('press any key to continue', cv2.WINDOW_NORMAL)
                cv2.imshow('press any key to continue', img)
                cv2.waitKey(0)

            #image_name = path2 + "//corner"+str(found) + '.png'
            #cv2.imwrite(image_name, img)
            #存储已标出角点的照片
            
    global path2  # 存放结果的目录(含记录相机参数的文件,和畸变矫正后的照片,3-D box照片)
    path2 = tkinter.filedialog.askdirectory(
        title="选择结果存放的文件夹(应与用于标定的照片所在的文件夹不同)")  # 选择结果存放的文件夹

    print("Number of images used for calibration: ", found)

    # 相机标定
    ret2, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints,
                                                        gray.shape[::-1], None, None)

    print("reprojection error:", ret2)
    print("内参矩阵:", mtx)
    print("畸变系数:", dist)
    print("旋转向量:", rvecs)
    print("平移向量:", tvecs)

    images = glob.glob(path+"//*.jpg")
    for i, fname in enumerate(images):
        img = cv2.imread(fname)
        if img is None:
            continue
        h, w = img.shape[:2]
        newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1,
                                                            (w, h))
        dst = cv2.undistort(img, mtx, dist, None, newcameramtx)  # 矫正畸变

        x, y, w, h = roi
        dst = dst[y:y + h, x:x + w]#裁剪
        outpath = path2+"//tianyi_gao_undistorted" + str(i + 1) + ".jpg"
        cv2.imwrite(outpath, dst)
    print("新内参矩阵:", newcameramtx)
    
    data = {
        'camera_matrix': np.asarray(mtx).tolist(),
        'dist_coeff': np.asarray(dist).tolist(),
        'new_camera_matrix': np.asarray(newcameramtx).tolist(),
        'rvecs': np.asarray(rvecs).tolist(),
        'tvecs': np.asarray(tvecs).tolist(),
        'reprojection_error': np.asarray(ret2).tolist()
    }
    # 存储相机参数(yaml)
    with open(path2+"//calibration_parameters.yaml", "w") as f:
        yaml.dump(data, f)
    # 存储相机参数(txt)
    with open(path2+"//tianyi_gao_cam.txt", "w") as f2:
        name = list(data.keys())
        value = list(data.values())
        for i in range(len(name)):
            f2.write(name[i] + ":" + "\n" + str(value[i]) + "\n")

    print('Calibrate Done')
    cv2.destroyAllWindows()
    return mtx, dist, rvecs, tvecs, ret2, path2
	print("Image loaded, Analyzing...")
	#find chessboard corners
	ret,corners = cv2.findChessboardCorners(gray_image, chessboard_size, None)

	if ret == True:
		print("Chessboard detected!")
		print(image_path)
		#define criteria for subpixel accuracy
		criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
		#refine corner location (to subpixel accuracy) based on criteria.
		cv2.cornerSubPix(gray_image, corners, (5,5), (-1,-1), criteria)
		obj_points.append(objp)
		img_points.append(corners)

#Calibrate camera
ret, K, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points,gray_image.shape[::-1], None, None)

#Save parameters into numpy file
np.save("./camera_params/ret", ret)
np.save("./camera_params/K", K)
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()
        cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
        #追加进入世界三维点和平面二维点中
        objpoints.append(objp)
        imgpoints.append(corners)
        # 将角点在图像上显示
        cv2.drawChessboardCorners(img, (w,h), corners, ret)
        cv2.namedWindow('findCorners', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('findCorners', 640, 480)
        cv2.imshow('findCorners',img)
        cv2.waitKey(200)
cv2.destroyAllWindows()
#%% 标定
print('正在计算')
#标定
ret, mtx, dist, rvecs, tvecs = \
    cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)


print("ret:",ret  )
print("mtx:\n",mtx)      # 内参数矩阵
print("dist畸变值:\n",dist   )   # 畸变系数   distortion cofficients = (k_1,k_2,p_1,p_2,k_3)
print("rvecs旋转(向量)外参:\n",rvecs)   # 旋转向量  # 外参数
print("tvecs平移(向量)外参:\n",tvecs  )  # 平移向量  # 外参数
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (u, v), 0, (u, v))
print('newcameramtx外参',newcameramtx)
#打开摄像机
camera=cv2.VideoCapture(0)
while True:
    (grabbed,frame)=camera.read()
    h1, w1 = frame.shape[:2]
    newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (u, v), 0, (u, v))
Ejemplo n.º 16
0
                print("Couple with " + t + " has been added")
                if (True == retR) & (True == retL):
                    objpoints.append(objp)
                    cv2.cornerSubPix(ChessImaR, cornersR, (11, 11), (-1, -1),
                                     criteria)
                    cv2.cornerSubPix(ChessImaL, cornersL, (11, 11), (-1, -1),
                                     criteria)
                    imgpointsR.append(cornersR)
                    imgpointsL.append(cornersL)
                break
            elif (cv2.waitKey(2) & 0xFF == ord('q')):
                break
    cv2.destroyAllWindows()
    # Determine the new values for different parameters
    #   Right Side
    retR, mtxR, distR, rvecsR, tvecsR = cv2.calibrateCamera(
        objpoints, imgpointsR, ChessImaR.shape[::-1], None, None)
    hR, wR = ChessImaR.shape[:2]
    OmtxR, roiR = cv2.getOptimalNewCameraMatrix(mtxR, distR, (wR, hR), 1,
                                                (wR, hR))

    #   Left Side
    retL, mtxL, distL, rvecsL, tvecsL = cv2.calibrateCamera(
        objpoints, imgpointsL, ChessImaL.shape[::-1], None, None)
    hL, wL = ChessImaL.shape[:2]
    OmtxL, roiL = cv2.getOptimalNewCameraMatrix(mtxL, distL, (wL, hL), 1,
                                                (wL, hL))

    print('Cameras Ready to use')
    print("Camera calibration value: " + str(retL) + " and " + str(retR))

    # ********************************************
Ejemplo n.º 17
0
        r_frame = cv2_helpers.get_resized(frame, 40)
        r_frame_bw = cv2_helpers.get_resized_and_bw(frame, 40)
        cv2.imshow("something", r_frame)
        found_corners, corners = cv2.findChessboardCorners(
            r_frame_bw, (nx, ny), None)
        if found_corners:
            frames_with_corners += 1
            objpoints.append(objp)
            corners2 = cv2.cornerSubPix(r_frame_bw, corners, (11, 11),
                                        (-1, -1), criteria)
            imgpoints.append(corners2)
            new_img = cv2.drawChessboardCorners(r_frame, (nx, ny), corners,
                                                ret)
            cv2.imshow("test", new_img)
            if frames_with_corners == 16:
                break

cap.release()
cv2.destroyAllWindows()

print("callibrating the given video...")
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints,
                                                   r_frame_bw.shape[::-1],
                                                   None, None)

print("ret: ", ret)
print("mtx: ", mtx)
print("dist: ", dist)
print("rvecs: ", rvecs)
print("tvecs: ", tvecs)