繁体   English   中英

如何通过 opencv python 中的网络摄像头从视频中捕获 500 张图像?

[英]How to capture a 500 images from a video through webcam in opencv python?

我正在使用以下代码从网络摄像头捕获图像。 但我只需要在点击时捕获一些图像。

 
# Opens the inbuilt camera of laptop to capture video.
cap = cv2.VideoCapture(0)
i = 0
 
while(cap.isOpened()):
    ret, frame = cap.read()
     
    # This condition prevents from infinite looping
    # incase video ends.
    if ret == False:
        break
     
    # Save Frame by Frame into disk using imwrite method
    cv2.imwrite('Frame'+str(i)+'.jpg', frame)
    i += 1
 
cap.release()
cv2.destroyAllWindows()```

假设你想要 500 张图片添加:

...
    i+=1
    if (i+1)%500==0:
        break

那很容易。 您可以使用k = cv2.waitKey(1)并检查按下了哪个按钮。 这是一个简单的例子:

import cv2


def main():
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():  # Check if the web cam is opened correctly
        print("failed to open cam")
        return -1
    else:
        print('webcam open')

    for i in range(10 ** 10):
        success, cv_frame = cap.read()
        if not success:
            print('failed to capture frame on iter {}'.format(i))
            break
        cv2.imshow('click t to save image and q to finish', cv_frame)
        k = cv2.waitKey(1)
        if k == ord('q'):
            print('q was pressed - finishing...')
            break
        elif k == ord('t'):
            print('t was pressed - saving image {}...'.format(i))
            image_path = 'Frame_{}.jpg'.format(i)  # i recommend a folder and not to save locally to avoid the mess
            cv2.imwrite(image_path, cv_frame)

    cap.release()
    cv2.destroyAllWindows()
    return


if __name__ == '__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM