代码部分
#打开摄像头,将读取的视频保存在本地,名字叫output.avi# coding=utf-8
import cv2 as cv
cap = cv.VideoCapture(0)
# 检查是否成功打开摄像头
if not cap.isOpened():print("Cannot open camera")exit()
# 获取摄像头帧的宽度和高度
frame_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))# 创建VideoWriter对象,用于保存视频。参数为输出文件名、FourCC编码(例如XVID)、帧率、帧大小(宽度和高度)
output = cv.VideoWriter('output.avi', cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (frame_width, frame_height))while True:# 逐帧捕获ret, frame = cap.read()# 如果正确读取帧,ret为Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")break# 在这里进行对帧的操作,比如灰度化gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)# 显示结果帧cv.imshow('frame', frame)# 将帧写入输出视频output.write(frame)if cv.waitKey(1) == ord('q'):break
# 完成所有操作后,释放捕获器和输出视频对象
cap.release()
output.release()
cv.destroyAllWindows()
#将上面录制的视频,每隔timeF的间隔,读取一帧并以图片的形式保存在本地import numpy as np
import cv2
import os
def video2image(video_dir, save_dir):cap = cv2.VideoCapture(video_dir) # 生成读取视频对象n = 1 # 计数width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # 获取视频的宽度height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 获取视频的高度fps = cap.get(cv2.CAP_PROP_FPS) # 获取视频的帧率fourcc = int(cap.get(cv2.CAP_PROP_FOURCC)) # 视频的编码# 定义视频输出# writer = cv2.VideoWriter("video_02_result.mp4", fourcc, fps, (width, height))i = 0timeF = int(fps) # 视频帧计数间隔频率while cap.isOpened():ret, frame = cap.read() # 按帧读取视频# 到视频结尾时终止if ret is False:break# 每隔timeF帧进行存储操作if (n % timeF == 0):i += 1print('保存第 %s 张图像' % i)save_image_dir = os.path.join(save_dir, '%s.jpg' % i)print('save_image_dir: ', save_image_dir)cv2.imwrite(save_image_dir, frame) # 保存视频帧图像n = n + 1cv2.waitKey(1) # 延时1mscap.release() # 释放视频对象# 读取文件夹所有视频,每个视频按帧保存图像
def video2image_multi(video_path, save_path):video_list = os.listdir(video_path)for i in range(len(video_list)):video_dir = os.path.join(video_path, video_list[i])cap = cv2.VideoCapture(video_dir)fps = cap.get(cv2.CAP_PROP_FPS) # 视频的帧率save_num = 0n = 1 # 计数timeF = int(fps) # 视频帧计数间隔频率while cap.isOpened():ret, frame = cap.read()if ret is False:break# 每隔timeF帧进行存储操作if (n % 10 == 0):save_num += 1save_image_dir = os.path.join(save_path, '%s_%s.jpg' % (i, save_num))cv2.imwrite(save_image_dir, frame)n = n + 1cv2.waitKey(1)cap.release()print('读取第 %s 个视频完成 !!!' % i)if __name__ == '__main__':video2image(r'E:\project\python\Camera calibration\output.avi', r'E:\project\python\Camera calibration\picture')
#进行标定
#必须使用文件夹下同比例的标定图import cv2
import numpy as np
import glob
import os
# 找棋盘格角点
# 设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # 阈值
#棋盘格模板规格
w = 9 # 10 - 1
h = 6 # 7 - 1
# 世界坐标系中的棋盘格点,例如(0,0,0), (1,0,0), (2,0,0) ....,(8,5,0),去掉Z坐标,记为二维矩阵
objp = np.zeros((w*h,3), np.float32)
objp[:,:2] = np.mgrid[0:w,0:h].T.reshape(-1,2)
objp = objp*18.1 # 18.1 mm# 储存棋盘格角点的世界坐标和图像坐标对
objpoints = [] # 在世界坐标系中的三维点
imgpoints = [] # 在图像平面的二维点
#加载pic文件夹下所有的jpg图像
images = glob.glob('./picture/*.jpg') # 拍摄的十几张棋盘图片所在目录i=0
for fname in images:img = cv2.imread(fname)# 获取画面中心点#获取图像的长宽h1, w1 = img.shape[0], img.shape[1]gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)u, v = img.shape[:2]# 找到棋盘格角点ret, corners = cv2.findChessboardCorners(gray, (w,h),None)# 如果找到足够点对,将其存储起来if ret == True:print("i:", i)i = i+1# 在原角点的基础上寻找亚像素角点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))# 纠正畸变dst1 = cv2.undistort(frame, mtx, dist, None, newcameramtx)#dst2 = cv2.undistort(frame, mtx, dist, None, newcameramtx)mapx,mapy=cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w1,h1),5)dst2=cv2.remap(frame,mapx,mapy,cv2.INTER_LINEAR)# 裁剪图像,输出纠正畸变以后的图片x, y, w1, h1 = roidst1 = dst1[y:y + h1, x:x + w1]#cv2.imshow('frame',dst2)#cv2.imshow('dst1',dst1)cv2.imshow('dst2', dst2)if cv2.waitKey(1) & 0xFF == ord('q'): # 按q保存一张图片cv2.imwrite("../u4/frame.jpg", dst1)break
标定图片