打开相机
import cv2
cap =cv2.VideoCapture(0,cv2.CAP_DSHOW)
#调整分辨率设置为320*240
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
while True:
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#frame = cv2.flip(frame) 用翻转摄像头
cv2.imshow('capture',frame)
if cv2.waitKey(1) == ord('q') or cv2.waitKey(1) == 27:
cv2.imwrite("test.png", frame)
break
cap.release()
cv2.destroyAllWindows()
打开相机并保存视频
import cv2
cap =cv2.VideoCapture(0,cv2.CAP_DSHOW)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('myvideo.avi',fourcc, 20.0,(640,480))
while True:
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
out.write(frame)
cv2.imshow('camera',frame)
key = cv2.waitKey(1)
if key == ord('q') or key == 27:
break
cap.release()
out.release()
cv2.destroyAllWindows()
注意VideoWriter中的分辨率要与实际读取的一致,否者会无法播放
打开视频
import cv2
cap =cv2.VideoCapture('myvideo.avi')
while True:
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
cv2.imshow('camera',frame)
key = cv2.waitKey(1)
if key == ord('q') or key == 27:
break
cap.release()
cv2.destroyAllWindows()