本文整理匯總了Python中cv2.findChessboardCorners方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.findChessboardCorners方法的具體用法?Python cv2.findChessboardCorners怎麽用?Python cv2.findChessboardCorners使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.findChessboardCorners方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_chessboard
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def get_chessboard(self, columns, rows, show=False):
"""
Take a picture with a chessboard visible in both captures.
``columns`` and ``rows`` should be the number of inside corners in the
chessboard's columns and rows. ``show`` determines whether the frames
are shown while the cameras search for a chessboard.
"""
found_chessboard = [False, False]
# Placeholder for corners
found_corners = [None, None]
while not all(found_chessboard):
frames = self.get_frames()
if show:
self.show_frames(1)
for i, frame in enumerate(frames):
(found_chessboard[i],
found_corners[i]) = cv2.findChessboardCorners(frame, (columns, rows),
flags=cv2.CALIB_CB_FAST_CHECK)
return frames, found_corners
示例2: _get_corners
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def _get_corners(self, image):
"""Find subpixel chessboard corners in image."""
temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(temp,
(self.rows, self.columns))
if not ret:
raise ChessboardNotFoundError("No chessboard could be found.")
cv2.cornerSubPix(temp, corners, (11, 11), (-1, -1),
(cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS,
30, 0.01))
return corners
示例3: find_chessboard
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def find_chessboard(frame):
chessboard_flags = cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE
small_frame = cv2.resize(frame, (0, 0), fx=0.3, fy=0.3)
return cv2.findChessboardCorners(small_frame, (9, 6), chessboard_flags)[0] and \
cv2.findChessboardCorners(frame, (9, 6), chessboard_flags)[0]
示例4: _chessboard_image_points
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def _chessboard_image_points(self,img):
found, corners = cv2.findChessboardCorners(img,(self.pattern_columns,self.pattern_rows))
return(found,corners)
示例5: processImage
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def processImage(fn):
print('processing %s... ' % fn)
img = cv.imread(fn, 0)
if img is None:
print("Failed to load", fn)
return None
assert w == img.shape[1] and h == img.shape[0], ("size: %d x %d ... " % (img.shape[1], img.shape[0]))
found, corners = cv.findChessboardCorners(img, pattern_size)
if found:
term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)
cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
if debug_dir:
vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
cv.drawChessboardCorners(vis, pattern_size, corners, found)
_path, name, _ext = splitfn(fn)
outfile = os.path.join(debug_dir, name + '_chess.png')
cv.imwrite(outfile, vis)
if not found:
print('chessboard not found')
return None
print(' %s... OK' % fn)
return (corners.reshape(-1, 2), pattern_points)
示例6: try_approximate_corners_blur
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def try_approximate_corners_blur(self, board_dims, sharpness_threshold):
sharpness = cv2.Laplacian(self.frame, cv2.CV_64F).var()
if sharpness < sharpness_threshold:
return False
found, corners = cv2.findChessboardCorners(self.frame, board_dims)
self.current_image_points = corners
return found
示例7: try_approximate_corners
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def try_approximate_corners(self, board_dims):
found, corners = cv2.findChessboardCorners(self.frame, board_dims)
self.current_image_points = corners
self.current_board_dims = board_dims
return found
示例8: cube
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def cube(img):
#img_in = cv2.imread("Picture 27.jpg")
#img = cv2.resize(img_in,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)
#cv2.imshow('img',img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#cv2.imshow('gray',gray)
ret, corners = cv2.findChessboardCorners(gray, (8,7),None)
# print ret,corners
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((7*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8,0:7].T.reshape(-1,2)
#axis = np.float32([[3,0,0], [0,3,0], [0,0,-3]]).reshape(-1,3)
axis = np.float32([[0,0,0], [0,3,0], [3,3,0], [3,0,0],
[0,0,-3],[0,3,-3],[3,3,-3],[3,0,-3] ])
if ret == True:
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
# Find the rotation and translation vectors.
rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners, mtx, dist)
# project 3D points to image plane
imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)
#print imgpts
img = draw2(img,corners,imgpts)
return img
示例9: find_chessboard
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def find_chessboard(self, sx=6, sy=9):
"""Finds the corners of an sx X sy chessboard in the image.
Parameters
----------
sx : int
Number of chessboard corners in x-direction.
sy : int
Number of chessboard corners in y-direction.
Returns
-------
:obj:`list` of :obj:`numpy.ndarray`
A list containing the 2D points of the corners of the detected
chessboard, or None if no chessboard found.
"""
# 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) ....,(6,5,0)
objp = np.zeros((sx * sy, 3), np.float32)
objp[:, :2] = np.mgrid[0:sx, 0:sy].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.
# create images
img = self.data.astype(np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (sx, sy), None)
# If found, add object points, image points (after refining them)
if ret:
objpoints.append(objp)
cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners)
if corners is not None:
return corners.squeeze()
return None
示例10: calibrate
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def calibrate(drawconer=False):
'''
read the calibration image and do the camera calibration
and output the result to a pickle file.
if drawconer is True, will draw the corner on the chessboard file and save it to another folder.
'''
# !!! IMPORTANT, set the nx, ny according the calibration chessboard pictures.
nx = 9
ny = 6
# prepare object points, like (0,0,0), (1,0,0), (2,0,0), ...(6,5,0)
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d pionts in image plane.
# Make a list of calibration images
images = glob.glob('chessboard_img/calibration*.jpg')
print("Reading the calibration file...")
# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
print("Searching corners on ", fname, "...")
ret, corners = cv2.findChessboardCorners(gray, (nx,ny), None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
if drawconer:
cv2.drawChessboardCorners(img, (nx,ny), corners, ret)
write_name = 'corners_found'+str(idx)+'.jpg'
cv2.imwrite(write_name, img)
cv2.imshow('img', img)
cv2.waitKey(500)
cv2.destroyAllWindows()
# Get image size
img_size = (img.shape[1],img.shape[0])
# Do camera calibration given object points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
# Save the camera calibration result for later use (we won't worry about rvecs / tvecs)
print("Saving the parameter to file...>>camera_cal.p")
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
pickle_file = open("camera_cal.p", "wb")
pickle.dump(dist_pickle, pickle_file)
pickle_file.close()
示例11: process_images
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def process_images(self, filepath):
"""Read images, detect corners, refine corners, and save data."""
# Arrays to store object points and image points from all the images.
self.objpoints = [] # 3d point in real world space
self.imgpoints_l = [] # 2d points in image plane.
self.imgpoints_r = [] # 2d points in image plane.
self.calib_successes = [] # polygon ids of left/right image sets with checkerboard corners.
images_left = glob.glob(filepath + "/left/*")
images_right = glob.glob(filepath + "/right/*")
images_left.sort()
images_right.sort()
print("\nAttempting to read images for left camera from dir: " +
filepath + "/left/")
print("Attempting to read images for right camera from dir: " +
filepath + "/right/")
assert len(images_left) != 0, "ERROR: Images not read correctly, check directory"
assert len(images_right) != 0, "ERROR: Images not read correctly, check directory"
for image_left, image_right in zip(images_left, images_right):
img_l = cv2.imread(image_left, 0)
img_r = cv2.imread(image_right, 0)
assert img_l is not None, "ERROR: Images not read correctly"
assert img_r is not None, "ERROR: Images not read correctly"
print("Finding chessboard corners for %s and %s..." % (os.path.basename(image_left), os.path.basename(image_right)))
start_time = time.time()
# Find the chess board corners
flags = 0
flags |= cv2.CALIB_CB_ADAPTIVE_THRESH
flags |= cv2.CALIB_CB_NORMALIZE_IMAGE
ret_l, corners_l = cv2.findChessboardCorners(img_l, (9, 6), flags)
ret_r, corners_r = cv2.findChessboardCorners(img_r, (9, 6), flags)
# termination criteria
self.criteria = (cv2.TERM_CRITERIA_MAX_ITER +
cv2.TERM_CRITERIA_EPS, 30, 0.001)
# if corners are found in both images, refine and add data
if ret_l and ret_r:
self.objpoints.append(self.objp)
rt = cv2.cornerSubPix(img_l, corners_l, (5, 5),
(-1, -1), self.criteria)
self.imgpoints_l.append(corners_l)
rt = cv2.cornerSubPix(img_r, corners_r, (5, 5),
(-1, -1), self.criteria)
self.imgpoints_r.append(corners_r)
self.calib_successes.append(polygon_from_image_name(image_left))
print("\t[OK]. Took %i seconds." % (round(time.time() - start_time, 2)))
else:
print("\t[ERROR] - Corners not detected. Took %i seconds." % (round(time.time() - start_time, 2)))
self.img_shape = img_r.shape[::-1]
print(str(len(self.objpoints)) + " of " + str(len(images_left)) +
" images being used for calibration")
self.ensure_valid_images()
示例12: calibrate_camera
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def calibrate_camera(nx, ny, basepath):
"""
:param nx: number of grids in x axis
:param ny: number of grids in y axis
:param basepath: path contains the calibration images
:return: write calibration file into basepath as calibration_pickle.p
"""
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)
# 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.
# Make a list of calibration images
images = glob.glob(path.join(basepath, 'calibration*.jpg'))
# Step through the list and search for chessboard corners
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (nx,ny),None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (nx,ny), corners, ret)
cv2.imshow('input image',img)
cv2.waitKey(500)
cv2.destroyAllWindows()
# calibrate the camera
img_size = (img.shape[1], img.shape[0])
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
# Save the camera calibration result for later use (we don't use rvecs / tvecs)
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
destnation = path.join(basepath,'calibration_pickle.p')
pickle.dump( dist_pickle, open( destnation, "wb" ) )
print("calibration data is written into: {}".format(destnation))
return mtx, dist
示例13: calibrate_camera
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def calibrate_camera(calib_images_dir, verbose=False):
"""
Calibrate the camera given a directory containing calibration chessboards.
:param calib_images_dir: directory containing chessboard frames
:param verbose: if True, draw and show chessboard corners
:return: calibration parameters
"""
assert path.exists(calib_images_dir), '"{}" must exist and contain calibration images.'.format(calib_images_dir)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6 * 9, 3), np.float32)
objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)
# 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.
# Make a list of calibration images
images = glob.glob(path.join(calib_images_dir, 'calibration*.jpg'))
# Step through the list and search for chessboard corners
for filename in images:
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
pattern_found, corners = cv2.findChessboardCorners(gray, (9, 6), None)
if pattern_found is True:
objpoints.append(objp)
imgpoints.append(corners)
if verbose:
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (9, 6), corners, pattern_found)
cv2.imshow('img',img)
cv2.waitKey(500)
if verbose:
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
return ret, mtx, dist, rvecs, tvecs
示例14: get_calibration_points
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def get_calibration_points(images, nx, ny):
'''
Generate two lists of calibration points from a set of calibration images
of chess boards to needed for `cv2.calibrateCamera()`.
It is recommended that `images` contain at least 20 images. All images
are expected to be of identical size and to contain the same, complete
chess board pattern.
Args:
images (array-like): A list of file names of the images to be
used for calibration.
nx (int): The number of horizontal inner corners (i.e. corners where two
white and two black tiles meet) of the chess board.
ny (int): The number of vertical inner corners (i.e. corners where two
white and two black tiles meet) of the chess board.
Returns:
object_points (list): The list of 3-D object points for calibration.
image_points (list): The list of 2-D image points for calibration.
'''
image_size = []
# Arrays to store object points and image points
# of all calibration images for `cv2.calibrateCamera()`.
object_points = [] # 3-D points in real world space
image_points = [] # 2-D points in image plane.
# All calibration images are expected to contain the same calibration pattern,
# so the object points are the same for all images.
# Format: (0,0,0), (1,0,0), (2,0,0), ...., (8,5,0)
# The third coordinate is always zero as the points lie in a plane.
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)
# Step through the list and search for chess board corners
for i, fname in enumerate(images):
img = cv2.imread(fname)
size = (img.shape[1], img.shape[0])
if i == 0:
image_size = size
if size != image_size:
raise ValueError("Expected all images to have identical size, but found varying sizes.")
image_size = size
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)
# If found, add object points, image points
if ret == True:
object_points.append(objp)
image_points.append(corners)
return object_points, image_points, image_size
示例15: get_K_and_D
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import findChessboardCorners [as 別名]
def get_K_and_D(checkerboard, imgsPath):
CHECKERBOARD = checkerboard
subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
_img_shape = None
objpoints = []
imgpoints = []
images = glob.glob(imgsPath + '/*.png')
for fname in images:
img = cv2.imread(fname)
if _img_shape == None:
_img_shape = img.shape[:2]
else:
assert _img_shape == img.shape[:2], "All images must share the same size."
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD,cv2.CALIB_CB_ADAPTIVE_THRESH+cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
if ret == True:
objpoints.append(objp)
cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria)
imgpoints.append(corners)
N_OK = len(objpoints)
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
rms, _, _, _, _ = cv2.fisheye.calibrate(
objpoints,
imgpoints,
gray.shape[::-1],
K,
D,
rvecs,
tvecs,
calibration_flags,
(cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
)
DIM = _img_shape[::-1]
print("Found " + str(N_OK) + " valid images for calibration")
print("DIM=" + str(_img_shape[::-1]))
print("K=np.array(" + str(K.tolist()) + ")")
print("D=np.array(" + str(D.tolist()) + ")")
return DIM, K, D