OpenCV保存讀取加載圖片和視頻

方法     描述
cv.VideoCapture()     初始化攝像頭,0開啓第一個攝像頭,1開啓第2個攝像頭,返回攝像頭對象,一般會自動打開攝像頭
cap.read()     讀取攝像頭幀,返回值1表示是否成功讀取幀,返回值2表示該幀
cv.cvtColor(frame,mode)     轉換圖片的色彩空間
cap.release()     關閉攝像頭
cap.isOpened()     檢查攝像頭是否打開
cap.open()     打開攝像頭
cap.get(propld)     獲得該幀的大小
cap.set(propld,value)     設置該幀的大小
1.從攝像頭讀取圖片

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()  
    # 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) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

2.從文件讀取視頻

import numpy as np
import cv2 as cv
cap = cv.VideoCapture('vtest.avi')
while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    cv.imshow('frame',gray)
    if cv.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

3.保存視頻

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')  # 保存視頻的編碼
out = cv.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv.flip(frame,0)
        # write the flipped frame
        out.write(frame)
        cv.imshow('frame',frame)
        if cv.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章