import time
endTime = time.time() + 12*60*60 # 12 hours from now
while time.time() < endTime:
captureImage()
time.sleep(30)
Creating time lapse images in python
Question
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.
Solution
OTHER TIPS
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)