#本節講解視頻的讀取,顯示和保存
# 1. cv2.VideoCapture()
# 有兩種用法
# cv2.VideoCapture(filename)
# filename : 要打開的視頻
# cv2.VideoCapture(device)
# device : 要打開的攝像頭,如果要打開默認攝像頭,則填 0 ,如筆記本自帶的攝像頭
import cv2
cap = cv2.VideoCapture('video_1.avi')
# 讀取視頻
# while(cap.isOpened()):
# ret, frame = cap.read()
# if ret == False:
# break
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# cv2.imshow('frame', gray)
# cv2.waitKey(10)
# k = cv2.waitKey(0)
#
# if k == 27:
# cap.release()
# cv2.destroyAllWindows()
# 保存視頻
# 1.指定 FourCC 編碼 FOURCC is short for "four character code"
# FOURCC是four character code“四個字符代碼”的縮寫
# -媒體文件中使用的視頻編解碼器,壓縮格式,顏色或像素格式的標識符。
# FourCC 就是一個4字節碼,用來確定視頻的編碼格式。
# 可用的編碼可以查看 http://www.fourcc.org/codecs.php, 推薦使用 ”XVID"
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
# def VideoWriter_fourcc(c1, c2, c3, c4): # real signature unknown; restored from __doc__
# """
# VideoWriter_fourcc(c1, c2, c3, c4) -> retval
# . @brief Concatenates 4 chars to a fourcc code
# .
# . @return a fourcc code
# .
# . This static method constructs the fourcc code of the codec to be used in the constructor
# . VideoWriter::VideoWriter or VideoWriter::open.
# """
# pass
# 2.創建一個 ViDeoWrite 對象
# VideoWriter(filename, fourcc, fps, frameSize[, isColor]) -> <VideoWriter object>
# 第一個參數是要保存的文件的路徑
# fourcc 指定編碼器
# fps 要保存的視頻的幀率
# frameSize 要保存的文件的畫面尺寸
# isColor 指示是黑白畫面還是彩色的畫面
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (960, 528), True)
# flip(src, flipCode[, dst]) -> dst
# filp函數用於圖像翻轉
# src -- 原始圖像矩陣
# dst -- 變換後矩陣
# flipCode -- 翻轉模式,有三種
# 0 : 垂直方向翻轉
# 1 : 水平方向翻轉
# 2 : 水平/垂直方向同時翻轉
while(cap.isOpened()):
ret, frame = cap.read()
# size = frame.shape
if ret == True:
frame = cv2.flip(frame, 0) #垂直方向翻轉,返回翻轉後的圖像
out.write(frame) #翻轉後的圖像寫入
cv2.imshow('frame', frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
else:
break
#釋放對象
cap.release()
out.release()
#關閉窗口
cv2.destroyAllWindows()