OpenCV Python笔记本摄像头,视频写入以及输出

一、用摄像头直接读取外界图像并显示

import cv2 as cv

cap = cv.VideoCapture(0)  #也可以通过1选择第二个摄像头
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    ret, frame = cap.read()  #第一个参数判断是否读取到帧
    if not ret:
        print("fail")
        break
    frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)  #转换为灰色图像
    frame = cv.flip(frame, 1)  #把图像翻转,可以试试要这一句和不要的区别,参数可以改
    cv.imshow("frame", frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

二、保存摄像头拍摄的视频

import cv2 as cv

cap = cv.VideoCapture(0)
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('E:\\python opencv\\demo2\\out.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("cannot")
        break
    frame = cv.flip(frame, 1)
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
out.release()
cv.destroyAllWindows()

不能保存的时候把绝对路径加上,可能就行了

三、读取显示电脑里的视频文件

import cv2 as cv

cap = cv.VideoCapture("E:\\python opencv\\demo2\\out.avi")
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("fail")
        break
    cv.imshow('image', frame)
    if cv.waitKey(10) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

刚开始学,多做点记录,方便以后复习

你可能感兴趣的:(OpenCV学习之路)