天天看點

python+opencv打開攝像頭,儲存視訊、拍照功能的實作

以下代碼是儲存視訊

# coding:utf-8
import cv2
import sys
reload(sys)
sys.setdefaultencoding('utf8')
cap = cv2.VideoCapture()
cap.set(,)
cap.set(,)
cap.set(, )
#此處fourcc的在MAC上有效,如果視訊儲存為空,那麼可以改一下這個參數試試, 也可以是-1
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
# 第三個參數則是鏡頭快慢的,10為正常,小于10為慢鏡頭
out = cv2.VideoWriter('/opt/code/video/output2.avi', fourcc,,(,))
while True:
    ret,frame = cap.read()
    if ret == True:
        frame = cv2.flip(frame, )
        a = out.write(frame)
        cv2.imshow("frame", frame)
        if cv2.waitKey() &  == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.destroyAllWindows()
           

以下代碼是拍照,在按q之後,儲存圖檔并退出。

import cv2

cap = cv2.VideoCapture()
while():
    # get a frame
    ret, frame = cap.read()
    # show a frame
    cv2.imshow("capture", frame)
    if cv2.waitKey() &  == ord('q'):
        cv2.imwrite("/opt/code/image/fangjian2.jpeg", frame)
        break
cap.release()
cv2.destroyAllWindows()