如何用OpenCV處理視頻
- 讀取視頻文件,顯示視頻,保存視頻文件
- 從攝像頭獲取並顯示視頻
1.用攝像頭捕獲視頻
為了獲取視頻,需要創建一個VideoCapature對象。其參數可以是設備的索引號,也可以是一個視頻文件。設備索引號一般筆記本自帶的攝像頭是0。之后就可以一幀一幀的捕獲視頻,但是一定要記得停止捕獲視頻
# -*- coding:utf-8 -*-
import numpy as np
import cv2
cap = cv2.VideoCapture(0)#cap僅僅是攝像頭的一個對象
while True:
ret,frame = cap.read()#一幀一幀的捕獲視頻,ret返回的是否讀取成功,frame返回的是幀
# gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#對幀的操作,這里是把彩色圖像轉為灰度圖像
# cv2.imshow('frame',gray)
cv2.imshow('frame',frame)
if cv2.waitKey(1) == ord('q'):#key值寫的太高,會導致視頻幀數很低
break
print(ret)
cap.release()
cv2.destroyAllWindows()
cap.read()返回一個布爾值,如果幀的讀取是正確的,就會返回True。可以通過檢查他的返回值來查看視頻文件是否已經到了結尾
有時候cap無法成功的初始化攝像頭,此時需要用cap.isOpened()來檢查是否初始化成功。返回值為True表示沒有問題
可以用cap.get(propId)來獲取視頻的一些參數信息。propIdし0-18的整數,具體代表視頻屬性如下
• CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
• CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
• CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
• CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
• CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
• CV_CAP_PROP_FPS Frame rate.
• CV_CAP_PROP_FOURCC 4-character code of codec.
• CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
• CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
• CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
• CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
• CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
• CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
• CV_CAP_PROP_HUE Hue of the image (only for cameras).
• CV_CAP_PROP_GAIN Gain of the image (only for cameras).
• CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
• CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
• CV_CAP_PROP_WHITE_BALANCE Currently unsupported
• CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
某些值可以用cap.set(propId,value)來修改,value是想要設置的新值
2.從文件播放視頻
把攝像頭捕獲中的0改成視頻文件就可以了。需要注意的是在播放視頻時使用cv2.waiKey()設置適當的持續時間(幀間頻率),如果設置的太低視頻會播放的很快,太大又會播的太慢,一般設為25ms即可
3.保存視頻
需要注意到地方都寫在代碼注釋里了
# -*- coding:utf-8 -*-
import numpy as np
import cv2
cap = cv2.VideoCapture(0)#cap僅僅是攝像頭的一個對象
fourcc = cv2.VideoWriter_fourcc(*'XVID')#指定編碼格式,Windows使用XVID,注意該寫法是固定的
out = cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))#定義一個視頻存儲對象,以及視頻編碼方式,幀率,視頻大小格式,最后一項設定灰度圖(默認為True彩色,但試了一下改成False視頻生成會出錯)
while (cap.isOpened()):
ret,frame = cap.read()
if ret == True:
# frame = cv2.flip(frame,0)#將圖像翻轉
out.write(frame)#保存每一幀合並成視頻
cv2.imshow('frame',frame)
if cv2.waitKey(1) == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
