环境要求:安装OpenCV
练习 1. 从本地读取一段视频,并获取帧数,帧率以及时长
import cv2 cap=cv2.VideoCapture('.\light.mp4') nbFrames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) wait = int(1/fps * 1000/1) duration = (nbFrames * fps) / 1000 print('Num. Frames = ',nbFrames) print('Frame Rate = ', fps, 'fps') print('Duration = ', duration, 'sec')
练习 2. 从摄像头读取视频并保存其中某一帧
首先检查摄像头权限是否打开
import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): #从摄像头读取图片 ret, frame = cap.read() #转为灰度图片 #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #显示摄像头,背景是灰度。 cv2.imshow('frame',frame) k = cv2.waitKey(10) #通过esc键退出摄像 if k == 27: cv2.destroyAllWindows() break #通过s键保存图片,并退出。 elif k==ord("s"): cv2.imwrite("C:/Users/Huawei/Desktop/EXP41/result.jpg",frame) cv2.destroyAllWindows() break # When everything done, release the capture cap.release()#释放摄像头 cv2.destroyAllWindows()#删除全部窗口
练习 3. 在 opencv 窗口实时显示高斯模糊后的(彩色)图像
在练习 2 的例子中加入 blur = cv2.GaussianBlur(frame,(0,0),5)import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): #从摄像头读取图片 ret, frame = cap.read() #转为灰度图片 #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #显示摄像头,背景是灰度。 blur = cv2.GaussianBlur(frame,(0,0),5) cv2.imshow('frame',blur) k = cv2.waitKey(10) #通过esc键退出摄像 if k == 27: cv2.destroyAllWindows() break #通过s键保存图片,并退出。 elif k==ord("s"): cv2.imwrite("C:/Users/Huawei/Desktop/EXP41/result.jpg",frame) cv2.destroyAllWindows() break # When everything done, release the capture cap.release()#释放摄像头 cv2.destroyAllWindows()#删除全部窗口
练习 4. 将视频读取到 NumPy 数组中
使用 OpenCV 可以从一个文件读取视频帧,并将其转换成 NumPy 数组。
import numpy as np import cv2 cap = cv2.VideoCapture("light.mp4") wid = int(cap.get(3)) hei = int(cap.get(4)) framerate = int(cap.get(5)) framenum = int(cap.get(7)) video = np.zeros((framenum,hei,wid,3),dtype='float16') cnt = 0 while(cap.isOpened()): a,b=cap.read() cv2.imshow('%d'%cnt, b) cv2.waitKey(20) b = b.astype('float16')/255 video[cnt]=b #print(cnt) cnt+=1电脑内存仅4GB,内存不足:
原博地址
https://blog.csdn.net/weixin_43673589





浙公网安备 33010602011771号