一段时间后,CV2开始拍摄空图像

时间:2019-05-31 06:18:13

标签: python cv2

我是python的新手,我有一个小问题。我应该在很长一段时间内使用网络摄像头每10秒拍摄一次图像。我的代码工作大约5个小时或1800张图片,然后突然间我保存的图片是空的。我不知道是什么原因导致了错误,并且我也没有收到错误消息,该skript继续运行。

我在python 2.7中使用spyder。当我重新启动内核时,我的skript再次工作了几个小时。这是我的代码:

import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'
try:
  while True:

       cam = cv2.VideoCapture(0)
       cam.set(3,1280) #set height
       cam.set(4,720) #set width
       s, im = cam.read() # captures image
    # Write date and time to image

       date_string = time.strftime("%Y-%m-%d %H:%M:%S")
       font                   = cv2.FONT_HERSHEY_SIMPLEX
       bottomLeftCornerOfText = (10,710)
       fontScale              = 1
       fontColor              = (255,255,255)
       lineType               = 2

       cv2.putText(im,date_string, 
           bottomLeftCornerOfText, 
           font, 
           fontScale,
           fontColor,
           lineType)


       temp = datetime.datetime.fromtimestamp(time.time())
       year = temp.year           
       month = temp.month
       day = temp.day
       hour = temp.hour
       minute = temp.minute
       second = temp.second

       imagename = year+'-'+month+'-'+day+'_'+hour+'-'+minute+'-   '+second+'.jpg'

         # writes image  to disk    
       cv2.imwrite(os.path.join(data_path,imagename),im)    
       cam.release()
       time.sleep(10)

finally:
  cam.release()

这是我的记忆问题吗?一张图片的大小为261KB。

1 个答案:

答案 0 :(得分:0)

硬盘已满?不知道这是否可以解决问题,但是您应该重新排列代码。无需每次都重新初始化相机:

import cv2
import time
import datetime
import os
data_path = 'V:\\Database\\Pictures'

cam = cv2.VideoCapture(0)
cam.set(3,1280) #set height
cam.set(4,720) #set width

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,710)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

while True:

    try:
        s, im = cam.read() # captures image
    except:
        # something here
        pass

    now = datetime.datetime.now()

    date_string = now.strftime("%Y-%m-%d %H:%M:%S")

    cv2.putText(im,date_string, 
        bottomLeftCornerOfText, 
        font, 
        fontScale,
        fontColor,
        lineType)

    imagename = now.strftime("%Y-%m-%d_%H-%M-%S") + '.jpg'

    # writes image  to disk    
    cv2.imwrite(os.path.join(data_path,imagename),im)    
    time.sleep(10)

cam.release()