1. 程式人生 > 程式設計 >python利用opencv儲存、播放視訊

python利用opencv儲存、播放視訊

程式碼已上傳至:https://gitee.com/tqbx/python-opencv/tree/master/Getting_started_videos

目標

學習讀取視訊,播放視訊,儲存視訊。
學習從相機中捕捉幀並展示。
學習cv2.VideoCapture(),cv2.VideoWriter()的使用

從相機中捕捉視訊

通過自帶攝像頭捕捉視訊,並將其轉化為灰度視訊顯示出來。

基本步驟如下:

1.首先建立一個VideoCapture物件,它的引數包含兩種:

  • 裝置索引,指定攝像機的編號。
  • 視訊檔案的名稱。

2.逐幀捕捉。

3.釋放捕捉物。

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
  print("Cannot open camera")
  exit()
while True:
  # Capture frame-by-frame
  ret,frame = cap.read()
  # if frame is read correctly ret is True
  if not ret:
    print("Can't receive frame (stream end?). Exiting ...")
    break
  # Our operations on the frame come here
  gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
  # Display the resulting frame
  cv.imshow('frame',gray)
  if cv.waitKey(1) == ord('q'):
    break
# When everything done,release the capture
cap.release()
cv.destroyAllWindows()

其他:

  • cap.read()返回布林值,如果frame讀取正確,為True,可以通過這個值判斷視訊是否已經結束。
  • 有時,cap可能會初始化捕獲失敗,可以通過cap.isOpened()來檢查其是否被初始化,如果為True那是最好,如果不是,可以使用cap.open()來嘗試開啟它。
  • 當然,你可以使用cap.get(propId)的方式獲取視訊的一些屬性,如幀的寬度,幀的高度,幀速等。propId是0-18的數字,每個數字代表一個屬性,對應關係見底部附錄。
  • 既然可以獲取,當然也可以嘗試設定,假設想要設定幀的寬度和高度為320和240:cap.set(3,320),cap.set(4,240)

從檔案中播放視訊

程式碼和從相機中捕獲視訊基本相同,不同之處在於傳入VideoCapture的引數,此時傳入視訊檔案的名稱。

在顯示每一幀的時候,可以使用cv2.waitKey()設定適當的時間,如果值很小,視訊將會很快。正常情況下,25ms就ok。

import numpy as np
import cv2

cap = cv2.VideoCapture('vtest.avi')

while(cap.isOpened()):
  ret,frame = cap.read()

  gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

  cv2.imshow('frame',gray)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

儲存視訊

1.建立一個VideoWriter 物件,指定如下引數:

  • 輸出的檔名,如output.avi。
  • FourCC code。
  • 每秒的幀數fps。
  • 幀的size。

2.FourCC code傳遞有兩種方式:

  • fourcc = cv2.VideoWriter_fourcc(*'XVID')
  • fourcc = cv2.VideoWriter_fourcc('X','V','I','D')

3.FourCC是一個用於指定視訊編解碼器的4位元組程式碼。

  • In Fedora: DIVX,XVID,MJPG,X264,WMV1,WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)
  • In Windows: DIVX (More to be tested and added)
  • In OSX : (I don't have access to OSX. Can some one fill this?)
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))

while(cap.isOpened()):
  ret,frame = cap.read()
  if ret==True:
    frame = cv2.flip(frame,0)

    # write the flipped frame
    out.write(frame)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  else:
    break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

附錄

  • CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds or video capture timestamp.
  • 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_U The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_WHITE_BALANCE_V The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_ISO_SPEED The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_BUFFERSIZE Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently)

參考閱讀

Getting Started with Videos

作者:天喬巴夏丶
出處:https://www.cnblogs.com/summerday152/
本文已收錄至Gitee:https://gitee.com/tqbx/JavaBlog
若有興趣,可以來參觀本人的個人小站:https://www.hyhwky.com

以上就是python利用opencv儲存、播放視訊的詳細內容,更多關於python opencv的資料請關注我們其它相關文章!