python3 opencv 3.0 捕捉视屏以及照片

import cv2
"""
下面是从摄像头捕捉实时流并将其写入文件的Python实现。
运行程序后 按键Q推出,按键C 进行拍照并保存到当前的路径
"""

# Create a VideoCapture object
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if not cap.isOpened():
    print("Unable to read camera feed")

# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
# 默认分辨率取决于系统。
# 我们将分辨率从float转换为整数。
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# 定义编解码器并创建VideoWriter对象。输出存储在“outpy.avi”文件中。
out = cv2.VideoWriter('outpy.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))

index = 0
while True:
    ret, frame = cap.read()
    if ret:
        # Write the frame into the file 'output.avi'
        out.write(frame)

        # Display the resulting frame
        cv2.imshow('frame', frame)

        key = cv2.waitKey(1)
        # Press Q on keyboard to stop recording
        if key & 0xFF == ord('q'):
            break
        if key & 0xFF == ord('c'):
            index += 1
            cv2.imwrite("capture_image_{}.{}".format(index, "jpg"), frame)

    # Break the loop
    else:
        break

# When everything done, release the video capture and video write objects
cap.release()
out.release()

# Closes all the frames
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/mtj66/article/details/80182150