Python OpenCV2 - 图像返回False

时间:2017-07-19 20:19:42

标签: python python-3.x opencv

我写了一个脚本,用于在早上7点到晚上10点之间每分钟从我的网络摄像头捕获图像。但是,我遇到ret, frame = cap.read()的问题,每次都返回False。 OpenCV2的官方文档使用了类似的功能。

我在这里做错了什么?

#! python3
# -*- coding: utf-8 -*-
import os
import cv2
import sys
import time


def main():
    CurrentDir = os.getcwd()

    if int(time.strftime('%H')) < 7:
        # Captures pics only after 7 AM. Doesnt after 10 PM.

        cap = cv2.VideoCapture(0)

        while int(time.strftime('%H')) < 22:
            print('Time less than 10 PM.')
            print('Image capture begins')
            if not os.path.exists('Pics'):
                os.makedirs('Pics', exist_ok=True)
            os.chdir('Pics')

            number = 1
            while True:
                fname = "Capture_" + str(number) + ".jpg"
                if not os.path.exists(fname):
                    break
                number = number + 1

            ret, frame = cap.read()

            if ret is None:
                logging.info('Error. Unable to Switch On WebCam')

            elif ret is False:
                print("Error. Failed to get Frame")

            else:
                print('Webcam Switched on successfully')

                try:
                    img = cv2.flip(frame, 1)
                    params = [int(cv2.IMWRITE_JPEG_QUALITY), 100]
                    cv2.imwrite(fname, img, params)   # Save with Options

                    print('Image saved to File : %s' % fname)

                except Exception as e:
                    print('Error while saving: ' + str(e))

            time.sleep(60)
        else:
            print('Time more than 10 PM. No Pic captured')

        # When everything done, release the capture
        cap.release()
        cv2.destroyAllWindows()
        print('CV2 Windows Closed Successfully.')

    else:
        print('Time less than 7 AM. No Pic captured')
    os.chdir(CurrentDir)

if __name__ == '__main__':
    main()

0 个答案:

没有答案