工具库
python3.6 opencv-python
pip install opencv-python
import cv2
cap = cv2.VideoCapture(0)
cap.release()
cv2.waitKey(1)
拍照片
按space 键,拍照 按q键退出
import cv2
import time
import os
def make_photo(n=None):
"""
n:连续拍照n张
"""
cap = cv2.VideoCapture(0)
if n is None:
while True:
ret, frame = cap.read()
if ret:
cv2.imshow("picture", frame)
while True:
key = cv2.waitKey()
if key == 113:
break
elif key == 32:
label = 1
while os.path.exists("%d.png"%label):
label += 1
cv2.imwrite("%d.png"%label, frame)
continue
break
else:
count = 0
while count < n:
ret, frame = cap.read()
if ret:
cv2.imshow("picture", frame)
time.sleep(1.5)
cv2.imwrite("%d.png"%count, frame)
count += 1
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
make_photo(5)
拍视频
def make_video():
"""使用opencv录像"""
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*"DIVX")
writer = cv2.VideoWriter('video.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret:
writer.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1)&0xff == 113:
break
else:
break
cap.release()
writer.release()
cv2.destroyAllWindows()
|