import cv2
import numpy as np
height_n = 8 #棋盘宽方向格子数目
width_n = 7 #棋盘高方向格子数目
block_width = 100
checker_img = np.zeros((height_n * block_width, width_n * block_width)) #全部填充白色
black_block = np.full((block_width,block_width),255)
for row in range(height_n): #行
for col in range(width_n): #列
if (row+col)%2==0: #若行+列可被2整除,在下面操作中将色块填充黑色
row_begin = row*block_width
row_end = row_begin+block_width
col_begin = col*block_width
col_end = col_begin+block_width
checker_img[row_begin:row_end,col_begin:col_end] = black_block
cv2.imwrite("checker_board.jpg",checker_img)
cv2.imshow("checker_board",checker_img)
cv2.waitKey(0)
这里注意np.zeros(())这里要有两个括号,代表二维数组,生成效果图如下,想直接获取可以戳下面的链接~
链接: https://pan.baidu.com/s/1fSKSrf4pPVwDJaXtctYPfg
提取码: y8u5
调用摄像头并进行相机矫正,相机标定
import numpy as np
import cv2
# 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((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].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.
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print('camera not detected')
number = 0
while (cap.isOpened()):
_, frame = cap.read()
# img = cv2.imread(frame)
cv2.imshow('result', frame)
k = cv2.waitKey(1)
if k & 0xff == ord('q') or number == 10 :
break
if k & 0xff == ord('s'):
number += 1
img = frame
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (7,6),None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (7,6), corners2,ret)
cv2.imshow('img',img)
cv2.waitKey(500)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
print('ret',ret,'mtx',mtx,'dist',dist,'rvecs',rvecs,'tvecs',tvecs)
cv2.destroyAllWindows()
参考:
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html#calibration