一、打開攝像頭
import cv2
# 打開攝像頭並灰度化顯示 capture = cv2.VideoCapture(0) while(True): # 獲取一幀 ret, frame = capture.read() # 將這幀轉換為灰度圖 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) # 如果輸入q,則退出 if cv2.waitKey(1) == ord('q'): break
cv2.VideoCapture(0)創建VideoCapture對象,參數0表示攝像頭編號,如果你有兩個攝像頭,也可以傳入1
# 獲取捕獲的分辨率 # propId可以直接寫數字,也可以用OpenCV的符號表示 width, height = capture.get(3), capture.get(4) print(width, height) # 以原分辨率的一倍來捕獲 capture.set(cv2.CAP_PROP_FRAME_WIDTH, width * 2) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, width * 2)
640.0 480.0
我的攝像頭分辨率是640 x 480.通過cap.get(propId)可以獲取攝像頭的一些屬性。比如分辨率、亮度和對比度等。propId是從0~18的數字,我例舉幾個:
cv::VideoCaptureProperties {
cv::CAP_PROP_POS_MSEC =0,
cv::CAP_PROP_POS_FRAMES =1,
cv::CAP_PROP_POS_AVI_RATIO =2,
cv::CAP_PROP_FRAME_WIDTH =3,
cv::CAP_PROP_FRAME_HEIGHT =4,
cv::CAP_PROP_FPS =5,
cv::CAP_PROP_FOURCC =6,
cv::CAP_PROP_FRAME_COUNT =7,
cv::CAP_PROP_FORMAT =8,
cv::CAP_PROP_MODE =9,
cv::CAP_PROP_BRIGHTNESS =10,
3:高度, 4:寬度, 5:幀率, 8:格式, 9:模式。。。
想了解完整的屬性列表可以參考:
VideoCaptureProperties。
也可以使用cap.set(propId, value)來修改屬性值
二、播放本地視頻
# 播放本地視頻 capture = cv2.VideoCapture('4.視頻展台的使用視頻.mp4') while(capture.isOpened()): ret, frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(30) == ord('q'): break
和打開攝像頭一樣,把攝像頭編號換成視頻的路徑就可以播放本地視頻。cv2.waitKey的參數0表示無限等待,數值越大,視頻播放越慢,反之,則越快。通常設置25到30
三、錄制視頻
保存圖片使用的是cv2.imwrite(),要保存視頻,需要創建一個VideoWriter對象,需要傳入四個參數
- 輸出的文件名,如’output.avi’
- 編碼方式FourCC碼
- 幀率FPS
- 要保存的分辨率大小
FourCC是用來指定視頻編碼方式的四字節碼
capture = cv2.VideoCapture(0) # 定義編碼方式並創建VideoWriter對象 fourcc = cv2.VideoWriter_fourcc(*'MJPG') outfile = cv2.VideoWriter('output.avi', fourcc, 25., (640, 480)) while(capture.isOpened()): ret, frame = capture.read() if ret: outfile.write(frame) # 寫入文件 cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break else: break
四、小結
使用cv2.VideoCapture()創建視頻對象,然后在循環中一幀一陣顯示圖像
cap.get(propId)獲取視頻屬性,cap.set(propId, value)設置視頻屬性
cv2.VideoWriter()創建視頻寫入對象,用來錄制、保存視頻
參考網址:https://tianchi.aliyun.com/course/courseConsole?courseId=40992&chapterIndex=1§ionIndex=3
