ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
使用工具Python3.5, 使用库numpy;opencv 1.用摄像头捕获视频 cv2.VideoCapture() :0为默认计算机默认摄像头,1可以更换来源; ~~~ import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): #capture frame-by-frame ret , frame = cap.read() #our operation on the frame come here gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY) #display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) &0xFF ==ord('q'): #按q键退出 break #when everything done , release the capture cap.release() cv2.destroyAllWindows() ~~~ 当代码报错时,可以使用cap.isOpened()来检查是否成功初始化了,返回值是True,就没有问题,否则就要使用cap.open()。 可以使用cap.get(propId)来获取视频的一些参数信息。propId可以是0到18之间的任何数,每一个数代表一个属性,自己可以尝试一下。 其中一些值可以使用cap.set(propId,value)来修改,例如cap.get(3)和cap.get(4)来查看每一帧的宽和高,默认是640x480。我们可以使用ret=cap.set(3,320)和ret = cap.set(4,240)来把宽和高改成320x240。 2.从文件中播放视频 把设备索引号改成文件名即可。在播放每一帧时,使用cv2.waitKey()适当持续时间,一般可以设置25ms。 ~~~ import numpy as np import cv2 cap=cv2.VideoCapture('filename.avi')#文件名及格式 while(True): #capture frame-by-frame ret , frame = cap.read() #our operation on the frame come here gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY) #display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) &0xFF ==ord('q'): #按q键退出 break #when everything done , release the capture cap.release() cv2.destroyAllWindows() ~~~ 代码中尝试修改视频流的一些属性; ![](https://box.kancloud.cn/00e7b470be24d10b99bd818751917c51_458x725.jpg) ![](https://box.kancloud.cn/bfe1412f9928c24f3711d654682ee9ba_578x242.jpg) 3.保存视频 创建一个VideoWrite的对象,确定输出文件名,指定FourCC编码,播放频率和帧的大小,最后是isColor标签True为彩色。 FourCC是一个4字节码,用来确定视频的编码格式。 1.In Fedora : DIVX , XVID , MJPG , X264 , WMV1 , WMV2 XVID是最好的,MJPG是高尺寸视频,X264得到小尺寸视频 2.In Windows : DIVX 3.In OSX :不知道用什么好 设置FourCC格式时,原文里采用了cv2.VideoWriter_fourcc()这个函数,若运行程序的时候显示这个函数不存在,可以改用了cv2.cv.CV_FOURCC这个函数。 ~~~ import numpy as np import cv2 cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) # write the flipped frame out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows() ~~~