溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python利用opencv實現保存、播放視頻

發布時間:2020-11-03 16:05:53 來源:億速云 閱讀:146 作者:Leah 欄目:開發技術

python利用opencv實現保存、播放視頻?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

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()

看完上述內容,你們掌握python利用opencv實現保存、播放視頻的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女