#環(huán)境:opencv 3.4.0 ? ?python 3.5.2
#讀取視頻
import cv2
cap = cv2.VideoCapture('video.avi')
#讀取攝像頭,0為攝像頭索引名挥,當(dāng)有多個攝像頭時伞矩,從0開始編號
cap = cv2.VideoCapture(0)
#從視頻或攝像頭中讀取一幀(即一張圖像),返回是否成功標(biāo)識ret(True代表成功撮慨,F(xiàn)alse代表失敗)聊倔,img為讀取的視頻幀
ret,frame = cap.read()
#完整的讀取視頻流并播放視頻流代碼
# -*- coding:utf-8 -*-
import cv2
cap = cv2.VideoCapture("video.avi")
while(1):
# 讀取視頻幀
? ? ret, frame = cap.read()
# 顯示視頻幀
? ? cv2.imshow("capture", frame)
#等候50ms,播放下一幀,或者按q鍵退出
if cv2.waitKey(50) &0xFF ==ord('q'):
? ? break
#釋放視頻流
cap.release()
#關(guān)閉所有窗口
cv2.destroyAllWindows()
#創(chuàng)建視頻流寫入對象橡伞,VideoWriter_fourcc為視頻編解碼器戚长,20為幀播放速率,(640宇植,480)為視頻幀大小
videoWriter = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc('I', '4', '2', '0'), 20, (640,480))
#向視頻文件寫入一幀
videoWriter.write(frame)
#詳解cv2.VideoWriter_fourcc對象(摘自Learning OpenCV3 Computer Vision with Python,坦白講不太懂)
#fourcc意為四字符代碼(Four-Character Codes)得封,顧名思義,該編碼由四個字符組成,下面是VideoWriter_fourcc對象一些常用的參數(shù)指郁,注意:字符順序不能弄混
#cv2.VideoWriter_fourcc('I', '4', '2', '0'),該參數(shù)是YUV編碼類型忙上,文件名后綴為.avi
#cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),該參數(shù)是MPEG-1編碼類型,文件名后綴為.avi
#cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),該參數(shù)是MPEG-4編碼類型闲坎,文件名后綴為.avi
#cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),該參數(shù)是Ogg Vorbis,文件名后綴為.ogv
#cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),該參數(shù)是Flash視頻疫粥,文件名后綴為.flv
#以下為寫視頻的完整代碼
#-*-coding:utf-8-*-
import cv2
cap = cv2.VideoCapture('./dataset/video/cap_zhihao.avi')
fps =int(cap.get(cv2.CAP_PROP_FPS))
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc('I','4','2','0'), fps, size)
ret, frame = cap.read()
while(ret):
? ? # 展示一幀
? ? cv2.imshow("capture", frame)
? ? videoWriter.write(frame)
? ? cv2.waitKey(fps)
? ? ret,frame = cap.read()
cap.release()
cv2.destroyAllWindows()