0

The following code capture an image from webcam, and saves into the disk. I want to write a program which can automate capturing of an image at every 30 seconds until 12 hours. What is the best way to do that?

import cv2     
cap = cv2.VideoCapture(0)
image0 = cap.read()[1]
cv2.imwrite('image0.png', image0)

Following is the modification based on the answer from @John Zwinck, since I need also to write the image captured every 30 seconds into the disk naming with the time captured:

import time, cv2
current_time = time.time()
endtime = current_time + 12*60*60
cap = cv2.VideoCapture(0)
while current_time < endtime:    
    img = cap.read()[1]
    cv2.imwrite('img_{}.png'.format(current_time), img)
    time.sleep(30)

However, above code could write only the last file over the previous one for each time. Looking for its improvement.

Charles
  • 50,943
  • 13
  • 104
  • 142

2 Answers2

4
import time
endTime = time.time() + 12*60*60 # 12 hours from now
while time.time() < endTime:
    captureImage()
    time.sleep(30)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • I also need to write the image captured every 30 seconds naming with the time captured –  Mar 01 '14 at 15:43
  • 1
    Great, so try implementing that. This isn't a code-for-hire-for-free service. If you get stuck, by all means come back with a new question. – John Zwinck Mar 01 '14 at 15:48
  • I see you already figured out how to put the time into the filename. So you're good now? – John Zwinck Mar 01 '14 at 16:21
0

Your output image name is the same!!! In the while loop the current_time will not change, so it will save each frame with the same name. Replacing .format(current_time) to .format(time.time()) should work.

Replace

while current_time < endtime:
img = cap.read()[1] cv2.imwrite('img_{}.png'.format(current_time), img) time.sleep(30)

To cv2.imwrite('img_{}.png'.format(int(time.time())), img)

abarisone
  • 3,707
  • 11
  • 35
  • 54
LSW
  • 1