Python OpenCV 读取图像、视频、摄像头

By qq84628151 没有评论

读取图像

import cv2

img = cv2.imread("D:/test123.png")
cv2.imshow("测试", img)
cv2.waitKey()
cv2.destroyAllWindows()

读取视频

import cv2

cap = cv2.VideoCapture("D:/3.mp4")
while True:
    ret, frame = cap.read()
    if ret == True:
        cv2.imshow("测试", frame)
        cv2.waitKey(1)
    else:
        break
cap.release()
cv2.destroyAllWindows()

读取单个摄像头

import cv2

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if ret == True:
        cv2.imshow("测试", frame)
        if cv2.waitKey(1) != -1:
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

同时采集多个摄像头

import cv2

cap = cv2.VideoCapture(0)
while True:
    cap.grab()
    ret, frame = cap.retrieve()
    if ret == True:
        cv2.imshow("测试", frame)
        if cv2.waitKey(1) != -1:
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()